[X86] Add target combine rules for horizontal add/sub.
[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   setTargetDAGCombine(ISD::BUILD_VECTOR);
1564   if (Subtarget->is64Bit())
1565     setTargetDAGCombine(ISD::MUL);
1566   setTargetDAGCombine(ISD::XOR);
1567
1568   computeRegisterProperties();
1569
1570   // On Darwin, -Os means optimize for size without hurting performance,
1571   // do not reduce the limit.
1572   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1573   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1574   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1575   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1576   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1577   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1578   setPrefLoopAlignment(4); // 2^4 bytes.
1579
1580   // Predictable cmov don't hurt on atom because it's in-order.
1581   PredictableSelectIsExpensive = !Subtarget->isAtom();
1582
1583   setPrefFunctionAlignment(4); // 2^4 bytes.
1584 }
1585
1586 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1587   if (!VT.isVector())
1588     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1589
1590   if (Subtarget->hasAVX512())
1591     switch(VT.getVectorNumElements()) {
1592     case  8: return MVT::v8i1;
1593     case 16: return MVT::v16i1;
1594   }
1595
1596   return VT.changeVectorElementTypeToInteger();
1597 }
1598
1599 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1600 /// the desired ByVal argument alignment.
1601 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1602   if (MaxAlign == 16)
1603     return;
1604   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1605     if (VTy->getBitWidth() == 128)
1606       MaxAlign = 16;
1607   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1608     unsigned EltAlign = 0;
1609     getMaxByValAlign(ATy->getElementType(), EltAlign);
1610     if (EltAlign > MaxAlign)
1611       MaxAlign = EltAlign;
1612   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1613     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1614       unsigned EltAlign = 0;
1615       getMaxByValAlign(STy->getElementType(i), EltAlign);
1616       if (EltAlign > MaxAlign)
1617         MaxAlign = EltAlign;
1618       if (MaxAlign == 16)
1619         break;
1620     }
1621   }
1622 }
1623
1624 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1625 /// function arguments in the caller parameter area. For X86, aggregates
1626 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1627 /// are at 4-byte boundaries.
1628 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1629   if (Subtarget->is64Bit()) {
1630     // Max of 8 and alignment of type.
1631     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1632     if (TyAlign > 8)
1633       return TyAlign;
1634     return 8;
1635   }
1636
1637   unsigned Align = 4;
1638   if (Subtarget->hasSSE1())
1639     getMaxByValAlign(Ty, Align);
1640   return Align;
1641 }
1642
1643 /// getOptimalMemOpType - Returns the target specific optimal type for load
1644 /// and store operations as a result of memset, memcpy, and memmove
1645 /// lowering. If DstAlign is zero that means it's safe to destination
1646 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1647 /// means there isn't a need to check it against alignment requirement,
1648 /// probably because the source does not need to be loaded. If 'IsMemset' is
1649 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1650 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1651 /// source is constant so it does not need to be loaded.
1652 /// It returns EVT::Other if the type should be determined using generic
1653 /// target-independent logic.
1654 EVT
1655 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1656                                        unsigned DstAlign, unsigned SrcAlign,
1657                                        bool IsMemset, bool ZeroMemset,
1658                                        bool MemcpyStrSrc,
1659                                        MachineFunction &MF) const {
1660   const Function *F = MF.getFunction();
1661   if ((!IsMemset || ZeroMemset) &&
1662       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1663                                        Attribute::NoImplicitFloat)) {
1664     if (Size >= 16 &&
1665         (Subtarget->isUnalignedMemAccessFast() ||
1666          ((DstAlign == 0 || DstAlign >= 16) &&
1667           (SrcAlign == 0 || SrcAlign >= 16)))) {
1668       if (Size >= 32) {
1669         if (Subtarget->hasInt256())
1670           return MVT::v8i32;
1671         if (Subtarget->hasFp256())
1672           return MVT::v8f32;
1673       }
1674       if (Subtarget->hasSSE2())
1675         return MVT::v4i32;
1676       if (Subtarget->hasSSE1())
1677         return MVT::v4f32;
1678     } else if (!MemcpyStrSrc && Size >= 8 &&
1679                !Subtarget->is64Bit() &&
1680                Subtarget->hasSSE2()) {
1681       // Do not use f64 to lower memcpy if source is string constant. It's
1682       // better to use i32 to avoid the loads.
1683       return MVT::f64;
1684     }
1685   }
1686   if (Subtarget->is64Bit() && Size >= 8)
1687     return MVT::i64;
1688   return MVT::i32;
1689 }
1690
1691 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1692   if (VT == MVT::f32)
1693     return X86ScalarSSEf32;
1694   else if (VT == MVT::f64)
1695     return X86ScalarSSEf64;
1696   return true;
1697 }
1698
1699 bool
1700 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1701                                                  unsigned,
1702                                                  bool *Fast) const {
1703   if (Fast)
1704     *Fast = Subtarget->isUnalignedMemAccessFast();
1705   return true;
1706 }
1707
1708 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1709 /// current function.  The returned value is a member of the
1710 /// MachineJumpTableInfo::JTEntryKind enum.
1711 unsigned X86TargetLowering::getJumpTableEncoding() const {
1712   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1713   // symbol.
1714   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1715       Subtarget->isPICStyleGOT())
1716     return MachineJumpTableInfo::EK_Custom32;
1717
1718   // Otherwise, use the normal jump table encoding heuristics.
1719   return TargetLowering::getJumpTableEncoding();
1720 }
1721
1722 const MCExpr *
1723 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1724                                              const MachineBasicBlock *MBB,
1725                                              unsigned uid,MCContext &Ctx) const{
1726   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1727          Subtarget->isPICStyleGOT());
1728   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1729   // entries.
1730   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1731                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1732 }
1733
1734 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1735 /// jumptable.
1736 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1737                                                     SelectionDAG &DAG) const {
1738   if (!Subtarget->is64Bit())
1739     // This doesn't have SDLoc associated with it, but is not really the
1740     // same as a Register.
1741     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1742   return Table;
1743 }
1744
1745 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1746 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1747 /// MCExpr.
1748 const MCExpr *X86TargetLowering::
1749 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1750                              MCContext &Ctx) const {
1751   // X86-64 uses RIP relative addressing based on the jump table label.
1752   if (Subtarget->isPICStyleRIPRel())
1753     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1754
1755   // Otherwise, the reference is relative to the PIC base.
1756   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1757 }
1758
1759 // FIXME: Why this routine is here? Move to RegInfo!
1760 std::pair<const TargetRegisterClass*, uint8_t>
1761 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1762   const TargetRegisterClass *RRC = nullptr;
1763   uint8_t Cost = 1;
1764   switch (VT.SimpleTy) {
1765   default:
1766     return TargetLowering::findRepresentativeClass(VT);
1767   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1768     RRC = Subtarget->is64Bit() ?
1769       (const TargetRegisterClass*)&X86::GR64RegClass :
1770       (const TargetRegisterClass*)&X86::GR32RegClass;
1771     break;
1772   case MVT::x86mmx:
1773     RRC = &X86::VR64RegClass;
1774     break;
1775   case MVT::f32: case MVT::f64:
1776   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1777   case MVT::v4f32: case MVT::v2f64:
1778   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1779   case MVT::v4f64:
1780     RRC = &X86::VR128RegClass;
1781     break;
1782   }
1783   return std::make_pair(RRC, Cost);
1784 }
1785
1786 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1787                                                unsigned &Offset) const {
1788   if (!Subtarget->isTargetLinux())
1789     return false;
1790
1791   if (Subtarget->is64Bit()) {
1792     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1793     Offset = 0x28;
1794     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1795       AddressSpace = 256;
1796     else
1797       AddressSpace = 257;
1798   } else {
1799     // %gs:0x14 on i386
1800     Offset = 0x14;
1801     AddressSpace = 256;
1802   }
1803   return true;
1804 }
1805
1806 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1807                                             unsigned DestAS) const {
1808   assert(SrcAS != DestAS && "Expected different address spaces!");
1809
1810   return SrcAS < 256 && DestAS < 256;
1811 }
1812
1813 //===----------------------------------------------------------------------===//
1814 //               Return Value Calling Convention Implementation
1815 //===----------------------------------------------------------------------===//
1816
1817 #include "X86GenCallingConv.inc"
1818
1819 bool
1820 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1821                                   MachineFunction &MF, bool isVarArg,
1822                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1823                         LLVMContext &Context) const {
1824   SmallVector<CCValAssign, 16> RVLocs;
1825   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1826                  RVLocs, Context);
1827   return CCInfo.CheckReturn(Outs, RetCC_X86);
1828 }
1829
1830 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1831   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1832   return ScratchRegs;
1833 }
1834
1835 SDValue
1836 X86TargetLowering::LowerReturn(SDValue Chain,
1837                                CallingConv::ID CallConv, bool isVarArg,
1838                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1839                                const SmallVectorImpl<SDValue> &OutVals,
1840                                SDLoc dl, SelectionDAG &DAG) const {
1841   MachineFunction &MF = DAG.getMachineFunction();
1842   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1843
1844   SmallVector<CCValAssign, 16> RVLocs;
1845   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1846                  RVLocs, *DAG.getContext());
1847   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1848
1849   SDValue Flag;
1850   SmallVector<SDValue, 6> RetOps;
1851   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1852   // Operand #1 = Bytes To Pop
1853   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1854                    MVT::i16));
1855
1856   // Copy the result values into the output registers.
1857   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1858     CCValAssign &VA = RVLocs[i];
1859     assert(VA.isRegLoc() && "Can only return in registers!");
1860     SDValue ValToCopy = OutVals[i];
1861     EVT ValVT = ValToCopy.getValueType();
1862
1863     // Promote values to the appropriate types
1864     if (VA.getLocInfo() == CCValAssign::SExt)
1865       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1866     else if (VA.getLocInfo() == CCValAssign::ZExt)
1867       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1868     else if (VA.getLocInfo() == CCValAssign::AExt)
1869       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1870     else if (VA.getLocInfo() == CCValAssign::BCvt)
1871       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1872
1873     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1874            "Unexpected FP-extend for return value.");  
1875
1876     // If this is x86-64, and we disabled SSE, we can't return FP values,
1877     // or SSE or MMX vectors.
1878     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1879          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1880           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1881       report_fatal_error("SSE register return with SSE disabled");
1882     }
1883     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1884     // llvm-gcc has never done it right and no one has noticed, so this
1885     // should be OK for now.
1886     if (ValVT == MVT::f64 &&
1887         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1888       report_fatal_error("SSE2 register return with SSE2 disabled");
1889
1890     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1891     // the RET instruction and handled by the FP Stackifier.
1892     if (VA.getLocReg() == X86::ST0 ||
1893         VA.getLocReg() == X86::ST1) {
1894       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1895       // change the value to the FP stack register class.
1896       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1897         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1898       RetOps.push_back(ValToCopy);
1899       // Don't emit a copytoreg.
1900       continue;
1901     }
1902
1903     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1904     // which is returned in RAX / RDX.
1905     if (Subtarget->is64Bit()) {
1906       if (ValVT == MVT::x86mmx) {
1907         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1908           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1909           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1910                                   ValToCopy);
1911           // If we don't have SSE2 available, convert to v4f32 so the generated
1912           // register is legal.
1913           if (!Subtarget->hasSSE2())
1914             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1915         }
1916       }
1917     }
1918
1919     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1920     Flag = Chain.getValue(1);
1921     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1922   }
1923
1924   // The x86-64 ABIs require that for returning structs by value we copy
1925   // the sret argument into %rax/%eax (depending on ABI) for the return.
1926   // Win32 requires us to put the sret argument to %eax as well.
1927   // We saved the argument into a virtual register in the entry block,
1928   // so now we copy the value out and into %rax/%eax.
1929   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1930       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1931     MachineFunction &MF = DAG.getMachineFunction();
1932     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1933     unsigned Reg = FuncInfo->getSRetReturnReg();
1934     assert(Reg &&
1935            "SRetReturnReg should have been set in LowerFormalArguments().");
1936     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1937
1938     unsigned RetValReg
1939         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1940           X86::RAX : X86::EAX;
1941     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1942     Flag = Chain.getValue(1);
1943
1944     // RAX/EAX now acts like a return value.
1945     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1946   }
1947
1948   RetOps[0] = Chain;  // Update chain.
1949
1950   // Add the flag if we have it.
1951   if (Flag.getNode())
1952     RetOps.push_back(Flag);
1953
1954   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1955 }
1956
1957 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1958   if (N->getNumValues() != 1)
1959     return false;
1960   if (!N->hasNUsesOfValue(1, 0))
1961     return false;
1962
1963   SDValue TCChain = Chain;
1964   SDNode *Copy = *N->use_begin();
1965   if (Copy->getOpcode() == ISD::CopyToReg) {
1966     // If the copy has a glue operand, we conservatively assume it isn't safe to
1967     // perform a tail call.
1968     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1969       return false;
1970     TCChain = Copy->getOperand(0);
1971   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1972     return false;
1973
1974   bool HasRet = false;
1975   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1976        UI != UE; ++UI) {
1977     if (UI->getOpcode() != X86ISD::RET_FLAG)
1978       return false;
1979     HasRet = true;
1980   }
1981
1982   if (!HasRet)
1983     return false;
1984
1985   Chain = TCChain;
1986   return true;
1987 }
1988
1989 MVT
1990 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1991                                             ISD::NodeType ExtendKind) const {
1992   MVT ReturnMVT;
1993   // TODO: Is this also valid on 32-bit?
1994   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1995     ReturnMVT = MVT::i8;
1996   else
1997     ReturnMVT = MVT::i32;
1998
1999   MVT MinVT = getRegisterType(ReturnMVT);
2000   return VT.bitsLT(MinVT) ? MinVT : VT;
2001 }
2002
2003 /// LowerCallResult - Lower the result values of a call into the
2004 /// appropriate copies out of appropriate physical registers.
2005 ///
2006 SDValue
2007 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2008                                    CallingConv::ID CallConv, bool isVarArg,
2009                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2010                                    SDLoc dl, SelectionDAG &DAG,
2011                                    SmallVectorImpl<SDValue> &InVals) const {
2012
2013   // Assign locations to each value returned by this call.
2014   SmallVector<CCValAssign, 16> RVLocs;
2015   bool Is64Bit = Subtarget->is64Bit();
2016   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2017                  getTargetMachine(), RVLocs, *DAG.getContext());
2018   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2019
2020   // Copy all of the result registers out of their specified physreg.
2021   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2022     CCValAssign &VA = RVLocs[i];
2023     EVT CopyVT = VA.getValVT();
2024
2025     // If this is x86-64, and we disabled SSE, we can't return FP values
2026     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2027         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2028       report_fatal_error("SSE register return with SSE disabled");
2029     }
2030
2031     SDValue Val;
2032
2033     // If this is a call to a function that returns an fp value on the floating
2034     // point stack, we must guarantee the value is popped from the stack, so
2035     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2036     // if the return value is not used. We use the FpPOP_RETVAL instruction
2037     // instead.
2038     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2039       // If we prefer to use the value in xmm registers, copy it out as f80 and
2040       // use a truncate to move it from fp stack reg to xmm reg.
2041       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2042       SDValue Ops[] = { Chain, InFlag };
2043       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2044                                          MVT::Other, MVT::Glue, Ops), 1);
2045       Val = Chain.getValue(0);
2046
2047       // Round the f80 to the right size, which also moves it to the appropriate
2048       // xmm register.
2049       if (CopyVT != VA.getValVT())
2050         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2051                           // This truncation won't change the value.
2052                           DAG.getIntPtrConstant(1));
2053     } else {
2054       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2055                                  CopyVT, InFlag).getValue(1);
2056       Val = Chain.getValue(0);
2057     }
2058     InFlag = Chain.getValue(2);
2059     InVals.push_back(Val);
2060   }
2061
2062   return Chain;
2063 }
2064
2065 //===----------------------------------------------------------------------===//
2066 //                C & StdCall & Fast Calling Convention implementation
2067 //===----------------------------------------------------------------------===//
2068 //  StdCall calling convention seems to be standard for many Windows' API
2069 //  routines and around. It differs from C calling convention just a little:
2070 //  callee should clean up the stack, not caller. Symbols should be also
2071 //  decorated in some fancy way :) It doesn't support any vector arguments.
2072 //  For info on fast calling convention see Fast Calling Convention (tail call)
2073 //  implementation LowerX86_32FastCCCallTo.
2074
2075 /// CallIsStructReturn - Determines whether a call uses struct return
2076 /// semantics.
2077 enum StructReturnType {
2078   NotStructReturn,
2079   RegStructReturn,
2080   StackStructReturn
2081 };
2082 static StructReturnType
2083 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2084   if (Outs.empty())
2085     return NotStructReturn;
2086
2087   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2088   if (!Flags.isSRet())
2089     return NotStructReturn;
2090   if (Flags.isInReg())
2091     return RegStructReturn;
2092   return StackStructReturn;
2093 }
2094
2095 /// ArgsAreStructReturn - Determines whether a function uses struct
2096 /// return semantics.
2097 static StructReturnType
2098 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2099   if (Ins.empty())
2100     return NotStructReturn;
2101
2102   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2103   if (!Flags.isSRet())
2104     return NotStructReturn;
2105   if (Flags.isInReg())
2106     return RegStructReturn;
2107   return StackStructReturn;
2108 }
2109
2110 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2111 /// by "Src" to address "Dst" with size and alignment information specified by
2112 /// the specific parameter attribute. The copy will be passed as a byval
2113 /// function parameter.
2114 static SDValue
2115 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2116                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2117                           SDLoc dl) {
2118   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2119
2120   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2121                        /*isVolatile*/false, /*AlwaysInline=*/true,
2122                        MachinePointerInfo(), MachinePointerInfo());
2123 }
2124
2125 /// IsTailCallConvention - Return true if the calling convention is one that
2126 /// supports tail call optimization.
2127 static bool IsTailCallConvention(CallingConv::ID CC) {
2128   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2129           CC == CallingConv::HiPE);
2130 }
2131
2132 /// \brief Return true if the calling convention is a C calling convention.
2133 static bool IsCCallConvention(CallingConv::ID CC) {
2134   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2135           CC == CallingConv::X86_64_SysV);
2136 }
2137
2138 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2139   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2140     return false;
2141
2142   CallSite CS(CI);
2143   CallingConv::ID CalleeCC = CS.getCallingConv();
2144   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2145     return false;
2146
2147   return true;
2148 }
2149
2150 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2151 /// a tailcall target by changing its ABI.
2152 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2153                                    bool GuaranteedTailCallOpt) {
2154   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2155 }
2156
2157 SDValue
2158 X86TargetLowering::LowerMemArgument(SDValue Chain,
2159                                     CallingConv::ID CallConv,
2160                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2161                                     SDLoc dl, SelectionDAG &DAG,
2162                                     const CCValAssign &VA,
2163                                     MachineFrameInfo *MFI,
2164                                     unsigned i) const {
2165   // Create the nodes corresponding to a load from this parameter slot.
2166   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2167   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2168                               getTargetMachine().Options.GuaranteedTailCallOpt);
2169   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2170   EVT ValVT;
2171
2172   // If value is passed by pointer we have address passed instead of the value
2173   // itself.
2174   if (VA.getLocInfo() == CCValAssign::Indirect)
2175     ValVT = VA.getLocVT();
2176   else
2177     ValVT = VA.getValVT();
2178
2179   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2180   // changed with more analysis.
2181   // In case of tail call optimization mark all arguments mutable. Since they
2182   // could be overwritten by lowering of arguments in case of a tail call.
2183   if (Flags.isByVal()) {
2184     unsigned Bytes = Flags.getByValSize();
2185     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2186     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2187     return DAG.getFrameIndex(FI, getPointerTy());
2188   } else {
2189     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2190                                     VA.getLocMemOffset(), isImmutable);
2191     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2192     return DAG.getLoad(ValVT, dl, Chain, FIN,
2193                        MachinePointerInfo::getFixedStack(FI),
2194                        false, false, false, 0);
2195   }
2196 }
2197
2198 SDValue
2199 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2200                                         CallingConv::ID CallConv,
2201                                         bool isVarArg,
2202                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2203                                         SDLoc dl,
2204                                         SelectionDAG &DAG,
2205                                         SmallVectorImpl<SDValue> &InVals)
2206                                           const {
2207   MachineFunction &MF = DAG.getMachineFunction();
2208   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2209
2210   const Function* Fn = MF.getFunction();
2211   if (Fn->hasExternalLinkage() &&
2212       Subtarget->isTargetCygMing() &&
2213       Fn->getName() == "main")
2214     FuncInfo->setForceFramePointer(true);
2215
2216   MachineFrameInfo *MFI = MF.getFrameInfo();
2217   bool Is64Bit = Subtarget->is64Bit();
2218   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2219
2220   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2221          "Var args not supported with calling convention fastcc, ghc or hipe");
2222
2223   // Assign locations to all of the incoming arguments.
2224   SmallVector<CCValAssign, 16> ArgLocs;
2225   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2226                  ArgLocs, *DAG.getContext());
2227
2228   // Allocate shadow area for Win64
2229   if (IsWin64)
2230     CCInfo.AllocateStack(32, 8);
2231
2232   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2233
2234   unsigned LastVal = ~0U;
2235   SDValue ArgValue;
2236   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2237     CCValAssign &VA = ArgLocs[i];
2238     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2239     // places.
2240     assert(VA.getValNo() != LastVal &&
2241            "Don't support value assigned to multiple locs yet");
2242     (void)LastVal;
2243     LastVal = VA.getValNo();
2244
2245     if (VA.isRegLoc()) {
2246       EVT RegVT = VA.getLocVT();
2247       const TargetRegisterClass *RC;
2248       if (RegVT == MVT::i32)
2249         RC = &X86::GR32RegClass;
2250       else if (Is64Bit && RegVT == MVT::i64)
2251         RC = &X86::GR64RegClass;
2252       else if (RegVT == MVT::f32)
2253         RC = &X86::FR32RegClass;
2254       else if (RegVT == MVT::f64)
2255         RC = &X86::FR64RegClass;
2256       else if (RegVT.is512BitVector())
2257         RC = &X86::VR512RegClass;
2258       else if (RegVT.is256BitVector())
2259         RC = &X86::VR256RegClass;
2260       else if (RegVT.is128BitVector())
2261         RC = &X86::VR128RegClass;
2262       else if (RegVT == MVT::x86mmx)
2263         RC = &X86::VR64RegClass;
2264       else if (RegVT == MVT::i1)
2265         RC = &X86::VK1RegClass;
2266       else if (RegVT == MVT::v8i1)
2267         RC = &X86::VK8RegClass;
2268       else if (RegVT == MVT::v16i1)
2269         RC = &X86::VK16RegClass;
2270       else
2271         llvm_unreachable("Unknown argument type!");
2272
2273       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2274       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2275
2276       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2277       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2278       // right size.
2279       if (VA.getLocInfo() == CCValAssign::SExt)
2280         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2281                                DAG.getValueType(VA.getValVT()));
2282       else if (VA.getLocInfo() == CCValAssign::ZExt)
2283         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2284                                DAG.getValueType(VA.getValVT()));
2285       else if (VA.getLocInfo() == CCValAssign::BCvt)
2286         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2287
2288       if (VA.isExtInLoc()) {
2289         // Handle MMX values passed in XMM regs.
2290         if (RegVT.isVector())
2291           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2292         else
2293           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2294       }
2295     } else {
2296       assert(VA.isMemLoc());
2297       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2298     }
2299
2300     // If value is passed via pointer - do a load.
2301     if (VA.getLocInfo() == CCValAssign::Indirect)
2302       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2303                              MachinePointerInfo(), false, false, false, 0);
2304
2305     InVals.push_back(ArgValue);
2306   }
2307
2308   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2309     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310       // The x86-64 ABIs require that for returning structs by value we copy
2311       // the sret argument into %rax/%eax (depending on ABI) for the return.
2312       // Win32 requires us to put the sret argument to %eax as well.
2313       // Save the argument into a virtual register so that we can access it
2314       // from the return points.
2315       if (Ins[i].Flags.isSRet()) {
2316         unsigned Reg = FuncInfo->getSRetReturnReg();
2317         if (!Reg) {
2318           MVT PtrTy = getPointerTy();
2319           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2320           FuncInfo->setSRetReturnReg(Reg);
2321         }
2322         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2323         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2324         break;
2325       }
2326     }
2327   }
2328
2329   unsigned StackSize = CCInfo.getNextStackOffset();
2330   // Align stack specially for tail calls.
2331   if (FuncIsMadeTailCallSafe(CallConv,
2332                              MF.getTarget().Options.GuaranteedTailCallOpt))
2333     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2334
2335   // If the function takes variable number of arguments, make a frame index for
2336   // the start of the first vararg value... for expansion of llvm.va_start.
2337   if (isVarArg) {
2338     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2339                     CallConv != CallingConv::X86_ThisCall)) {
2340       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2341     }
2342     if (Is64Bit) {
2343       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2344
2345       // FIXME: We should really autogenerate these arrays
2346       static const MCPhysReg GPR64ArgRegsWin64[] = {
2347         X86::RCX, X86::RDX, X86::R8,  X86::R9
2348       };
2349       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2350         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2351       };
2352       static const MCPhysReg XMMArgRegs64Bit[] = {
2353         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2354         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2355       };
2356       const MCPhysReg *GPR64ArgRegs;
2357       unsigned NumXMMRegs = 0;
2358
2359       if (IsWin64) {
2360         // The XMM registers which might contain var arg parameters are shadowed
2361         // in their paired GPR.  So we only need to save the GPR to their home
2362         // slots.
2363         TotalNumIntRegs = 4;
2364         GPR64ArgRegs = GPR64ArgRegsWin64;
2365       } else {
2366         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2367         GPR64ArgRegs = GPR64ArgRegs64Bit;
2368
2369         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2370                                                 TotalNumXMMRegs);
2371       }
2372       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2373                                                        TotalNumIntRegs);
2374
2375       bool NoImplicitFloatOps = Fn->getAttributes().
2376         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2377       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2378              "SSE register cannot be used when SSE is disabled!");
2379       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2380                NoImplicitFloatOps) &&
2381              "SSE register cannot be used when SSE is disabled!");
2382       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2383           !Subtarget->hasSSE1())
2384         // Kernel mode asks for SSE to be disabled, so don't push them
2385         // on the stack.
2386         TotalNumXMMRegs = 0;
2387
2388       if (IsWin64) {
2389         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2390         // Get to the caller-allocated home save location.  Add 8 to account
2391         // for the return address.
2392         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2393         FuncInfo->setRegSaveFrameIndex(
2394           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2395         // Fixup to set vararg frame on shadow area (4 x i64).
2396         if (NumIntRegs < 4)
2397           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2398       } else {
2399         // For X86-64, if there are vararg parameters that are passed via
2400         // registers, then we must store them to their spots on the stack so
2401         // they may be loaded by deferencing the result of va_next.
2402         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2403         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2404         FuncInfo->setRegSaveFrameIndex(
2405           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2406                                false));
2407       }
2408
2409       // Store the integer parameter registers.
2410       SmallVector<SDValue, 8> MemOps;
2411       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2412                                         getPointerTy());
2413       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2414       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2415         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2416                                   DAG.getIntPtrConstant(Offset));
2417         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2418                                      &X86::GR64RegClass);
2419         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2420         SDValue Store =
2421           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2422                        MachinePointerInfo::getFixedStack(
2423                          FuncInfo->getRegSaveFrameIndex(), Offset),
2424                        false, false, 0);
2425         MemOps.push_back(Store);
2426         Offset += 8;
2427       }
2428
2429       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2430         // Now store the XMM (fp + vector) parameter registers.
2431         SmallVector<SDValue, 11> SaveXMMOps;
2432         SaveXMMOps.push_back(Chain);
2433
2434         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2435         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2436         SaveXMMOps.push_back(ALVal);
2437
2438         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2439                                FuncInfo->getRegSaveFrameIndex()));
2440         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2441                                FuncInfo->getVarArgsFPOffset()));
2442
2443         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2444           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2445                                        &X86::VR128RegClass);
2446           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2447           SaveXMMOps.push_back(Val);
2448         }
2449         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2450                                      MVT::Other, SaveXMMOps));
2451       }
2452
2453       if (!MemOps.empty())
2454         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2455     }
2456   }
2457
2458   // Some CCs need callee pop.
2459   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2460                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2461     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2462   } else {
2463     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2464     // If this is an sret function, the return should pop the hidden pointer.
2465     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2466         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2467         argsAreStructReturn(Ins) == StackStructReturn)
2468       FuncInfo->setBytesToPopOnReturn(4);
2469   }
2470
2471   if (!Is64Bit) {
2472     // RegSaveFrameIndex is X86-64 only.
2473     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2474     if (CallConv == CallingConv::X86_FastCall ||
2475         CallConv == CallingConv::X86_ThisCall)
2476       // fastcc functions can't have varargs.
2477       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2478   }
2479
2480   FuncInfo->setArgumentStackSize(StackSize);
2481
2482   return Chain;
2483 }
2484
2485 SDValue
2486 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2487                                     SDValue StackPtr, SDValue Arg,
2488                                     SDLoc dl, SelectionDAG &DAG,
2489                                     const CCValAssign &VA,
2490                                     ISD::ArgFlagsTy Flags) const {
2491   unsigned LocMemOffset = VA.getLocMemOffset();
2492   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2493   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2494   if (Flags.isByVal())
2495     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2496
2497   return DAG.getStore(Chain, dl, Arg, PtrOff,
2498                       MachinePointerInfo::getStack(LocMemOffset),
2499                       false, false, 0);
2500 }
2501
2502 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2503 /// optimization is performed and it is required.
2504 SDValue
2505 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2506                                            SDValue &OutRetAddr, SDValue Chain,
2507                                            bool IsTailCall, bool Is64Bit,
2508                                            int FPDiff, SDLoc dl) const {
2509   // Adjust the Return address stack slot.
2510   EVT VT = getPointerTy();
2511   OutRetAddr = getReturnAddressFrameIndex(DAG);
2512
2513   // Load the "old" Return address.
2514   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2515                            false, false, false, 0);
2516   return SDValue(OutRetAddr.getNode(), 1);
2517 }
2518
2519 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2520 /// optimization is performed and it is required (FPDiff!=0).
2521 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2522                                         SDValue Chain, SDValue RetAddrFrIdx,
2523                                         EVT PtrVT, unsigned SlotSize,
2524                                         int FPDiff, SDLoc dl) {
2525   // Store the return address to the appropriate stack slot.
2526   if (!FPDiff) return Chain;
2527   // Calculate the new stack slot for the return address.
2528   int NewReturnAddrFI =
2529     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2530                                          false);
2531   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2532   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2533                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2534                        false, false, 0);
2535   return Chain;
2536 }
2537
2538 SDValue
2539 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2540                              SmallVectorImpl<SDValue> &InVals) const {
2541   SelectionDAG &DAG                     = CLI.DAG;
2542   SDLoc &dl                             = CLI.DL;
2543   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2544   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2545   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2546   SDValue Chain                         = CLI.Chain;
2547   SDValue Callee                        = CLI.Callee;
2548   CallingConv::ID CallConv              = CLI.CallConv;
2549   bool &isTailCall                      = CLI.IsTailCall;
2550   bool isVarArg                         = CLI.IsVarArg;
2551
2552   MachineFunction &MF = DAG.getMachineFunction();
2553   bool Is64Bit        = Subtarget->is64Bit();
2554   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2555   StructReturnType SR = callIsStructReturn(Outs);
2556   bool IsSibcall      = false;
2557
2558   if (MF.getTarget().Options.DisableTailCalls)
2559     isTailCall = false;
2560
2561   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2562   if (IsMustTail) {
2563     // Force this to be a tail call.  The verifier rules are enough to ensure
2564     // that we can lower this successfully without moving the return address
2565     // around.
2566     isTailCall = true;
2567   } else if (isTailCall) {
2568     // Check if it's really possible to do a tail call.
2569     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2570                     isVarArg, SR != NotStructReturn,
2571                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2572                     Outs, OutVals, Ins, DAG);
2573
2574     // Sibcalls are automatically detected tailcalls which do not require
2575     // ABI changes.
2576     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2577       IsSibcall = true;
2578
2579     if (isTailCall)
2580       ++NumTailCalls;
2581   }
2582
2583   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2584          "Var args not supported with calling convention fastcc, ghc or hipe");
2585
2586   // Analyze operands of the call, assigning locations to each operand.
2587   SmallVector<CCValAssign, 16> ArgLocs;
2588   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2589                  ArgLocs, *DAG.getContext());
2590
2591   // Allocate shadow area for Win64
2592   if (IsWin64)
2593     CCInfo.AllocateStack(32, 8);
2594
2595   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2596
2597   // Get a count of how many bytes are to be pushed on the stack.
2598   unsigned NumBytes = CCInfo.getNextStackOffset();
2599   if (IsSibcall)
2600     // This is a sibcall. The memory operands are available in caller's
2601     // own caller's stack.
2602     NumBytes = 0;
2603   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2604            IsTailCallConvention(CallConv))
2605     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2606
2607   int FPDiff = 0;
2608   if (isTailCall && !IsSibcall && !IsMustTail) {
2609     // Lower arguments at fp - stackoffset + fpdiff.
2610     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2611     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2612
2613     FPDiff = NumBytesCallerPushed - NumBytes;
2614
2615     // Set the delta of movement of the returnaddr stackslot.
2616     // But only set if delta is greater than previous delta.
2617     if (FPDiff < X86Info->getTCReturnAddrDelta())
2618       X86Info->setTCReturnAddrDelta(FPDiff);
2619   }
2620
2621   unsigned NumBytesToPush = NumBytes;
2622   unsigned NumBytesToPop = NumBytes;
2623
2624   // If we have an inalloca argument, all stack space has already been allocated
2625   // for us and be right at the top of the stack.  We don't support multiple
2626   // arguments passed in memory when using inalloca.
2627   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2628     NumBytesToPush = 0;
2629     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2630            "an inalloca argument must be the only memory argument");
2631   }
2632
2633   if (!IsSibcall)
2634     Chain = DAG.getCALLSEQ_START(
2635         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2636
2637   SDValue RetAddrFrIdx;
2638   // Load return address for tail calls.
2639   if (isTailCall && FPDiff)
2640     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2641                                     Is64Bit, FPDiff, dl);
2642
2643   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2644   SmallVector<SDValue, 8> MemOpChains;
2645   SDValue StackPtr;
2646
2647   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2648   // of tail call optimization arguments are handle later.
2649   const X86RegisterInfo *RegInfo =
2650     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2651   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2652     // Skip inalloca arguments, they have already been written.
2653     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2654     if (Flags.isInAlloca())
2655       continue;
2656
2657     CCValAssign &VA = ArgLocs[i];
2658     EVT RegVT = VA.getLocVT();
2659     SDValue Arg = OutVals[i];
2660     bool isByVal = Flags.isByVal();
2661
2662     // Promote the value if needed.
2663     switch (VA.getLocInfo()) {
2664     default: llvm_unreachable("Unknown loc info!");
2665     case CCValAssign::Full: break;
2666     case CCValAssign::SExt:
2667       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2668       break;
2669     case CCValAssign::ZExt:
2670       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2671       break;
2672     case CCValAssign::AExt:
2673       if (RegVT.is128BitVector()) {
2674         // Special case: passing MMX values in XMM registers.
2675         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2676         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2677         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2678       } else
2679         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2680       break;
2681     case CCValAssign::BCvt:
2682       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2683       break;
2684     case CCValAssign::Indirect: {
2685       // Store the argument.
2686       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2687       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2688       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2689                            MachinePointerInfo::getFixedStack(FI),
2690                            false, false, 0);
2691       Arg = SpillSlot;
2692       break;
2693     }
2694     }
2695
2696     if (VA.isRegLoc()) {
2697       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2698       if (isVarArg && IsWin64) {
2699         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2700         // shadow reg if callee is a varargs function.
2701         unsigned ShadowReg = 0;
2702         switch (VA.getLocReg()) {
2703         case X86::XMM0: ShadowReg = X86::RCX; break;
2704         case X86::XMM1: ShadowReg = X86::RDX; break;
2705         case X86::XMM2: ShadowReg = X86::R8; break;
2706         case X86::XMM3: ShadowReg = X86::R9; break;
2707         }
2708         if (ShadowReg)
2709           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2710       }
2711     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2712       assert(VA.isMemLoc());
2713       if (!StackPtr.getNode())
2714         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2715                                       getPointerTy());
2716       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2717                                              dl, DAG, VA, Flags));
2718     }
2719   }
2720
2721   if (!MemOpChains.empty())
2722     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2723
2724   if (Subtarget->isPICStyleGOT()) {
2725     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2726     // GOT pointer.
2727     if (!isTailCall) {
2728       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2729                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2730     } else {
2731       // If we are tail calling and generating PIC/GOT style code load the
2732       // address of the callee into ECX. The value in ecx is used as target of
2733       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2734       // for tail calls on PIC/GOT architectures. Normally we would just put the
2735       // address of GOT into ebx and then call target@PLT. But for tail calls
2736       // ebx would be restored (since ebx is callee saved) before jumping to the
2737       // target@PLT.
2738
2739       // Note: The actual moving to ECX is done further down.
2740       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2741       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2742           !G->getGlobal()->hasProtectedVisibility())
2743         Callee = LowerGlobalAddress(Callee, DAG);
2744       else if (isa<ExternalSymbolSDNode>(Callee))
2745         Callee = LowerExternalSymbol(Callee, DAG);
2746     }
2747   }
2748
2749   if (Is64Bit && isVarArg && !IsWin64) {
2750     // From AMD64 ABI document:
2751     // For calls that may call functions that use varargs or stdargs
2752     // (prototype-less calls or calls to functions containing ellipsis (...) in
2753     // the declaration) %al is used as hidden argument to specify the number
2754     // of SSE registers used. The contents of %al do not need to match exactly
2755     // the number of registers, but must be an ubound on the number of SSE
2756     // registers used and is in the range 0 - 8 inclusive.
2757
2758     // Count the number of XMM registers allocated.
2759     static const MCPhysReg XMMArgRegs[] = {
2760       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2761       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2762     };
2763     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2764     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2765            && "SSE registers cannot be used when SSE is disabled");
2766
2767     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2768                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2769   }
2770
2771   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2772   // don't need this because the eligibility check rejects calls that require
2773   // shuffling arguments passed in memory.
2774   if (!IsSibcall && isTailCall) {
2775     // Force all the incoming stack arguments to be loaded from the stack
2776     // before any new outgoing arguments are stored to the stack, because the
2777     // outgoing stack slots may alias the incoming argument stack slots, and
2778     // the alias isn't otherwise explicit. This is slightly more conservative
2779     // than necessary, because it means that each store effectively depends
2780     // on every argument instead of just those arguments it would clobber.
2781     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2782
2783     SmallVector<SDValue, 8> MemOpChains2;
2784     SDValue FIN;
2785     int FI = 0;
2786     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2787       CCValAssign &VA = ArgLocs[i];
2788       if (VA.isRegLoc())
2789         continue;
2790       assert(VA.isMemLoc());
2791       SDValue Arg = OutVals[i];
2792       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2793       // Skip inalloca arguments.  They don't require any work.
2794       if (Flags.isInAlloca())
2795         continue;
2796       // Create frame index.
2797       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2798       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2799       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2800       FIN = DAG.getFrameIndex(FI, getPointerTy());
2801
2802       if (Flags.isByVal()) {
2803         // Copy relative to framepointer.
2804         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2805         if (!StackPtr.getNode())
2806           StackPtr = DAG.getCopyFromReg(Chain, dl,
2807                                         RegInfo->getStackRegister(),
2808                                         getPointerTy());
2809         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2810
2811         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2812                                                          ArgChain,
2813                                                          Flags, DAG, dl));
2814       } else {
2815         // Store relative to framepointer.
2816         MemOpChains2.push_back(
2817           DAG.getStore(ArgChain, dl, Arg, FIN,
2818                        MachinePointerInfo::getFixedStack(FI),
2819                        false, false, 0));
2820       }
2821     }
2822
2823     if (!MemOpChains2.empty())
2824       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2825
2826     // Store the return address to the appropriate stack slot.
2827     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2828                                      getPointerTy(), RegInfo->getSlotSize(),
2829                                      FPDiff, dl);
2830   }
2831
2832   // Build a sequence of copy-to-reg nodes chained together with token chain
2833   // and flag operands which copy the outgoing args into registers.
2834   SDValue InFlag;
2835   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2836     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2837                              RegsToPass[i].second, InFlag);
2838     InFlag = Chain.getValue(1);
2839   }
2840
2841   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2842     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2843     // In the 64-bit large code model, we have to make all calls
2844     // through a register, since the call instruction's 32-bit
2845     // pc-relative offset may not be large enough to hold the whole
2846     // address.
2847   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2848     // If the callee is a GlobalAddress node (quite common, every direct call
2849     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2850     // it.
2851
2852     // We should use extra load for direct calls to dllimported functions in
2853     // non-JIT mode.
2854     const GlobalValue *GV = G->getGlobal();
2855     if (!GV->hasDLLImportStorageClass()) {
2856       unsigned char OpFlags = 0;
2857       bool ExtraLoad = false;
2858       unsigned WrapperKind = ISD::DELETED_NODE;
2859
2860       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2861       // external symbols most go through the PLT in PIC mode.  If the symbol
2862       // has hidden or protected visibility, or if it is static or local, then
2863       // we don't need to use the PLT - we can directly call it.
2864       if (Subtarget->isTargetELF() &&
2865           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2866           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2867         OpFlags = X86II::MO_PLT;
2868       } else if (Subtarget->isPICStyleStubAny() &&
2869                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2870                  (!Subtarget->getTargetTriple().isMacOSX() ||
2871                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2872         // PC-relative references to external symbols should go through $stub,
2873         // unless we're building with the leopard linker or later, which
2874         // automatically synthesizes these stubs.
2875         OpFlags = X86II::MO_DARWIN_STUB;
2876       } else if (Subtarget->isPICStyleRIPRel() &&
2877                  isa<Function>(GV) &&
2878                  cast<Function>(GV)->getAttributes().
2879                    hasAttribute(AttributeSet::FunctionIndex,
2880                                 Attribute::NonLazyBind)) {
2881         // If the function is marked as non-lazy, generate an indirect call
2882         // which loads from the GOT directly. This avoids runtime overhead
2883         // at the cost of eager binding (and one extra byte of encoding).
2884         OpFlags = X86II::MO_GOTPCREL;
2885         WrapperKind = X86ISD::WrapperRIP;
2886         ExtraLoad = true;
2887       }
2888
2889       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2890                                           G->getOffset(), OpFlags);
2891
2892       // Add a wrapper if needed.
2893       if (WrapperKind != ISD::DELETED_NODE)
2894         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2895       // Add extra indirection if needed.
2896       if (ExtraLoad)
2897         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2898                              MachinePointerInfo::getGOT(),
2899                              false, false, false, 0);
2900     }
2901   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2902     unsigned char OpFlags = 0;
2903
2904     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2905     // external symbols should go through the PLT.
2906     if (Subtarget->isTargetELF() &&
2907         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2908       OpFlags = X86II::MO_PLT;
2909     } else if (Subtarget->isPICStyleStubAny() &&
2910                (!Subtarget->getTargetTriple().isMacOSX() ||
2911                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2912       // PC-relative references to external symbols should go through $stub,
2913       // unless we're building with the leopard linker or later, which
2914       // automatically synthesizes these stubs.
2915       OpFlags = X86II::MO_DARWIN_STUB;
2916     }
2917
2918     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2919                                          OpFlags);
2920   }
2921
2922   // Returns a chain & a flag for retval copy to use.
2923   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2924   SmallVector<SDValue, 8> Ops;
2925
2926   if (!IsSibcall && isTailCall) {
2927     Chain = DAG.getCALLSEQ_END(Chain,
2928                                DAG.getIntPtrConstant(NumBytesToPop, true),
2929                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2930     InFlag = Chain.getValue(1);
2931   }
2932
2933   Ops.push_back(Chain);
2934   Ops.push_back(Callee);
2935
2936   if (isTailCall)
2937     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2938
2939   // Add argument registers to the end of the list so that they are known live
2940   // into the call.
2941   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2942     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2943                                   RegsToPass[i].second.getValueType()));
2944
2945   // Add a register mask operand representing the call-preserved registers.
2946   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2947   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2948   assert(Mask && "Missing call preserved mask for calling convention");
2949   Ops.push_back(DAG.getRegisterMask(Mask));
2950
2951   if (InFlag.getNode())
2952     Ops.push_back(InFlag);
2953
2954   if (isTailCall) {
2955     // We used to do:
2956     //// If this is the first return lowered for this function, add the regs
2957     //// to the liveout set for the function.
2958     // This isn't right, although it's probably harmless on x86; liveouts
2959     // should be computed from returns not tail calls.  Consider a void
2960     // function making a tail call to a function returning int.
2961     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2962   }
2963
2964   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2965   InFlag = Chain.getValue(1);
2966
2967   // Create the CALLSEQ_END node.
2968   unsigned NumBytesForCalleeToPop;
2969   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2970                        getTargetMachine().Options.GuaranteedTailCallOpt))
2971     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2972   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2973            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2974            SR == StackStructReturn)
2975     // If this is a call to a struct-return function, the callee
2976     // pops the hidden struct pointer, so we have to push it back.
2977     // This is common for Darwin/X86, Linux & Mingw32 targets.
2978     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2979     NumBytesForCalleeToPop = 4;
2980   else
2981     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2982
2983   // Returns a flag for retval copy to use.
2984   if (!IsSibcall) {
2985     Chain = DAG.getCALLSEQ_END(Chain,
2986                                DAG.getIntPtrConstant(NumBytesToPop, true),
2987                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2988                                                      true),
2989                                InFlag, dl);
2990     InFlag = Chain.getValue(1);
2991   }
2992
2993   // Handle result values, copying them out of physregs into vregs that we
2994   // return.
2995   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2996                          Ins, dl, DAG, InVals);
2997 }
2998
2999 //===----------------------------------------------------------------------===//
3000 //                Fast Calling Convention (tail call) implementation
3001 //===----------------------------------------------------------------------===//
3002
3003 //  Like std call, callee cleans arguments, convention except that ECX is
3004 //  reserved for storing the tail called function address. Only 2 registers are
3005 //  free for argument passing (inreg). Tail call optimization is performed
3006 //  provided:
3007 //                * tailcallopt is enabled
3008 //                * caller/callee are fastcc
3009 //  On X86_64 architecture with GOT-style position independent code only local
3010 //  (within module) calls are supported at the moment.
3011 //  To keep the stack aligned according to platform abi the function
3012 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3013 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3014 //  If a tail called function callee has more arguments than the caller the
3015 //  caller needs to make sure that there is room to move the RETADDR to. This is
3016 //  achieved by reserving an area the size of the argument delta right after the
3017 //  original REtADDR, but before the saved framepointer or the spilled registers
3018 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3019 //  stack layout:
3020 //    arg1
3021 //    arg2
3022 //    RETADDR
3023 //    [ new RETADDR
3024 //      move area ]
3025 //    (possible EBP)
3026 //    ESI
3027 //    EDI
3028 //    local1 ..
3029
3030 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3031 /// for a 16 byte align requirement.
3032 unsigned
3033 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3034                                                SelectionDAG& DAG) const {
3035   MachineFunction &MF = DAG.getMachineFunction();
3036   const TargetMachine &TM = MF.getTarget();
3037   const X86RegisterInfo *RegInfo =
3038     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3039   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3040   unsigned StackAlignment = TFI.getStackAlignment();
3041   uint64_t AlignMask = StackAlignment - 1;
3042   int64_t Offset = StackSize;
3043   unsigned SlotSize = RegInfo->getSlotSize();
3044   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3045     // Number smaller than 12 so just add the difference.
3046     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3047   } else {
3048     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3049     Offset = ((~AlignMask) & Offset) + StackAlignment +
3050       (StackAlignment-SlotSize);
3051   }
3052   return Offset;
3053 }
3054
3055 /// MatchingStackOffset - Return true if the given stack call argument is
3056 /// already available in the same position (relatively) of the caller's
3057 /// incoming argument stack.
3058 static
3059 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3060                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3061                          const X86InstrInfo *TII) {
3062   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3063   int FI = INT_MAX;
3064   if (Arg.getOpcode() == ISD::CopyFromReg) {
3065     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3066     if (!TargetRegisterInfo::isVirtualRegister(VR))
3067       return false;
3068     MachineInstr *Def = MRI->getVRegDef(VR);
3069     if (!Def)
3070       return false;
3071     if (!Flags.isByVal()) {
3072       if (!TII->isLoadFromStackSlot(Def, FI))
3073         return false;
3074     } else {
3075       unsigned Opcode = Def->getOpcode();
3076       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3077           Def->getOperand(1).isFI()) {
3078         FI = Def->getOperand(1).getIndex();
3079         Bytes = Flags.getByValSize();
3080       } else
3081         return false;
3082     }
3083   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3084     if (Flags.isByVal())
3085       // ByVal argument is passed in as a pointer but it's now being
3086       // dereferenced. e.g.
3087       // define @foo(%struct.X* %A) {
3088       //   tail call @bar(%struct.X* byval %A)
3089       // }
3090       return false;
3091     SDValue Ptr = Ld->getBasePtr();
3092     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3093     if (!FINode)
3094       return false;
3095     FI = FINode->getIndex();
3096   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3097     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3098     FI = FINode->getIndex();
3099     Bytes = Flags.getByValSize();
3100   } else
3101     return false;
3102
3103   assert(FI != INT_MAX);
3104   if (!MFI->isFixedObjectIndex(FI))
3105     return false;
3106   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3107 }
3108
3109 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3110 /// for tail call optimization. Targets which want to do tail call
3111 /// optimization should implement this function.
3112 bool
3113 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3114                                                      CallingConv::ID CalleeCC,
3115                                                      bool isVarArg,
3116                                                      bool isCalleeStructRet,
3117                                                      bool isCallerStructRet,
3118                                                      Type *RetTy,
3119                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3120                                     const SmallVectorImpl<SDValue> &OutVals,
3121                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3122                                                      SelectionDAG &DAG) const {
3123   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3124     return false;
3125
3126   // If -tailcallopt is specified, make fastcc functions tail-callable.
3127   const MachineFunction &MF = DAG.getMachineFunction();
3128   const Function *CallerF = MF.getFunction();
3129
3130   // If the function return type is x86_fp80 and the callee return type is not,
3131   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3132   // perform a tailcall optimization here.
3133   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3134     return false;
3135
3136   CallingConv::ID CallerCC = CallerF->getCallingConv();
3137   bool CCMatch = CallerCC == CalleeCC;
3138   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3139   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3140
3141   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3142     if (IsTailCallConvention(CalleeCC) && CCMatch)
3143       return true;
3144     return false;
3145   }
3146
3147   // Look for obvious safe cases to perform tail call optimization that do not
3148   // require ABI changes. This is what gcc calls sibcall.
3149
3150   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3151   // emit a special epilogue.
3152   const X86RegisterInfo *RegInfo =
3153     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3154   if (RegInfo->needsStackRealignment(MF))
3155     return false;
3156
3157   // Also avoid sibcall optimization if either caller or callee uses struct
3158   // return semantics.
3159   if (isCalleeStructRet || isCallerStructRet)
3160     return false;
3161
3162   // An stdcall/thiscall caller is expected to clean up its arguments; the
3163   // callee isn't going to do that.
3164   // FIXME: this is more restrictive than needed. We could produce a tailcall
3165   // when the stack adjustment matches. For example, with a thiscall that takes
3166   // only one argument.
3167   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3168                    CallerCC == CallingConv::X86_ThisCall))
3169     return false;
3170
3171   // Do not sibcall optimize vararg calls unless all arguments are passed via
3172   // registers.
3173   if (isVarArg && !Outs.empty()) {
3174
3175     // Optimizing for varargs on Win64 is unlikely to be safe without
3176     // additional testing.
3177     if (IsCalleeWin64 || IsCallerWin64)
3178       return false;
3179
3180     SmallVector<CCValAssign, 16> ArgLocs;
3181     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3182                    getTargetMachine(), ArgLocs, *DAG.getContext());
3183
3184     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3185     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3186       if (!ArgLocs[i].isRegLoc())
3187         return false;
3188   }
3189
3190   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3191   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3192   // this into a sibcall.
3193   bool Unused = false;
3194   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3195     if (!Ins[i].Used) {
3196       Unused = true;
3197       break;
3198     }
3199   }
3200   if (Unused) {
3201     SmallVector<CCValAssign, 16> RVLocs;
3202     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3203                    getTargetMachine(), RVLocs, *DAG.getContext());
3204     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3205     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3206       CCValAssign &VA = RVLocs[i];
3207       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3208         return false;
3209     }
3210   }
3211
3212   // If the calling conventions do not match, then we'd better make sure the
3213   // results are returned in the same way as what the caller expects.
3214   if (!CCMatch) {
3215     SmallVector<CCValAssign, 16> RVLocs1;
3216     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3217                     getTargetMachine(), RVLocs1, *DAG.getContext());
3218     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3219
3220     SmallVector<CCValAssign, 16> RVLocs2;
3221     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3222                     getTargetMachine(), RVLocs2, *DAG.getContext());
3223     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3224
3225     if (RVLocs1.size() != RVLocs2.size())
3226       return false;
3227     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3228       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3229         return false;
3230       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3231         return false;
3232       if (RVLocs1[i].isRegLoc()) {
3233         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3234           return false;
3235       } else {
3236         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3237           return false;
3238       }
3239     }
3240   }
3241
3242   // If the callee takes no arguments then go on to check the results of the
3243   // call.
3244   if (!Outs.empty()) {
3245     // Check if stack adjustment is needed. For now, do not do this if any
3246     // argument is passed on the stack.
3247     SmallVector<CCValAssign, 16> ArgLocs;
3248     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3249                    getTargetMachine(), ArgLocs, *DAG.getContext());
3250
3251     // Allocate shadow area for Win64
3252     if (IsCalleeWin64)
3253       CCInfo.AllocateStack(32, 8);
3254
3255     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3256     if (CCInfo.getNextStackOffset()) {
3257       MachineFunction &MF = DAG.getMachineFunction();
3258       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3259         return false;
3260
3261       // Check if the arguments are already laid out in the right way as
3262       // the caller's fixed stack objects.
3263       MachineFrameInfo *MFI = MF.getFrameInfo();
3264       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3265       const X86InstrInfo *TII =
3266         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3267       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3268         CCValAssign &VA = ArgLocs[i];
3269         SDValue Arg = OutVals[i];
3270         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3271         if (VA.getLocInfo() == CCValAssign::Indirect)
3272           return false;
3273         if (!VA.isRegLoc()) {
3274           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3275                                    MFI, MRI, TII))
3276             return false;
3277         }
3278       }
3279     }
3280
3281     // If the tailcall address may be in a register, then make sure it's
3282     // possible to register allocate for it. In 32-bit, the call address can
3283     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3284     // callee-saved registers are restored. These happen to be the same
3285     // registers used to pass 'inreg' arguments so watch out for those.
3286     if (!Subtarget->is64Bit() &&
3287         ((!isa<GlobalAddressSDNode>(Callee) &&
3288           !isa<ExternalSymbolSDNode>(Callee)) ||
3289          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3290       unsigned NumInRegs = 0;
3291       // In PIC we need an extra register to formulate the address computation
3292       // for the callee.
3293       unsigned MaxInRegs =
3294           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3295
3296       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3297         CCValAssign &VA = ArgLocs[i];
3298         if (!VA.isRegLoc())
3299           continue;
3300         unsigned Reg = VA.getLocReg();
3301         switch (Reg) {
3302         default: break;
3303         case X86::EAX: case X86::EDX: case X86::ECX:
3304           if (++NumInRegs == MaxInRegs)
3305             return false;
3306           break;
3307         }
3308       }
3309     }
3310   }
3311
3312   return true;
3313 }
3314
3315 FastISel *
3316 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3317                                   const TargetLibraryInfo *libInfo) const {
3318   return X86::createFastISel(funcInfo, libInfo);
3319 }
3320
3321 //===----------------------------------------------------------------------===//
3322 //                           Other Lowering Hooks
3323 //===----------------------------------------------------------------------===//
3324
3325 static bool MayFoldLoad(SDValue Op) {
3326   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3327 }
3328
3329 static bool MayFoldIntoStore(SDValue Op) {
3330   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3331 }
3332
3333 static bool isTargetShuffle(unsigned Opcode) {
3334   switch(Opcode) {
3335   default: return false;
3336   case X86ISD::PSHUFD:
3337   case X86ISD::PSHUFHW:
3338   case X86ISD::PSHUFLW:
3339   case X86ISD::SHUFP:
3340   case X86ISD::PALIGNR:
3341   case X86ISD::MOVLHPS:
3342   case X86ISD::MOVLHPD:
3343   case X86ISD::MOVHLPS:
3344   case X86ISD::MOVLPS:
3345   case X86ISD::MOVLPD:
3346   case X86ISD::MOVSHDUP:
3347   case X86ISD::MOVSLDUP:
3348   case X86ISD::MOVDDUP:
3349   case X86ISD::MOVSS:
3350   case X86ISD::MOVSD:
3351   case X86ISD::UNPCKL:
3352   case X86ISD::UNPCKH:
3353   case X86ISD::VPERMILP:
3354   case X86ISD::VPERM2X128:
3355   case X86ISD::VPERMI:
3356     return true;
3357   }
3358 }
3359
3360 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3361                                     SDValue V1, SelectionDAG &DAG) {
3362   switch(Opc) {
3363   default: llvm_unreachable("Unknown x86 shuffle node");
3364   case X86ISD::MOVSHDUP:
3365   case X86ISD::MOVSLDUP:
3366   case X86ISD::MOVDDUP:
3367     return DAG.getNode(Opc, dl, VT, V1);
3368   }
3369 }
3370
3371 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3372                                     SDValue V1, unsigned TargetMask,
3373                                     SelectionDAG &DAG) {
3374   switch(Opc) {
3375   default: llvm_unreachable("Unknown x86 shuffle node");
3376   case X86ISD::PSHUFD:
3377   case X86ISD::PSHUFHW:
3378   case X86ISD::PSHUFLW:
3379   case X86ISD::VPERMILP:
3380   case X86ISD::VPERMI:
3381     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3382   }
3383 }
3384
3385 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3386                                     SDValue V1, SDValue V2, unsigned TargetMask,
3387                                     SelectionDAG &DAG) {
3388   switch(Opc) {
3389   default: llvm_unreachable("Unknown x86 shuffle node");
3390   case X86ISD::PALIGNR:
3391   case X86ISD::SHUFP:
3392   case X86ISD::VPERM2X128:
3393     return DAG.getNode(Opc, dl, VT, V1, V2,
3394                        DAG.getConstant(TargetMask, MVT::i8));
3395   }
3396 }
3397
3398 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3399                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3400   switch(Opc) {
3401   default: llvm_unreachable("Unknown x86 shuffle node");
3402   case X86ISD::MOVLHPS:
3403   case X86ISD::MOVLHPD:
3404   case X86ISD::MOVHLPS:
3405   case X86ISD::MOVLPS:
3406   case X86ISD::MOVLPD:
3407   case X86ISD::MOVSS:
3408   case X86ISD::MOVSD:
3409   case X86ISD::UNPCKL:
3410   case X86ISD::UNPCKH:
3411     return DAG.getNode(Opc, dl, VT, V1, V2);
3412   }
3413 }
3414
3415 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3416   MachineFunction &MF = DAG.getMachineFunction();
3417   const X86RegisterInfo *RegInfo =
3418     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3419   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3420   int ReturnAddrIndex = FuncInfo->getRAIndex();
3421
3422   if (ReturnAddrIndex == 0) {
3423     // Set up a frame object for the return address.
3424     unsigned SlotSize = RegInfo->getSlotSize();
3425     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3426                                                            -(int64_t)SlotSize,
3427                                                            false);
3428     FuncInfo->setRAIndex(ReturnAddrIndex);
3429   }
3430
3431   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3432 }
3433
3434 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3435                                        bool hasSymbolicDisplacement) {
3436   // Offset should fit into 32 bit immediate field.
3437   if (!isInt<32>(Offset))
3438     return false;
3439
3440   // If we don't have a symbolic displacement - we don't have any extra
3441   // restrictions.
3442   if (!hasSymbolicDisplacement)
3443     return true;
3444
3445   // FIXME: Some tweaks might be needed for medium code model.
3446   if (M != CodeModel::Small && M != CodeModel::Kernel)
3447     return false;
3448
3449   // For small code model we assume that latest object is 16MB before end of 31
3450   // bits boundary. We may also accept pretty large negative constants knowing
3451   // that all objects are in the positive half of address space.
3452   if (M == CodeModel::Small && Offset < 16*1024*1024)
3453     return true;
3454
3455   // For kernel code model we know that all object resist in the negative half
3456   // of 32bits address space. We may not accept negative offsets, since they may
3457   // be just off and we may accept pretty large positive ones.
3458   if (M == CodeModel::Kernel && Offset > 0)
3459     return true;
3460
3461   return false;
3462 }
3463
3464 /// isCalleePop - Determines whether the callee is required to pop its
3465 /// own arguments. Callee pop is necessary to support tail calls.
3466 bool X86::isCalleePop(CallingConv::ID CallingConv,
3467                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3468   if (IsVarArg)
3469     return false;
3470
3471   switch (CallingConv) {
3472   default:
3473     return false;
3474   case CallingConv::X86_StdCall:
3475     return !is64Bit;
3476   case CallingConv::X86_FastCall:
3477     return !is64Bit;
3478   case CallingConv::X86_ThisCall:
3479     return !is64Bit;
3480   case CallingConv::Fast:
3481     return TailCallOpt;
3482   case CallingConv::GHC:
3483     return TailCallOpt;
3484   case CallingConv::HiPE:
3485     return TailCallOpt;
3486   }
3487 }
3488
3489 /// \brief Return true if the condition is an unsigned comparison operation.
3490 static bool isX86CCUnsigned(unsigned X86CC) {
3491   switch (X86CC) {
3492   default: llvm_unreachable("Invalid integer condition!");
3493   case X86::COND_E:     return true;
3494   case X86::COND_G:     return false;
3495   case X86::COND_GE:    return false;
3496   case X86::COND_L:     return false;
3497   case X86::COND_LE:    return false;
3498   case X86::COND_NE:    return true;
3499   case X86::COND_B:     return true;
3500   case X86::COND_A:     return true;
3501   case X86::COND_BE:    return true;
3502   case X86::COND_AE:    return true;
3503   }
3504   llvm_unreachable("covered switch fell through?!");
3505 }
3506
3507 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3508 /// specific condition code, returning the condition code and the LHS/RHS of the
3509 /// comparison to make.
3510 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3511                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3512   if (!isFP) {
3513     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3514       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3515         // X > -1   -> X == 0, jump !sign.
3516         RHS = DAG.getConstant(0, RHS.getValueType());
3517         return X86::COND_NS;
3518       }
3519       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3520         // X < 0   -> X == 0, jump on sign.
3521         return X86::COND_S;
3522       }
3523       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3524         // X < 1   -> X <= 0
3525         RHS = DAG.getConstant(0, RHS.getValueType());
3526         return X86::COND_LE;
3527       }
3528     }
3529
3530     switch (SetCCOpcode) {
3531     default: llvm_unreachable("Invalid integer condition!");
3532     case ISD::SETEQ:  return X86::COND_E;
3533     case ISD::SETGT:  return X86::COND_G;
3534     case ISD::SETGE:  return X86::COND_GE;
3535     case ISD::SETLT:  return X86::COND_L;
3536     case ISD::SETLE:  return X86::COND_LE;
3537     case ISD::SETNE:  return X86::COND_NE;
3538     case ISD::SETULT: return X86::COND_B;
3539     case ISD::SETUGT: return X86::COND_A;
3540     case ISD::SETULE: return X86::COND_BE;
3541     case ISD::SETUGE: return X86::COND_AE;
3542     }
3543   }
3544
3545   // First determine if it is required or is profitable to flip the operands.
3546
3547   // If LHS is a foldable load, but RHS is not, flip the condition.
3548   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3549       !ISD::isNON_EXTLoad(RHS.getNode())) {
3550     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3551     std::swap(LHS, RHS);
3552   }
3553
3554   switch (SetCCOpcode) {
3555   default: break;
3556   case ISD::SETOLT:
3557   case ISD::SETOLE:
3558   case ISD::SETUGT:
3559   case ISD::SETUGE:
3560     std::swap(LHS, RHS);
3561     break;
3562   }
3563
3564   // On a floating point condition, the flags are set as follows:
3565   // ZF  PF  CF   op
3566   //  0 | 0 | 0 | X > Y
3567   //  0 | 0 | 1 | X < Y
3568   //  1 | 0 | 0 | X == Y
3569   //  1 | 1 | 1 | unordered
3570   switch (SetCCOpcode) {
3571   default: llvm_unreachable("Condcode should be pre-legalized away");
3572   case ISD::SETUEQ:
3573   case ISD::SETEQ:   return X86::COND_E;
3574   case ISD::SETOLT:              // flipped
3575   case ISD::SETOGT:
3576   case ISD::SETGT:   return X86::COND_A;
3577   case ISD::SETOLE:              // flipped
3578   case ISD::SETOGE:
3579   case ISD::SETGE:   return X86::COND_AE;
3580   case ISD::SETUGT:              // flipped
3581   case ISD::SETULT:
3582   case ISD::SETLT:   return X86::COND_B;
3583   case ISD::SETUGE:              // flipped
3584   case ISD::SETULE:
3585   case ISD::SETLE:   return X86::COND_BE;
3586   case ISD::SETONE:
3587   case ISD::SETNE:   return X86::COND_NE;
3588   case ISD::SETUO:   return X86::COND_P;
3589   case ISD::SETO:    return X86::COND_NP;
3590   case ISD::SETOEQ:
3591   case ISD::SETUNE:  return X86::COND_INVALID;
3592   }
3593 }
3594
3595 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3596 /// code. Current x86 isa includes the following FP cmov instructions:
3597 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3598 static bool hasFPCMov(unsigned X86CC) {
3599   switch (X86CC) {
3600   default:
3601     return false;
3602   case X86::COND_B:
3603   case X86::COND_BE:
3604   case X86::COND_E:
3605   case X86::COND_P:
3606   case X86::COND_A:
3607   case X86::COND_AE:
3608   case X86::COND_NE:
3609   case X86::COND_NP:
3610     return true;
3611   }
3612 }
3613
3614 /// isFPImmLegal - Returns true if the target can instruction select the
3615 /// specified FP immediate natively. If false, the legalizer will
3616 /// materialize the FP immediate as a load from a constant pool.
3617 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3618   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3619     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3620       return true;
3621   }
3622   return false;
3623 }
3624
3625 /// \brief Returns true if it is beneficial to convert a load of a constant
3626 /// to just the constant itself.
3627 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3628                                                           Type *Ty) const {
3629   assert(Ty->isIntegerTy());
3630
3631   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3632   if (BitSize == 0 || BitSize > 64)
3633     return false;
3634   return true;
3635 }
3636
3637 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3638 /// the specified range (L, H].
3639 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3640   return (Val < 0) || (Val >= Low && Val < Hi);
3641 }
3642
3643 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3644 /// specified value.
3645 static bool isUndefOrEqual(int Val, int CmpVal) {
3646   return (Val < 0 || Val == CmpVal);
3647 }
3648
3649 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3650 /// from position Pos and ending in Pos+Size, falls within the specified
3651 /// sequential range (L, L+Pos]. or is undef.
3652 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3653                                        unsigned Pos, unsigned Size, int Low) {
3654   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3655     if (!isUndefOrEqual(Mask[i], Low))
3656       return false;
3657   return true;
3658 }
3659
3660 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3661 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3662 /// the second operand.
3663 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3664   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3665     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3666   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3667     return (Mask[0] < 2 && Mask[1] < 2);
3668   return false;
3669 }
3670
3671 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3672 /// is suitable for input to PSHUFHW.
3673 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3674   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3675     return false;
3676
3677   // Lower quadword copied in order or undef.
3678   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3679     return false;
3680
3681   // Upper quadword shuffled.
3682   for (unsigned i = 4; i != 8; ++i)
3683     if (!isUndefOrInRange(Mask[i], 4, 8))
3684       return false;
3685
3686   if (VT == MVT::v16i16) {
3687     // Lower quadword copied in order or undef.
3688     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3689       return false;
3690
3691     // Upper quadword shuffled.
3692     for (unsigned i = 12; i != 16; ++i)
3693       if (!isUndefOrInRange(Mask[i], 12, 16))
3694         return false;
3695   }
3696
3697   return true;
3698 }
3699
3700 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3701 /// is suitable for input to PSHUFLW.
3702 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3703   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3704     return false;
3705
3706   // Upper quadword copied in order.
3707   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3708     return false;
3709
3710   // Lower quadword shuffled.
3711   for (unsigned i = 0; i != 4; ++i)
3712     if (!isUndefOrInRange(Mask[i], 0, 4))
3713       return false;
3714
3715   if (VT == MVT::v16i16) {
3716     // Upper quadword copied in order.
3717     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3718       return false;
3719
3720     // Lower quadword shuffled.
3721     for (unsigned i = 8; i != 12; ++i)
3722       if (!isUndefOrInRange(Mask[i], 8, 12))
3723         return false;
3724   }
3725
3726   return true;
3727 }
3728
3729 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3730 /// is suitable for input to PALIGNR.
3731 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3732                           const X86Subtarget *Subtarget) {
3733   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3734       (VT.is256BitVector() && !Subtarget->hasInt256()))
3735     return false;
3736
3737   unsigned NumElts = VT.getVectorNumElements();
3738   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3739   unsigned NumLaneElts = NumElts/NumLanes;
3740
3741   // Do not handle 64-bit element shuffles with palignr.
3742   if (NumLaneElts == 2)
3743     return false;
3744
3745   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3746     unsigned i;
3747     for (i = 0; i != NumLaneElts; ++i) {
3748       if (Mask[i+l] >= 0)
3749         break;
3750     }
3751
3752     // Lane is all undef, go to next lane
3753     if (i == NumLaneElts)
3754       continue;
3755
3756     int Start = Mask[i+l];
3757
3758     // Make sure its in this lane in one of the sources
3759     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3760         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3761       return false;
3762
3763     // If not lane 0, then we must match lane 0
3764     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3765       return false;
3766
3767     // Correct second source to be contiguous with first source
3768     if (Start >= (int)NumElts)
3769       Start -= NumElts - NumLaneElts;
3770
3771     // Make sure we're shifting in the right direction.
3772     if (Start <= (int)(i+l))
3773       return false;
3774
3775     Start -= i;
3776
3777     // Check the rest of the elements to see if they are consecutive.
3778     for (++i; i != NumLaneElts; ++i) {
3779       int Idx = Mask[i+l];
3780
3781       // Make sure its in this lane
3782       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3783           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3784         return false;
3785
3786       // If not lane 0, then we must match lane 0
3787       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3788         return false;
3789
3790       if (Idx >= (int)NumElts)
3791         Idx -= NumElts - NumLaneElts;
3792
3793       if (!isUndefOrEqual(Idx, Start+i))
3794         return false;
3795
3796     }
3797   }
3798
3799   return true;
3800 }
3801
3802 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3803 /// the two vector operands have swapped position.
3804 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3805                                      unsigned NumElems) {
3806   for (unsigned i = 0; i != NumElems; ++i) {
3807     int idx = Mask[i];
3808     if (idx < 0)
3809       continue;
3810     else if (idx < (int)NumElems)
3811       Mask[i] = idx + NumElems;
3812     else
3813       Mask[i] = idx - NumElems;
3814   }
3815 }
3816
3817 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3818 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3819 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3820 /// reverse of what x86 shuffles want.
3821 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3822
3823   unsigned NumElems = VT.getVectorNumElements();
3824   unsigned NumLanes = VT.getSizeInBits()/128;
3825   unsigned NumLaneElems = NumElems/NumLanes;
3826
3827   if (NumLaneElems != 2 && NumLaneElems != 4)
3828     return false;
3829
3830   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3831   bool symetricMaskRequired =
3832     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3833
3834   // VSHUFPSY divides the resulting vector into 4 chunks.
3835   // The sources are also splitted into 4 chunks, and each destination
3836   // chunk must come from a different source chunk.
3837   //
3838   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3839   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3840   //
3841   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3842   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3843   //
3844   // VSHUFPDY divides the resulting vector into 4 chunks.
3845   // The sources are also splitted into 4 chunks, and each destination
3846   // chunk must come from a different source chunk.
3847   //
3848   //  SRC1 =>      X3       X2       X1       X0
3849   //  SRC2 =>      Y3       Y2       Y1       Y0
3850   //
3851   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3852   //
3853   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3854   unsigned HalfLaneElems = NumLaneElems/2;
3855   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3856     for (unsigned i = 0; i != NumLaneElems; ++i) {
3857       int Idx = Mask[i+l];
3858       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3859       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3860         return false;
3861       // For VSHUFPSY, the mask of the second half must be the same as the
3862       // first but with the appropriate offsets. This works in the same way as
3863       // VPERMILPS works with masks.
3864       if (!symetricMaskRequired || Idx < 0)
3865         continue;
3866       if (MaskVal[i] < 0) {
3867         MaskVal[i] = Idx - l;
3868         continue;
3869       }
3870       if ((signed)(Idx - l) != MaskVal[i])
3871         return false;
3872     }
3873   }
3874
3875   return true;
3876 }
3877
3878 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3879 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3880 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3881   if (!VT.is128BitVector())
3882     return false;
3883
3884   unsigned NumElems = VT.getVectorNumElements();
3885
3886   if (NumElems != 4)
3887     return false;
3888
3889   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3890   return isUndefOrEqual(Mask[0], 6) &&
3891          isUndefOrEqual(Mask[1], 7) &&
3892          isUndefOrEqual(Mask[2], 2) &&
3893          isUndefOrEqual(Mask[3], 3);
3894 }
3895
3896 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3897 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3898 /// <2, 3, 2, 3>
3899 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3900   if (!VT.is128BitVector())
3901     return false;
3902
3903   unsigned NumElems = VT.getVectorNumElements();
3904
3905   if (NumElems != 4)
3906     return false;
3907
3908   return isUndefOrEqual(Mask[0], 2) &&
3909          isUndefOrEqual(Mask[1], 3) &&
3910          isUndefOrEqual(Mask[2], 2) &&
3911          isUndefOrEqual(Mask[3], 3);
3912 }
3913
3914 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3915 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3916 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3917   if (!VT.is128BitVector())
3918     return false;
3919
3920   unsigned NumElems = VT.getVectorNumElements();
3921
3922   if (NumElems != 2 && NumElems != 4)
3923     return false;
3924
3925   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3926     if (!isUndefOrEqual(Mask[i], i + NumElems))
3927       return false;
3928
3929   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3930     if (!isUndefOrEqual(Mask[i], i))
3931       return false;
3932
3933   return true;
3934 }
3935
3936 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3938 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3939   if (!VT.is128BitVector())
3940     return false;
3941
3942   unsigned NumElems = VT.getVectorNumElements();
3943
3944   if (NumElems != 2 && NumElems != 4)
3945     return false;
3946
3947   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3948     if (!isUndefOrEqual(Mask[i], i))
3949       return false;
3950
3951   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3952     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3953       return false;
3954
3955   return true;
3956 }
3957
3958 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3959 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3960 /// i. e: If all but one element come from the same vector.
3961 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3962   // TODO: Deal with AVX's VINSERTPS
3963   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3964     return false;
3965
3966   unsigned CorrectPosV1 = 0;
3967   unsigned CorrectPosV2 = 0;
3968   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3969     if (Mask[i] == -1) {
3970       ++CorrectPosV1;
3971       ++CorrectPosV2;
3972       continue;
3973     }
3974
3975     if (Mask[i] == i)
3976       ++CorrectPosV1;
3977     else if (Mask[i] == i + 4)
3978       ++CorrectPosV2;
3979   }
3980
3981   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3982     // We have 3 elements (undefs count as elements from any vector) from one
3983     // vector, and one from another.
3984     return true;
3985
3986   return false;
3987 }
3988
3989 //
3990 // Some special combinations that can be optimized.
3991 //
3992 static
3993 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3994                                SelectionDAG &DAG) {
3995   MVT VT = SVOp->getSimpleValueType(0);
3996   SDLoc dl(SVOp);
3997
3998   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3999     return SDValue();
4000
4001   ArrayRef<int> Mask = SVOp->getMask();
4002
4003   // These are the special masks that may be optimized.
4004   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4005   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4006   bool MatchEvenMask = true;
4007   bool MatchOddMask  = true;
4008   for (int i=0; i<8; ++i) {
4009     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4010       MatchEvenMask = false;
4011     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4012       MatchOddMask = false;
4013   }
4014
4015   if (!MatchEvenMask && !MatchOddMask)
4016     return SDValue();
4017
4018   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4019
4020   SDValue Op0 = SVOp->getOperand(0);
4021   SDValue Op1 = SVOp->getOperand(1);
4022
4023   if (MatchEvenMask) {
4024     // Shift the second operand right to 32 bits.
4025     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4026     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4027   } else {
4028     // Shift the first operand left to 32 bits.
4029     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4030     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4031   }
4032   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4033   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4034 }
4035
4036 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4037 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4038 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4039                          bool HasInt256, bool V2IsSplat = false) {
4040
4041   assert(VT.getSizeInBits() >= 128 &&
4042          "Unsupported vector type for unpckl");
4043
4044   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4045   unsigned NumLanes;
4046   unsigned NumOf256BitLanes;
4047   unsigned NumElts = VT.getVectorNumElements();
4048   if (VT.is256BitVector()) {
4049     if (NumElts != 4 && NumElts != 8 &&
4050         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4051     return false;
4052     NumLanes = 2;
4053     NumOf256BitLanes = 1;
4054   } else if (VT.is512BitVector()) {
4055     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4056            "Unsupported vector type for unpckh");
4057     NumLanes = 2;
4058     NumOf256BitLanes = 2;
4059   } else {
4060     NumLanes = 1;
4061     NumOf256BitLanes = 1;
4062   }
4063
4064   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4065   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4066
4067   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4068     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4069       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4070         int BitI  = Mask[l256*NumEltsInStride+l+i];
4071         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4072         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4073           return false;
4074         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4075           return false;
4076         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4077           return false;
4078       }
4079     }
4080   }
4081   return true;
4082 }
4083
4084 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4085 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4086 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4087                          bool HasInt256, bool V2IsSplat = false) {
4088   assert(VT.getSizeInBits() >= 128 &&
4089          "Unsupported vector type for unpckh");
4090
4091   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4092   unsigned NumLanes;
4093   unsigned NumOf256BitLanes;
4094   unsigned NumElts = VT.getVectorNumElements();
4095   if (VT.is256BitVector()) {
4096     if (NumElts != 4 && NumElts != 8 &&
4097         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4098     return false;
4099     NumLanes = 2;
4100     NumOf256BitLanes = 1;
4101   } else if (VT.is512BitVector()) {
4102     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4103            "Unsupported vector type for unpckh");
4104     NumLanes = 2;
4105     NumOf256BitLanes = 2;
4106   } else {
4107     NumLanes = 1;
4108     NumOf256BitLanes = 1;
4109   }
4110
4111   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4112   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4113
4114   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4115     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4116       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4117         int BitI  = Mask[l256*NumEltsInStride+l+i];
4118         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4119         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4120           return false;
4121         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4122           return false;
4123         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4124           return false;
4125       }
4126     }
4127   }
4128   return true;
4129 }
4130
4131 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4132 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4133 /// <0, 0, 1, 1>
4134 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4135   unsigned NumElts = VT.getVectorNumElements();
4136   bool Is256BitVec = VT.is256BitVector();
4137
4138   if (VT.is512BitVector())
4139     return false;
4140   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4141          "Unsupported vector type for unpckh");
4142
4143   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4144       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4145     return false;
4146
4147   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4148   // FIXME: Need a better way to get rid of this, there's no latency difference
4149   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4150   // the former later. We should also remove the "_undef" special mask.
4151   if (NumElts == 4 && Is256BitVec)
4152     return false;
4153
4154   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4155   // independently on 128-bit lanes.
4156   unsigned NumLanes = VT.getSizeInBits()/128;
4157   unsigned NumLaneElts = NumElts/NumLanes;
4158
4159   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4160     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4161       int BitI  = Mask[l+i];
4162       int BitI1 = Mask[l+i+1];
4163
4164       if (!isUndefOrEqual(BitI, j))
4165         return false;
4166       if (!isUndefOrEqual(BitI1, j))
4167         return false;
4168     }
4169   }
4170
4171   return true;
4172 }
4173
4174 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4175 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4176 /// <2, 2, 3, 3>
4177 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4178   unsigned NumElts = VT.getVectorNumElements();
4179
4180   if (VT.is512BitVector())
4181     return false;
4182
4183   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4184          "Unsupported vector type for unpckh");
4185
4186   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4187       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4188     return false;
4189
4190   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4191   // independently on 128-bit lanes.
4192   unsigned NumLanes = VT.getSizeInBits()/128;
4193   unsigned NumLaneElts = NumElts/NumLanes;
4194
4195   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4196     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4197       int BitI  = Mask[l+i];
4198       int BitI1 = Mask[l+i+1];
4199       if (!isUndefOrEqual(BitI, j))
4200         return false;
4201       if (!isUndefOrEqual(BitI1, j))
4202         return false;
4203     }
4204   }
4205   return true;
4206 }
4207
4208 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4209 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4210 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4211   if (!VT.is512BitVector())
4212     return false;
4213
4214   unsigned NumElts = VT.getVectorNumElements();
4215   unsigned HalfSize = NumElts/2;
4216   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4217     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4218       *Imm = 1;
4219       return true;
4220     }
4221   }
4222   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4223     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4224       *Imm = 0;
4225       return true;
4226     }
4227   }
4228   return false;
4229 }
4230
4231 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4232 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4233 /// MOVSD, and MOVD, i.e. setting the lowest element.
4234 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4235   if (VT.getVectorElementType().getSizeInBits() < 32)
4236     return false;
4237   if (!VT.is128BitVector())
4238     return false;
4239
4240   unsigned NumElts = VT.getVectorNumElements();
4241
4242   if (!isUndefOrEqual(Mask[0], NumElts))
4243     return false;
4244
4245   for (unsigned i = 1; i != NumElts; ++i)
4246     if (!isUndefOrEqual(Mask[i], i))
4247       return false;
4248
4249   return true;
4250 }
4251
4252 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4253 /// as permutations between 128-bit chunks or halves. As an example: this
4254 /// shuffle bellow:
4255 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4256 /// The first half comes from the second half of V1 and the second half from the
4257 /// the second half of V2.
4258 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4259   if (!HasFp256 || !VT.is256BitVector())
4260     return false;
4261
4262   // The shuffle result is divided into half A and half B. In total the two
4263   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4264   // B must come from C, D, E or F.
4265   unsigned HalfSize = VT.getVectorNumElements()/2;
4266   bool MatchA = false, MatchB = false;
4267
4268   // Check if A comes from one of C, D, E, F.
4269   for (unsigned Half = 0; Half != 4; ++Half) {
4270     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4271       MatchA = true;
4272       break;
4273     }
4274   }
4275
4276   // Check if B comes from one of C, D, E, F.
4277   for (unsigned Half = 0; Half != 4; ++Half) {
4278     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4279       MatchB = true;
4280       break;
4281     }
4282   }
4283
4284   return MatchA && MatchB;
4285 }
4286
4287 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4288 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4289 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4290   MVT VT = SVOp->getSimpleValueType(0);
4291
4292   unsigned HalfSize = VT.getVectorNumElements()/2;
4293
4294   unsigned FstHalf = 0, SndHalf = 0;
4295   for (unsigned i = 0; i < HalfSize; ++i) {
4296     if (SVOp->getMaskElt(i) > 0) {
4297       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4298       break;
4299     }
4300   }
4301   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4302     if (SVOp->getMaskElt(i) > 0) {
4303       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4304       break;
4305     }
4306   }
4307
4308   return (FstHalf | (SndHalf << 4));
4309 }
4310
4311 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4312 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4313   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4314   if (EltSize < 32)
4315     return false;
4316
4317   unsigned NumElts = VT.getVectorNumElements();
4318   Imm8 = 0;
4319   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4320     for (unsigned i = 0; i != NumElts; ++i) {
4321       if (Mask[i] < 0)
4322         continue;
4323       Imm8 |= Mask[i] << (i*2);
4324     }
4325     return true;
4326   }
4327
4328   unsigned LaneSize = 4;
4329   SmallVector<int, 4> MaskVal(LaneSize, -1);
4330
4331   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4332     for (unsigned i = 0; i != LaneSize; ++i) {
4333       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4334         return false;
4335       if (Mask[i+l] < 0)
4336         continue;
4337       if (MaskVal[i] < 0) {
4338         MaskVal[i] = Mask[i+l] - l;
4339         Imm8 |= MaskVal[i] << (i*2);
4340         continue;
4341       }
4342       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4343         return false;
4344     }
4345   }
4346   return true;
4347 }
4348
4349 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4350 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4351 /// Note that VPERMIL mask matching is different depending whether theunderlying
4352 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4353 /// to the same elements of the low, but to the higher half of the source.
4354 /// In VPERMILPD the two lanes could be shuffled independently of each other
4355 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4356 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4357   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4358   if (VT.getSizeInBits() < 256 || EltSize < 32)
4359     return false;
4360   bool symetricMaskRequired = (EltSize == 32);
4361   unsigned NumElts = VT.getVectorNumElements();
4362
4363   unsigned NumLanes = VT.getSizeInBits()/128;
4364   unsigned LaneSize = NumElts/NumLanes;
4365   // 2 or 4 elements in one lane
4366
4367   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4368   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4369     for (unsigned i = 0; i != LaneSize; ++i) {
4370       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4371         return false;
4372       if (symetricMaskRequired) {
4373         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4374           ExpectedMaskVal[i] = Mask[i+l] - l;
4375           continue;
4376         }
4377         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4378           return false;
4379       }
4380     }
4381   }
4382   return true;
4383 }
4384
4385 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4386 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4387 /// element of vector 2 and the other elements to come from vector 1 in order.
4388 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4389                                bool V2IsSplat = false, bool V2IsUndef = false) {
4390   if (!VT.is128BitVector())
4391     return false;
4392
4393   unsigned NumOps = VT.getVectorNumElements();
4394   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4395     return false;
4396
4397   if (!isUndefOrEqual(Mask[0], 0))
4398     return false;
4399
4400   for (unsigned i = 1; i != NumOps; ++i)
4401     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4402           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4403           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4404       return false;
4405
4406   return true;
4407 }
4408
4409 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4410 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4411 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4412 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4413                            const X86Subtarget *Subtarget) {
4414   if (!Subtarget->hasSSE3())
4415     return false;
4416
4417   unsigned NumElems = VT.getVectorNumElements();
4418
4419   if ((VT.is128BitVector() && NumElems != 4) ||
4420       (VT.is256BitVector() && NumElems != 8) ||
4421       (VT.is512BitVector() && NumElems != 16))
4422     return false;
4423
4424   // "i+1" is the value the indexed mask element must have
4425   for (unsigned i = 0; i != NumElems; i += 2)
4426     if (!isUndefOrEqual(Mask[i], i+1) ||
4427         !isUndefOrEqual(Mask[i+1], i+1))
4428       return false;
4429
4430   return true;
4431 }
4432
4433 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4434 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4435 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4436 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4437                            const X86Subtarget *Subtarget) {
4438   if (!Subtarget->hasSSE3())
4439     return false;
4440
4441   unsigned NumElems = VT.getVectorNumElements();
4442
4443   if ((VT.is128BitVector() && NumElems != 4) ||
4444       (VT.is256BitVector() && NumElems != 8) ||
4445       (VT.is512BitVector() && NumElems != 16))
4446     return false;
4447
4448   // "i" is the value the indexed mask element must have
4449   for (unsigned i = 0; i != NumElems; i += 2)
4450     if (!isUndefOrEqual(Mask[i], i) ||
4451         !isUndefOrEqual(Mask[i+1], i))
4452       return false;
4453
4454   return true;
4455 }
4456
4457 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4458 /// specifies a shuffle of elements that is suitable for input to 256-bit
4459 /// version of MOVDDUP.
4460 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4461   if (!HasFp256 || !VT.is256BitVector())
4462     return false;
4463
4464   unsigned NumElts = VT.getVectorNumElements();
4465   if (NumElts != 4)
4466     return false;
4467
4468   for (unsigned i = 0; i != NumElts/2; ++i)
4469     if (!isUndefOrEqual(Mask[i], 0))
4470       return false;
4471   for (unsigned i = NumElts/2; i != NumElts; ++i)
4472     if (!isUndefOrEqual(Mask[i], NumElts/2))
4473       return false;
4474   return true;
4475 }
4476
4477 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4478 /// specifies a shuffle of elements that is suitable for input to 128-bit
4479 /// version of MOVDDUP.
4480 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4481   if (!VT.is128BitVector())
4482     return false;
4483
4484   unsigned e = VT.getVectorNumElements() / 2;
4485   for (unsigned i = 0; i != e; ++i)
4486     if (!isUndefOrEqual(Mask[i], i))
4487       return false;
4488   for (unsigned i = 0; i != e; ++i)
4489     if (!isUndefOrEqual(Mask[e+i], i))
4490       return false;
4491   return true;
4492 }
4493
4494 /// isVEXTRACTIndex - Return true if the specified
4495 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4496 /// suitable for instruction that extract 128 or 256 bit vectors
4497 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4498   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4499   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4500     return false;
4501
4502   // The index should be aligned on a vecWidth-bit boundary.
4503   uint64_t Index =
4504     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4505
4506   MVT VT = N->getSimpleValueType(0);
4507   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4508   bool Result = (Index * ElSize) % vecWidth == 0;
4509
4510   return Result;
4511 }
4512
4513 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4514 /// operand specifies a subvector insert that is suitable for input to
4515 /// insertion of 128 or 256-bit subvectors
4516 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4517   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4518   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4519     return false;
4520   // The index should be aligned on a vecWidth-bit boundary.
4521   uint64_t Index =
4522     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4523
4524   MVT VT = N->getSimpleValueType(0);
4525   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4526   bool Result = (Index * ElSize) % vecWidth == 0;
4527
4528   return Result;
4529 }
4530
4531 bool X86::isVINSERT128Index(SDNode *N) {
4532   return isVINSERTIndex(N, 128);
4533 }
4534
4535 bool X86::isVINSERT256Index(SDNode *N) {
4536   return isVINSERTIndex(N, 256);
4537 }
4538
4539 bool X86::isVEXTRACT128Index(SDNode *N) {
4540   return isVEXTRACTIndex(N, 128);
4541 }
4542
4543 bool X86::isVEXTRACT256Index(SDNode *N) {
4544   return isVEXTRACTIndex(N, 256);
4545 }
4546
4547 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4548 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4549 /// Handles 128-bit and 256-bit.
4550 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4551   MVT VT = N->getSimpleValueType(0);
4552
4553   assert((VT.getSizeInBits() >= 128) &&
4554          "Unsupported vector type for PSHUF/SHUFP");
4555
4556   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4557   // independently on 128-bit lanes.
4558   unsigned NumElts = VT.getVectorNumElements();
4559   unsigned NumLanes = VT.getSizeInBits()/128;
4560   unsigned NumLaneElts = NumElts/NumLanes;
4561
4562   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4563          "Only supports 2, 4 or 8 elements per lane");
4564
4565   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4566   unsigned Mask = 0;
4567   for (unsigned i = 0; i != NumElts; ++i) {
4568     int Elt = N->getMaskElt(i);
4569     if (Elt < 0) continue;
4570     Elt &= NumLaneElts - 1;
4571     unsigned ShAmt = (i << Shift) % 8;
4572     Mask |= Elt << ShAmt;
4573   }
4574
4575   return Mask;
4576 }
4577
4578 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4579 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4580 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4581   MVT VT = N->getSimpleValueType(0);
4582
4583   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4584          "Unsupported vector type for PSHUFHW");
4585
4586   unsigned NumElts = VT.getVectorNumElements();
4587
4588   unsigned Mask = 0;
4589   for (unsigned l = 0; l != NumElts; l += 8) {
4590     // 8 nodes per lane, but we only care about the last 4.
4591     for (unsigned i = 0; i < 4; ++i) {
4592       int Elt = N->getMaskElt(l+i+4);
4593       if (Elt < 0) continue;
4594       Elt &= 0x3; // only 2-bits.
4595       Mask |= Elt << (i * 2);
4596     }
4597   }
4598
4599   return Mask;
4600 }
4601
4602 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4603 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4604 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4605   MVT VT = N->getSimpleValueType(0);
4606
4607   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4608          "Unsupported vector type for PSHUFHW");
4609
4610   unsigned NumElts = VT.getVectorNumElements();
4611
4612   unsigned Mask = 0;
4613   for (unsigned l = 0; l != NumElts; l += 8) {
4614     // 8 nodes per lane, but we only care about the first 4.
4615     for (unsigned i = 0; i < 4; ++i) {
4616       int Elt = N->getMaskElt(l+i);
4617       if (Elt < 0) continue;
4618       Elt &= 0x3; // only 2-bits
4619       Mask |= Elt << (i * 2);
4620     }
4621   }
4622
4623   return Mask;
4624 }
4625
4626 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4627 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4628 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4629   MVT VT = SVOp->getSimpleValueType(0);
4630   unsigned EltSize = VT.is512BitVector() ? 1 :
4631     VT.getVectorElementType().getSizeInBits() >> 3;
4632
4633   unsigned NumElts = VT.getVectorNumElements();
4634   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4635   unsigned NumLaneElts = NumElts/NumLanes;
4636
4637   int Val = 0;
4638   unsigned i;
4639   for (i = 0; i != NumElts; ++i) {
4640     Val = SVOp->getMaskElt(i);
4641     if (Val >= 0)
4642       break;
4643   }
4644   if (Val >= (int)NumElts)
4645     Val -= NumElts - NumLaneElts;
4646
4647   assert(Val - i > 0 && "PALIGNR imm should be positive");
4648   return (Val - i) * EltSize;
4649 }
4650
4651 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4652   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4653   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4654     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4655
4656   uint64_t Index =
4657     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4658
4659   MVT VecVT = N->getOperand(0).getSimpleValueType();
4660   MVT ElVT = VecVT.getVectorElementType();
4661
4662   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4663   return Index / NumElemsPerChunk;
4664 }
4665
4666 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4667   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4668   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4669     llvm_unreachable("Illegal insert subvector for VINSERT");
4670
4671   uint64_t Index =
4672     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4673
4674   MVT VecVT = N->getSimpleValueType(0);
4675   MVT ElVT = VecVT.getVectorElementType();
4676
4677   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4678   return Index / NumElemsPerChunk;
4679 }
4680
4681 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4682 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4683 /// and VINSERTI128 instructions.
4684 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4685   return getExtractVEXTRACTImmediate(N, 128);
4686 }
4687
4688 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4689 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4690 /// and VINSERTI64x4 instructions.
4691 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4692   return getExtractVEXTRACTImmediate(N, 256);
4693 }
4694
4695 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4696 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4697 /// and VINSERTI128 instructions.
4698 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4699   return getInsertVINSERTImmediate(N, 128);
4700 }
4701
4702 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4703 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4704 /// and VINSERTI64x4 instructions.
4705 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4706   return getInsertVINSERTImmediate(N, 256);
4707 }
4708
4709 /// isZero - Returns true if Elt is a constant integer zero
4710 static bool isZero(SDValue V) {
4711   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4712   return C && C->isNullValue();
4713 }
4714
4715 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4716 /// constant +0.0.
4717 bool X86::isZeroNode(SDValue Elt) {
4718   if (isZero(Elt))
4719     return true;
4720   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4721     return CFP->getValueAPF().isPosZero();
4722   return false;
4723 }
4724
4725 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4726 /// their permute mask.
4727 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4728                                     SelectionDAG &DAG) {
4729   MVT VT = SVOp->getSimpleValueType(0);
4730   unsigned NumElems = VT.getVectorNumElements();
4731   SmallVector<int, 8> MaskVec;
4732
4733   for (unsigned i = 0; i != NumElems; ++i) {
4734     int Idx = SVOp->getMaskElt(i);
4735     if (Idx >= 0) {
4736       if (Idx < (int)NumElems)
4737         Idx += NumElems;
4738       else
4739         Idx -= NumElems;
4740     }
4741     MaskVec.push_back(Idx);
4742   }
4743   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4744                               SVOp->getOperand(0), &MaskVec[0]);
4745 }
4746
4747 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4748 /// match movhlps. The lower half elements should come from upper half of
4749 /// V1 (and in order), and the upper half elements should come from the upper
4750 /// half of V2 (and in order).
4751 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4752   if (!VT.is128BitVector())
4753     return false;
4754   if (VT.getVectorNumElements() != 4)
4755     return false;
4756   for (unsigned i = 0, e = 2; i != e; ++i)
4757     if (!isUndefOrEqual(Mask[i], i+2))
4758       return false;
4759   for (unsigned i = 2; i != 4; ++i)
4760     if (!isUndefOrEqual(Mask[i], i+4))
4761       return false;
4762   return true;
4763 }
4764
4765 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4766 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4767 /// required.
4768 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4769   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4770     return false;
4771   N = N->getOperand(0).getNode();
4772   if (!ISD::isNON_EXTLoad(N))
4773     return false;
4774   if (LD)
4775     *LD = cast<LoadSDNode>(N);
4776   return true;
4777 }
4778
4779 // Test whether the given value is a vector value which will be legalized
4780 // into a load.
4781 static bool WillBeConstantPoolLoad(SDNode *N) {
4782   if (N->getOpcode() != ISD::BUILD_VECTOR)
4783     return false;
4784
4785   // Check for any non-constant elements.
4786   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4787     switch (N->getOperand(i).getNode()->getOpcode()) {
4788     case ISD::UNDEF:
4789     case ISD::ConstantFP:
4790     case ISD::Constant:
4791       break;
4792     default:
4793       return false;
4794     }
4795
4796   // Vectors of all-zeros and all-ones are materialized with special
4797   // instructions rather than being loaded.
4798   return !ISD::isBuildVectorAllZeros(N) &&
4799          !ISD::isBuildVectorAllOnes(N);
4800 }
4801
4802 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4803 /// match movlp{s|d}. The lower half elements should come from lower half of
4804 /// V1 (and in order), and the upper half elements should come from the upper
4805 /// half of V2 (and in order). And since V1 will become the source of the
4806 /// MOVLP, it must be either a vector load or a scalar load to vector.
4807 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4808                                ArrayRef<int> Mask, MVT VT) {
4809   if (!VT.is128BitVector())
4810     return false;
4811
4812   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4813     return false;
4814   // Is V2 is a vector load, don't do this transformation. We will try to use
4815   // load folding shufps op.
4816   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4817     return false;
4818
4819   unsigned NumElems = VT.getVectorNumElements();
4820
4821   if (NumElems != 2 && NumElems != 4)
4822     return false;
4823   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4824     if (!isUndefOrEqual(Mask[i], i))
4825       return false;
4826   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4827     if (!isUndefOrEqual(Mask[i], i+NumElems))
4828       return false;
4829   return true;
4830 }
4831
4832 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4833 /// all the same.
4834 static bool isSplatVector(SDNode *N) {
4835   if (N->getOpcode() != ISD::BUILD_VECTOR)
4836     return false;
4837
4838   SDValue SplatValue = N->getOperand(0);
4839   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4840     if (N->getOperand(i) != SplatValue)
4841       return false;
4842   return true;
4843 }
4844
4845 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4846 /// to an zero vector.
4847 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4848 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4849   SDValue V1 = N->getOperand(0);
4850   SDValue V2 = N->getOperand(1);
4851   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4852   for (unsigned i = 0; i != NumElems; ++i) {
4853     int Idx = N->getMaskElt(i);
4854     if (Idx >= (int)NumElems) {
4855       unsigned Opc = V2.getOpcode();
4856       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4857         continue;
4858       if (Opc != ISD::BUILD_VECTOR ||
4859           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4860         return false;
4861     } else if (Idx >= 0) {
4862       unsigned Opc = V1.getOpcode();
4863       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4864         continue;
4865       if (Opc != ISD::BUILD_VECTOR ||
4866           !X86::isZeroNode(V1.getOperand(Idx)))
4867         return false;
4868     }
4869   }
4870   return true;
4871 }
4872
4873 /// getZeroVector - Returns a vector of specified type with all zero elements.
4874 ///
4875 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4876                              SelectionDAG &DAG, SDLoc dl) {
4877   assert(VT.isVector() && "Expected a vector type");
4878
4879   // Always build SSE zero vectors as <4 x i32> bitcasted
4880   // to their dest type. This ensures they get CSE'd.
4881   SDValue Vec;
4882   if (VT.is128BitVector()) {  // SSE
4883     if (Subtarget->hasSSE2()) {  // SSE2
4884       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4885       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4886     } else { // SSE1
4887       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4888       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4889     }
4890   } else if (VT.is256BitVector()) { // AVX
4891     if (Subtarget->hasInt256()) { // AVX2
4892       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4893       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4894       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4895     } else {
4896       // 256-bit logic and arithmetic instructions in AVX are all
4897       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4898       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4899       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4900       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4901     }
4902   } else if (VT.is512BitVector()) { // AVX-512
4903       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4904       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4905                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4906       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4907   } else if (VT.getScalarType() == MVT::i1) {
4908     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4909     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4910     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4911     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4912   } else
4913     llvm_unreachable("Unexpected vector type");
4914
4915   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4916 }
4917
4918 /// getOnesVector - Returns a vector of specified type with all bits set.
4919 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4920 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4921 /// Then bitcast to their original type, ensuring they get CSE'd.
4922 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4923                              SDLoc dl) {
4924   assert(VT.isVector() && "Expected a vector type");
4925
4926   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4927   SDValue Vec;
4928   if (VT.is256BitVector()) {
4929     if (HasInt256) { // AVX2
4930       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4931       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4932     } else { // AVX
4933       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4934       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4935     }
4936   } else if (VT.is128BitVector()) {
4937     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4938   } else
4939     llvm_unreachable("Unexpected vector type");
4940
4941   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4942 }
4943
4944 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4945 /// that point to V2 points to its first element.
4946 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4947   for (unsigned i = 0; i != NumElems; ++i) {
4948     if (Mask[i] > (int)NumElems) {
4949       Mask[i] = NumElems;
4950     }
4951   }
4952 }
4953
4954 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4955 /// operation of specified width.
4956 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4957                        SDValue V2) {
4958   unsigned NumElems = VT.getVectorNumElements();
4959   SmallVector<int, 8> Mask;
4960   Mask.push_back(NumElems);
4961   for (unsigned i = 1; i != NumElems; ++i)
4962     Mask.push_back(i);
4963   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4964 }
4965
4966 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4967 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4968                           SDValue V2) {
4969   unsigned NumElems = VT.getVectorNumElements();
4970   SmallVector<int, 8> Mask;
4971   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4972     Mask.push_back(i);
4973     Mask.push_back(i + NumElems);
4974   }
4975   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4976 }
4977
4978 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4979 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4980                           SDValue V2) {
4981   unsigned NumElems = VT.getVectorNumElements();
4982   SmallVector<int, 8> Mask;
4983   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4984     Mask.push_back(i + Half);
4985     Mask.push_back(i + NumElems + Half);
4986   }
4987   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4988 }
4989
4990 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4991 // a generic shuffle instruction because the target has no such instructions.
4992 // Generate shuffles which repeat i16 and i8 several times until they can be
4993 // represented by v4f32 and then be manipulated by target suported shuffles.
4994 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4995   MVT VT = V.getSimpleValueType();
4996   int NumElems = VT.getVectorNumElements();
4997   SDLoc dl(V);
4998
4999   while (NumElems > 4) {
5000     if (EltNo < NumElems/2) {
5001       V = getUnpackl(DAG, dl, VT, V, V);
5002     } else {
5003       V = getUnpackh(DAG, dl, VT, V, V);
5004       EltNo -= NumElems/2;
5005     }
5006     NumElems >>= 1;
5007   }
5008   return V;
5009 }
5010
5011 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5012 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5013   MVT VT = V.getSimpleValueType();
5014   SDLoc dl(V);
5015
5016   if (VT.is128BitVector()) {
5017     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5018     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5019     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5020                              &SplatMask[0]);
5021   } else if (VT.is256BitVector()) {
5022     // To use VPERMILPS to splat scalars, the second half of indicies must
5023     // refer to the higher part, which is a duplication of the lower one,
5024     // because VPERMILPS can only handle in-lane permutations.
5025     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5026                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5027
5028     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5029     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5030                              &SplatMask[0]);
5031   } else
5032     llvm_unreachable("Vector size not supported");
5033
5034   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5035 }
5036
5037 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5038 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5039   MVT SrcVT = SV->getSimpleValueType(0);
5040   SDValue V1 = SV->getOperand(0);
5041   SDLoc dl(SV);
5042
5043   int EltNo = SV->getSplatIndex();
5044   int NumElems = SrcVT.getVectorNumElements();
5045   bool Is256BitVec = SrcVT.is256BitVector();
5046
5047   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5048          "Unknown how to promote splat for type");
5049
5050   // Extract the 128-bit part containing the splat element and update
5051   // the splat element index when it refers to the higher register.
5052   if (Is256BitVec) {
5053     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5054     if (EltNo >= NumElems/2)
5055       EltNo -= NumElems/2;
5056   }
5057
5058   // All i16 and i8 vector types can't be used directly by a generic shuffle
5059   // instruction because the target has no such instruction. Generate shuffles
5060   // which repeat i16 and i8 several times until they fit in i32, and then can
5061   // be manipulated by target suported shuffles.
5062   MVT EltVT = SrcVT.getVectorElementType();
5063   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5064     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5065
5066   // Recreate the 256-bit vector and place the same 128-bit vector
5067   // into the low and high part. This is necessary because we want
5068   // to use VPERM* to shuffle the vectors
5069   if (Is256BitVec) {
5070     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5071   }
5072
5073   return getLegalSplat(DAG, V1, EltNo);
5074 }
5075
5076 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5077 /// vector of zero or undef vector.  This produces a shuffle where the low
5078 /// element of V2 is swizzled into the zero/undef vector, landing at element
5079 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5080 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5081                                            bool IsZero,
5082                                            const X86Subtarget *Subtarget,
5083                                            SelectionDAG &DAG) {
5084   MVT VT = V2.getSimpleValueType();
5085   SDValue V1 = IsZero
5086     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5087   unsigned NumElems = VT.getVectorNumElements();
5088   SmallVector<int, 16> MaskVec;
5089   for (unsigned i = 0; i != NumElems; ++i)
5090     // If this is the insertion idx, put the low elt of V2 here.
5091     MaskVec.push_back(i == Idx ? NumElems : i);
5092   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5093 }
5094
5095 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5096 /// target specific opcode. Returns true if the Mask could be calculated.
5097 /// Sets IsUnary to true if only uses one source.
5098 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5099                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5100   unsigned NumElems = VT.getVectorNumElements();
5101   SDValue ImmN;
5102
5103   IsUnary = false;
5104   switch(N->getOpcode()) {
5105   case X86ISD::SHUFP:
5106     ImmN = N->getOperand(N->getNumOperands()-1);
5107     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5108     break;
5109   case X86ISD::UNPCKH:
5110     DecodeUNPCKHMask(VT, Mask);
5111     break;
5112   case X86ISD::UNPCKL:
5113     DecodeUNPCKLMask(VT, Mask);
5114     break;
5115   case X86ISD::MOVHLPS:
5116     DecodeMOVHLPSMask(NumElems, Mask);
5117     break;
5118   case X86ISD::MOVLHPS:
5119     DecodeMOVLHPSMask(NumElems, Mask);
5120     break;
5121   case X86ISD::PALIGNR:
5122     ImmN = N->getOperand(N->getNumOperands()-1);
5123     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5124     break;
5125   case X86ISD::PSHUFD:
5126   case X86ISD::VPERMILP:
5127     ImmN = N->getOperand(N->getNumOperands()-1);
5128     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5129     IsUnary = true;
5130     break;
5131   case X86ISD::PSHUFHW:
5132     ImmN = N->getOperand(N->getNumOperands()-1);
5133     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5134     IsUnary = true;
5135     break;
5136   case X86ISD::PSHUFLW:
5137     ImmN = N->getOperand(N->getNumOperands()-1);
5138     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5139     IsUnary = true;
5140     break;
5141   case X86ISD::VPERMI:
5142     ImmN = N->getOperand(N->getNumOperands()-1);
5143     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5144     IsUnary = true;
5145     break;
5146   case X86ISD::MOVSS:
5147   case X86ISD::MOVSD: {
5148     // The index 0 always comes from the first element of the second source,
5149     // this is why MOVSS and MOVSD are used in the first place. The other
5150     // elements come from the other positions of the first source vector
5151     Mask.push_back(NumElems);
5152     for (unsigned i = 1; i != NumElems; ++i) {
5153       Mask.push_back(i);
5154     }
5155     break;
5156   }
5157   case X86ISD::VPERM2X128:
5158     ImmN = N->getOperand(N->getNumOperands()-1);
5159     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5160     if (Mask.empty()) return false;
5161     break;
5162   case X86ISD::MOVDDUP:
5163   case X86ISD::MOVLHPD:
5164   case X86ISD::MOVLPD:
5165   case X86ISD::MOVLPS:
5166   case X86ISD::MOVSHDUP:
5167   case X86ISD::MOVSLDUP:
5168     // Not yet implemented
5169     return false;
5170   default: llvm_unreachable("unknown target shuffle node");
5171   }
5172
5173   return true;
5174 }
5175
5176 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5177 /// element of the result of the vector shuffle.
5178 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5179                                    unsigned Depth) {
5180   if (Depth == 6)
5181     return SDValue();  // Limit search depth.
5182
5183   SDValue V = SDValue(N, 0);
5184   EVT VT = V.getValueType();
5185   unsigned Opcode = V.getOpcode();
5186
5187   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5188   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5189     int Elt = SV->getMaskElt(Index);
5190
5191     if (Elt < 0)
5192       return DAG.getUNDEF(VT.getVectorElementType());
5193
5194     unsigned NumElems = VT.getVectorNumElements();
5195     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5196                                          : SV->getOperand(1);
5197     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5198   }
5199
5200   // Recurse into target specific vector shuffles to find scalars.
5201   if (isTargetShuffle(Opcode)) {
5202     MVT ShufVT = V.getSimpleValueType();
5203     unsigned NumElems = ShufVT.getVectorNumElements();
5204     SmallVector<int, 16> ShuffleMask;
5205     bool IsUnary;
5206
5207     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5208       return SDValue();
5209
5210     int Elt = ShuffleMask[Index];
5211     if (Elt < 0)
5212       return DAG.getUNDEF(ShufVT.getVectorElementType());
5213
5214     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5215                                          : N->getOperand(1);
5216     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5217                                Depth+1);
5218   }
5219
5220   // Actual nodes that may contain scalar elements
5221   if (Opcode == ISD::BITCAST) {
5222     V = V.getOperand(0);
5223     EVT SrcVT = V.getValueType();
5224     unsigned NumElems = VT.getVectorNumElements();
5225
5226     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5227       return SDValue();
5228   }
5229
5230   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5231     return (Index == 0) ? V.getOperand(0)
5232                         : DAG.getUNDEF(VT.getVectorElementType());
5233
5234   if (V.getOpcode() == ISD::BUILD_VECTOR)
5235     return V.getOperand(Index);
5236
5237   return SDValue();
5238 }
5239
5240 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5241 /// shuffle operation which come from a consecutively from a zero. The
5242 /// search can start in two different directions, from left or right.
5243 /// We count undefs as zeros until PreferredNum is reached.
5244 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5245                                          unsigned NumElems, bool ZerosFromLeft,
5246                                          SelectionDAG &DAG,
5247                                          unsigned PreferredNum = -1U) {
5248   unsigned NumZeros = 0;
5249   for (unsigned i = 0; i != NumElems; ++i) {
5250     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5251     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5252     if (!Elt.getNode())
5253       break;
5254
5255     if (X86::isZeroNode(Elt))
5256       ++NumZeros;
5257     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5258       NumZeros = std::min(NumZeros + 1, PreferredNum);
5259     else
5260       break;
5261   }
5262
5263   return NumZeros;
5264 }
5265
5266 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5267 /// correspond consecutively to elements from one of the vector operands,
5268 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5269 static
5270 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5271                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5272                               unsigned NumElems, unsigned &OpNum) {
5273   bool SeenV1 = false;
5274   bool SeenV2 = false;
5275
5276   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5277     int Idx = SVOp->getMaskElt(i);
5278     // Ignore undef indicies
5279     if (Idx < 0)
5280       continue;
5281
5282     if (Idx < (int)NumElems)
5283       SeenV1 = true;
5284     else
5285       SeenV2 = true;
5286
5287     // Only accept consecutive elements from the same vector
5288     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5289       return false;
5290   }
5291
5292   OpNum = SeenV1 ? 0 : 1;
5293   return true;
5294 }
5295
5296 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5297 /// logical left shift of a vector.
5298 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5299                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5300   unsigned NumElems =
5301     SVOp->getSimpleValueType(0).getVectorNumElements();
5302   unsigned NumZeros = getNumOfConsecutiveZeros(
5303       SVOp, NumElems, false /* check zeros from right */, DAG,
5304       SVOp->getMaskElt(0));
5305   unsigned OpSrc;
5306
5307   if (!NumZeros)
5308     return false;
5309
5310   // Considering the elements in the mask that are not consecutive zeros,
5311   // check if they consecutively come from only one of the source vectors.
5312   //
5313   //               V1 = {X, A, B, C}     0
5314   //                         \  \  \    /
5315   //   vector_shuffle V1, V2 <1, 2, 3, X>
5316   //
5317   if (!isShuffleMaskConsecutive(SVOp,
5318             0,                   // Mask Start Index
5319             NumElems-NumZeros,   // Mask End Index(exclusive)
5320             NumZeros,            // Where to start looking in the src vector
5321             NumElems,            // Number of elements in vector
5322             OpSrc))              // Which source operand ?
5323     return false;
5324
5325   isLeft = false;
5326   ShAmt = NumZeros;
5327   ShVal = SVOp->getOperand(OpSrc);
5328   return true;
5329 }
5330
5331 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5332 /// logical left shift of a vector.
5333 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5334                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5335   unsigned NumElems =
5336     SVOp->getSimpleValueType(0).getVectorNumElements();
5337   unsigned NumZeros = getNumOfConsecutiveZeros(
5338       SVOp, NumElems, true /* check zeros from left */, DAG,
5339       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5340   unsigned OpSrc;
5341
5342   if (!NumZeros)
5343     return false;
5344
5345   // Considering the elements in the mask that are not consecutive zeros,
5346   // check if they consecutively come from only one of the source vectors.
5347   //
5348   //                           0    { A, B, X, X } = V2
5349   //                          / \    /  /
5350   //   vector_shuffle V1, V2 <X, X, 4, 5>
5351   //
5352   if (!isShuffleMaskConsecutive(SVOp,
5353             NumZeros,     // Mask Start Index
5354             NumElems,     // Mask End Index(exclusive)
5355             0,            // Where to start looking in the src vector
5356             NumElems,     // Number of elements in vector
5357             OpSrc))       // Which source operand ?
5358     return false;
5359
5360   isLeft = true;
5361   ShAmt = NumZeros;
5362   ShVal = SVOp->getOperand(OpSrc);
5363   return true;
5364 }
5365
5366 /// isVectorShift - Returns true if the shuffle can be implemented as a
5367 /// logical left or right shift of a vector.
5368 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5369                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5370   // Although the logic below support any bitwidth size, there are no
5371   // shift instructions which handle more than 128-bit vectors.
5372   if (!SVOp->getSimpleValueType(0).is128BitVector())
5373     return false;
5374
5375   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5376       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5377     return true;
5378
5379   return false;
5380 }
5381
5382 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5383 ///
5384 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5385                                        unsigned NumNonZero, unsigned NumZero,
5386                                        SelectionDAG &DAG,
5387                                        const X86Subtarget* Subtarget,
5388                                        const TargetLowering &TLI) {
5389   if (NumNonZero > 8)
5390     return SDValue();
5391
5392   SDLoc dl(Op);
5393   SDValue V;
5394   bool First = true;
5395   for (unsigned i = 0; i < 16; ++i) {
5396     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5397     if (ThisIsNonZero && First) {
5398       if (NumZero)
5399         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5400       else
5401         V = DAG.getUNDEF(MVT::v8i16);
5402       First = false;
5403     }
5404
5405     if ((i & 1) != 0) {
5406       SDValue ThisElt, LastElt;
5407       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5408       if (LastIsNonZero) {
5409         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5410                               MVT::i16, Op.getOperand(i-1));
5411       }
5412       if (ThisIsNonZero) {
5413         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5414         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5415                               ThisElt, DAG.getConstant(8, MVT::i8));
5416         if (LastIsNonZero)
5417           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5418       } else
5419         ThisElt = LastElt;
5420
5421       if (ThisElt.getNode())
5422         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5423                         DAG.getIntPtrConstant(i/2));
5424     }
5425   }
5426
5427   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5428 }
5429
5430 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5431 ///
5432 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5433                                      unsigned NumNonZero, unsigned NumZero,
5434                                      SelectionDAG &DAG,
5435                                      const X86Subtarget* Subtarget,
5436                                      const TargetLowering &TLI) {
5437   if (NumNonZero > 4)
5438     return SDValue();
5439
5440   SDLoc dl(Op);
5441   SDValue V;
5442   bool First = true;
5443   for (unsigned i = 0; i < 8; ++i) {
5444     bool isNonZero = (NonZeros & (1 << i)) != 0;
5445     if (isNonZero) {
5446       if (First) {
5447         if (NumZero)
5448           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5449         else
5450           V = DAG.getUNDEF(MVT::v8i16);
5451         First = false;
5452       }
5453       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5454                       MVT::v8i16, V, Op.getOperand(i),
5455                       DAG.getIntPtrConstant(i));
5456     }
5457   }
5458
5459   return V;
5460 }
5461
5462 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5463 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5464                                      unsigned NonZeros, unsigned NumNonZero,
5465                                      unsigned NumZero, SelectionDAG &DAG,
5466                                      const X86Subtarget *Subtarget,
5467                                      const TargetLowering &TLI) {
5468   // We know there's at least one non-zero element
5469   unsigned FirstNonZeroIdx = 0;
5470   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5471   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5472          X86::isZeroNode(FirstNonZero)) {
5473     ++FirstNonZeroIdx;
5474     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5475   }
5476
5477   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5478       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5479     return SDValue();
5480
5481   SDValue V = FirstNonZero.getOperand(0);
5482   MVT VVT = V.getSimpleValueType();
5483   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5484     return SDValue();
5485
5486   unsigned FirstNonZeroDst =
5487       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5488   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5489   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5490   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5491
5492   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5493     SDValue Elem = Op.getOperand(Idx);
5494     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5495       continue;
5496
5497     // TODO: What else can be here? Deal with it.
5498     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5499       return SDValue();
5500
5501     // TODO: Some optimizations are still possible here
5502     // ex: Getting one element from a vector, and the rest from another.
5503     if (Elem.getOperand(0) != V)
5504       return SDValue();
5505
5506     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5507     if (Dst == Idx)
5508       ++CorrectIdx;
5509     else if (IncorrectIdx == -1U) {
5510       IncorrectIdx = Idx;
5511       IncorrectDst = Dst;
5512     } else
5513       // There was already one element with an incorrect index.
5514       // We can't optimize this case to an insertps.
5515       return SDValue();
5516   }
5517
5518   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5519     SDLoc dl(Op);
5520     EVT VT = Op.getSimpleValueType();
5521     unsigned ElementMoveMask = 0;
5522     if (IncorrectIdx == -1U)
5523       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5524     else
5525       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5526
5527     SDValue InsertpsMask =
5528         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5529     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5530   }
5531
5532   return SDValue();
5533 }
5534
5535 /// getVShift - Return a vector logical shift node.
5536 ///
5537 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5538                          unsigned NumBits, SelectionDAG &DAG,
5539                          const TargetLowering &TLI, SDLoc dl) {
5540   assert(VT.is128BitVector() && "Unknown type for VShift");
5541   EVT ShVT = MVT::v2i64;
5542   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5543   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5544   return DAG.getNode(ISD::BITCAST, dl, VT,
5545                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5546                              DAG.getConstant(NumBits,
5547                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5548 }
5549
5550 static SDValue
5551 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5552
5553   // Check if the scalar load can be widened into a vector load. And if
5554   // the address is "base + cst" see if the cst can be "absorbed" into
5555   // the shuffle mask.
5556   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5557     SDValue Ptr = LD->getBasePtr();
5558     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5559       return SDValue();
5560     EVT PVT = LD->getValueType(0);
5561     if (PVT != MVT::i32 && PVT != MVT::f32)
5562       return SDValue();
5563
5564     int FI = -1;
5565     int64_t Offset = 0;
5566     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5567       FI = FINode->getIndex();
5568       Offset = 0;
5569     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5570                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5571       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5572       Offset = Ptr.getConstantOperandVal(1);
5573       Ptr = Ptr.getOperand(0);
5574     } else {
5575       return SDValue();
5576     }
5577
5578     // FIXME: 256-bit vector instructions don't require a strict alignment,
5579     // improve this code to support it better.
5580     unsigned RequiredAlign = VT.getSizeInBits()/8;
5581     SDValue Chain = LD->getChain();
5582     // Make sure the stack object alignment is at least 16 or 32.
5583     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5584     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5585       if (MFI->isFixedObjectIndex(FI)) {
5586         // Can't change the alignment. FIXME: It's possible to compute
5587         // the exact stack offset and reference FI + adjust offset instead.
5588         // If someone *really* cares about this. That's the way to implement it.
5589         return SDValue();
5590       } else {
5591         MFI->setObjectAlignment(FI, RequiredAlign);
5592       }
5593     }
5594
5595     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5596     // Ptr + (Offset & ~15).
5597     if (Offset < 0)
5598       return SDValue();
5599     if ((Offset % RequiredAlign) & 3)
5600       return SDValue();
5601     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5602     if (StartOffset)
5603       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5604                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5605
5606     int EltNo = (Offset - StartOffset) >> 2;
5607     unsigned NumElems = VT.getVectorNumElements();
5608
5609     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5610     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5611                              LD->getPointerInfo().getWithOffset(StartOffset),
5612                              false, false, false, 0);
5613
5614     SmallVector<int, 8> Mask;
5615     for (unsigned i = 0; i != NumElems; ++i)
5616       Mask.push_back(EltNo);
5617
5618     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5619   }
5620
5621   return SDValue();
5622 }
5623
5624 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5625 /// vector of type 'VT', see if the elements can be replaced by a single large
5626 /// load which has the same value as a build_vector whose operands are 'elts'.
5627 ///
5628 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5629 ///
5630 /// FIXME: we'd also like to handle the case where the last elements are zero
5631 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5632 /// There's even a handy isZeroNode for that purpose.
5633 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5634                                         SDLoc &DL, SelectionDAG &DAG,
5635                                         bool isAfterLegalize) {
5636   EVT EltVT = VT.getVectorElementType();
5637   unsigned NumElems = Elts.size();
5638
5639   LoadSDNode *LDBase = nullptr;
5640   unsigned LastLoadedElt = -1U;
5641
5642   // For each element in the initializer, see if we've found a load or an undef.
5643   // If we don't find an initial load element, or later load elements are
5644   // non-consecutive, bail out.
5645   for (unsigned i = 0; i < NumElems; ++i) {
5646     SDValue Elt = Elts[i];
5647
5648     if (!Elt.getNode() ||
5649         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5650       return SDValue();
5651     if (!LDBase) {
5652       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5653         return SDValue();
5654       LDBase = cast<LoadSDNode>(Elt.getNode());
5655       LastLoadedElt = i;
5656       continue;
5657     }
5658     if (Elt.getOpcode() == ISD::UNDEF)
5659       continue;
5660
5661     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5662     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5663       return SDValue();
5664     LastLoadedElt = i;
5665   }
5666
5667   // If we have found an entire vector of loads and undefs, then return a large
5668   // load of the entire vector width starting at the base pointer.  If we found
5669   // consecutive loads for the low half, generate a vzext_load node.
5670   if (LastLoadedElt == NumElems - 1) {
5671
5672     if (isAfterLegalize &&
5673         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5674       return SDValue();
5675
5676     SDValue NewLd = SDValue();
5677
5678     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5679       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5680                           LDBase->getPointerInfo(),
5681                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5682                           LDBase->isInvariant(), 0);
5683     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5684                         LDBase->getPointerInfo(),
5685                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5686                         LDBase->isInvariant(), LDBase->getAlignment());
5687
5688     if (LDBase->hasAnyUseOfValue(1)) {
5689       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5690                                      SDValue(LDBase, 1),
5691                                      SDValue(NewLd.getNode(), 1));
5692       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5693       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5694                              SDValue(NewLd.getNode(), 1));
5695     }
5696
5697     return NewLd;
5698   }
5699   if (NumElems == 4 && LastLoadedElt == 1 &&
5700       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5701     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5702     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5703     SDValue ResNode =
5704         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5705                                 LDBase->getPointerInfo(),
5706                                 LDBase->getAlignment(),
5707                                 false/*isVolatile*/, true/*ReadMem*/,
5708                                 false/*WriteMem*/);
5709
5710     // Make sure the newly-created LOAD is in the same position as LDBase in
5711     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5712     // update uses of LDBase's output chain to use the TokenFactor.
5713     if (LDBase->hasAnyUseOfValue(1)) {
5714       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5715                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5716       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5717       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5718                              SDValue(ResNode.getNode(), 1));
5719     }
5720
5721     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5722   }
5723   return SDValue();
5724 }
5725
5726 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5727 /// to generate a splat value for the following cases:
5728 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5729 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5730 /// a scalar load, or a constant.
5731 /// The VBROADCAST node is returned when a pattern is found,
5732 /// or SDValue() otherwise.
5733 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5734                                     SelectionDAG &DAG) {
5735   if (!Subtarget->hasFp256())
5736     return SDValue();
5737
5738   MVT VT = Op.getSimpleValueType();
5739   SDLoc dl(Op);
5740
5741   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5742          "Unsupported vector type for broadcast.");
5743
5744   SDValue Ld;
5745   bool ConstSplatVal;
5746
5747   switch (Op.getOpcode()) {
5748     default:
5749       // Unknown pattern found.
5750       return SDValue();
5751
5752     case ISD::BUILD_VECTOR: {
5753       // The BUILD_VECTOR node must be a splat.
5754       if (!isSplatVector(Op.getNode()))
5755         return SDValue();
5756
5757       Ld = Op.getOperand(0);
5758       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5759                      Ld.getOpcode() == ISD::ConstantFP);
5760
5761       // The suspected load node has several users. Make sure that all
5762       // of its users are from the BUILD_VECTOR node.
5763       // Constants may have multiple users.
5764       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5765         return SDValue();
5766       break;
5767     }
5768
5769     case ISD::VECTOR_SHUFFLE: {
5770       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5771
5772       // Shuffles must have a splat mask where the first element is
5773       // broadcasted.
5774       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5775         return SDValue();
5776
5777       SDValue Sc = Op.getOperand(0);
5778       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5779           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5780
5781         if (!Subtarget->hasInt256())
5782           return SDValue();
5783
5784         // Use the register form of the broadcast instruction available on AVX2.
5785         if (VT.getSizeInBits() >= 256)
5786           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5787         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5788       }
5789
5790       Ld = Sc.getOperand(0);
5791       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5792                        Ld.getOpcode() == ISD::ConstantFP);
5793
5794       // The scalar_to_vector node and the suspected
5795       // load node must have exactly one user.
5796       // Constants may have multiple users.
5797
5798       // AVX-512 has register version of the broadcast
5799       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5800         Ld.getValueType().getSizeInBits() >= 32;
5801       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5802           !hasRegVer))
5803         return SDValue();
5804       break;
5805     }
5806   }
5807
5808   bool IsGE256 = (VT.getSizeInBits() >= 256);
5809
5810   // Handle the broadcasting a single constant scalar from the constant pool
5811   // into a vector. On Sandybridge it is still better to load a constant vector
5812   // from the constant pool and not to broadcast it from a scalar.
5813   if (ConstSplatVal && Subtarget->hasInt256()) {
5814     EVT CVT = Ld.getValueType();
5815     assert(!CVT.isVector() && "Must not broadcast a vector type");
5816     unsigned ScalarSize = CVT.getSizeInBits();
5817
5818     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5819       const Constant *C = nullptr;
5820       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5821         C = CI->getConstantIntValue();
5822       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5823         C = CF->getConstantFPValue();
5824
5825       assert(C && "Invalid constant type");
5826
5827       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5828       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5829       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5830       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5831                        MachinePointerInfo::getConstantPool(),
5832                        false, false, false, Alignment);
5833
5834       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5835     }
5836   }
5837
5838   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5839   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5840
5841   // Handle AVX2 in-register broadcasts.
5842   if (!IsLoad && Subtarget->hasInt256() &&
5843       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5844     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5845
5846   // The scalar source must be a normal load.
5847   if (!IsLoad)
5848     return SDValue();
5849
5850   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5851     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5852
5853   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5854   // double since there is no vbroadcastsd xmm
5855   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5856     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5857       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5858   }
5859
5860   // Unsupported broadcast.
5861   return SDValue();
5862 }
5863
5864 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5865 /// underlying vector and index.
5866 ///
5867 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5868 /// index.
5869 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5870                                          SDValue ExtIdx) {
5871   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5872   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5873     return Idx;
5874
5875   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5876   // lowered this:
5877   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5878   // to:
5879   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5880   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5881   //                           undef)
5882   //                       Constant<0>)
5883   // In this case the vector is the extract_subvector expression and the index
5884   // is 2, as specified by the shuffle.
5885   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5886   SDValue ShuffleVec = SVOp->getOperand(0);
5887   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5888   assert(ShuffleVecVT.getVectorElementType() ==
5889          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5890
5891   int ShuffleIdx = SVOp->getMaskElt(Idx);
5892   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5893     ExtractedFromVec = ShuffleVec;
5894     return ShuffleIdx;
5895   }
5896   return Idx;
5897 }
5898
5899 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5900   MVT VT = Op.getSimpleValueType();
5901
5902   // Skip if insert_vec_elt is not supported.
5903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5904   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5905     return SDValue();
5906
5907   SDLoc DL(Op);
5908   unsigned NumElems = Op.getNumOperands();
5909
5910   SDValue VecIn1;
5911   SDValue VecIn2;
5912   SmallVector<unsigned, 4> InsertIndices;
5913   SmallVector<int, 8> Mask(NumElems, -1);
5914
5915   for (unsigned i = 0; i != NumElems; ++i) {
5916     unsigned Opc = Op.getOperand(i).getOpcode();
5917
5918     if (Opc == ISD::UNDEF)
5919       continue;
5920
5921     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5922       // Quit if more than 1 elements need inserting.
5923       if (InsertIndices.size() > 1)
5924         return SDValue();
5925
5926       InsertIndices.push_back(i);
5927       continue;
5928     }
5929
5930     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5931     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5932     // Quit if non-constant index.
5933     if (!isa<ConstantSDNode>(ExtIdx))
5934       return SDValue();
5935     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5936
5937     // Quit if extracted from vector of different type.
5938     if (ExtractedFromVec.getValueType() != VT)
5939       return SDValue();
5940
5941     if (!VecIn1.getNode())
5942       VecIn1 = ExtractedFromVec;
5943     else if (VecIn1 != ExtractedFromVec) {
5944       if (!VecIn2.getNode())
5945         VecIn2 = ExtractedFromVec;
5946       else if (VecIn2 != ExtractedFromVec)
5947         // Quit if more than 2 vectors to shuffle
5948         return SDValue();
5949     }
5950
5951     if (ExtractedFromVec == VecIn1)
5952       Mask[i] = Idx;
5953     else if (ExtractedFromVec == VecIn2)
5954       Mask[i] = Idx + NumElems;
5955   }
5956
5957   if (!VecIn1.getNode())
5958     return SDValue();
5959
5960   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5961   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5962   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5963     unsigned Idx = InsertIndices[i];
5964     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5965                      DAG.getIntPtrConstant(Idx));
5966   }
5967
5968   return NV;
5969 }
5970
5971 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5972 SDValue
5973 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5974
5975   MVT VT = Op.getSimpleValueType();
5976   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5977          "Unexpected type in LowerBUILD_VECTORvXi1!");
5978
5979   SDLoc dl(Op);
5980   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5981     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5982     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5983     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5984   }
5985
5986   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5987     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5988     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5989     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5990   }
5991
5992   bool AllContants = true;
5993   uint64_t Immediate = 0;
5994   int NonConstIdx = -1;
5995   bool IsSplat = true;
5996   unsigned NumNonConsts = 0;
5997   unsigned NumConsts = 0;
5998   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5999     SDValue In = Op.getOperand(idx);
6000     if (In.getOpcode() == ISD::UNDEF)
6001       continue;
6002     if (!isa<ConstantSDNode>(In)) {
6003       AllContants = false;
6004       NonConstIdx = idx;
6005       NumNonConsts++;
6006     }
6007     else {
6008       NumConsts++;
6009       if (cast<ConstantSDNode>(In)->getZExtValue())
6010       Immediate |= (1ULL << idx);
6011     }
6012     if (In != Op.getOperand(0))
6013       IsSplat = false;
6014   }
6015
6016   if (AllContants) {
6017     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6018       DAG.getConstant(Immediate, MVT::i16));
6019     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6020                        DAG.getIntPtrConstant(0));
6021   }
6022
6023   if (NumNonConsts == 1 && NonConstIdx != 0) {
6024     SDValue DstVec;
6025     if (NumConsts) {
6026       SDValue VecAsImm = DAG.getConstant(Immediate,
6027                                          MVT::getIntegerVT(VT.getSizeInBits()));
6028       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6029     }
6030     else 
6031       DstVec = DAG.getUNDEF(VT);
6032     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6033                        Op.getOperand(NonConstIdx),
6034                        DAG.getIntPtrConstant(NonConstIdx));
6035   }
6036   if (!IsSplat && (NonConstIdx != 0))
6037     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6038   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6039   SDValue Select;
6040   if (IsSplat)
6041     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6042                           DAG.getConstant(-1, SelectVT),
6043                           DAG.getConstant(0, SelectVT));
6044   else
6045     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6046                          DAG.getConstant((Immediate | 1), SelectVT),
6047                          DAG.getConstant(Immediate, SelectVT));
6048   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6049 }
6050
6051 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6052                                           const X86Subtarget *Subtarget) {
6053   EVT VT = N->getValueType(0);
6054
6055   // Try to match a horizontal ADD or SUB.
6056   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) ||
6057       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget->hasAVX()) ||
6058       ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) ||
6059       ((VT == MVT::v8i32 || VT == MVT::v16i16) && Subtarget->hasAVX2())) {
6060     unsigned NumOperands = N->getNumOperands();
6061     unsigned Opcode = N->getOperand(0)->getOpcode();
6062     bool isCommutable = false;
6063     bool CanFold = false;
6064     switch (Opcode) {
6065     default : break;
6066     case ISD::ADD :
6067     case ISD::FADD :
6068       isCommutable = true;
6069       // FALL-THROUGH
6070     case ISD::SUB :
6071     case ISD::FSUB :
6072       CanFold = true;
6073     }
6074
6075     // Verify that operands have the same opcode; also, the opcode can only
6076     // be either of: ADD, FADD, SUB, FSUB.
6077     SDValue InVec0, InVec1;
6078     for (unsigned i = 0, e = NumOperands; i != e && CanFold; ++i) {
6079       SDValue Op = N->getOperand(i);
6080       CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6081
6082       if (!CanFold)
6083         break;
6084
6085       SDValue Op0 = Op.getOperand(0);
6086       SDValue Op1 = Op.getOperand(1);
6087
6088       // Try to match the following pattern:
6089       // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6090       CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6091           Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6092           Op0.getOperand(0) == Op1.getOperand(0) &&
6093           isa<ConstantSDNode>(Op0.getOperand(1)) &&
6094           isa<ConstantSDNode>(Op1.getOperand(1)));
6095       if (!CanFold)
6096         break;
6097
6098       unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6099       unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6100       unsigned ExpectedIndex = (i * 2) % NumOperands;
6101  
6102       if (i == 0)
6103         InVec0 = Op0.getOperand(0);
6104       else if (i * 2 == NumOperands)
6105         InVec1 = Op0.getOperand(0);
6106
6107       SDValue Expected = (i * 2 < NumOperands) ? InVec0 : InVec1;
6108       if (I0 == ExpectedIndex)
6109         CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6110       else if (isCommutable && I1 == ExpectedIndex) {
6111         // Try to see if we can match the following dag sequence:
6112         // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6113         CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6114       }
6115     }
6116
6117     if (CanFold) {
6118       unsigned NewOpcode;
6119       switch (Opcode) {
6120       default : llvm_unreachable("Unexpected opcode found!");
6121       case ISD::ADD : NewOpcode = X86ISD::HADD; break;
6122       case ISD::FADD : NewOpcode = X86ISD::FHADD; break;
6123       case ISD::SUB : NewOpcode = X86ISD::HSUB; break;
6124       case ISD::FSUB : NewOpcode = X86ISD::FHSUB; break;
6125       }
6126  
6127       return DAG.getNode(NewOpcode, SDLoc(N), VT, InVec0, InVec1);
6128     }
6129   }
6130
6131   return SDValue();
6132 }
6133
6134 SDValue
6135 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6136   SDLoc dl(Op);
6137
6138   MVT VT = Op.getSimpleValueType();
6139   MVT ExtVT = VT.getVectorElementType();
6140   unsigned NumElems = Op.getNumOperands();
6141
6142   // Generate vectors for predicate vectors.
6143   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6144     return LowerBUILD_VECTORvXi1(Op, DAG);
6145
6146   // Vectors containing all zeros can be matched by pxor and xorps later
6147   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6148     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6149     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6150     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6151       return Op;
6152
6153     return getZeroVector(VT, Subtarget, DAG, dl);
6154   }
6155
6156   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6157   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6158   // vpcmpeqd on 256-bit vectors.
6159   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6160     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6161       return Op;
6162
6163     if (!VT.is512BitVector())
6164       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6165   }
6166
6167   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6168   if (Broadcast.getNode())
6169     return Broadcast;
6170
6171   unsigned EVTBits = ExtVT.getSizeInBits();
6172
6173   unsigned NumZero  = 0;
6174   unsigned NumNonZero = 0;
6175   unsigned NonZeros = 0;
6176   bool IsAllConstants = true;
6177   SmallSet<SDValue, 8> Values;
6178   for (unsigned i = 0; i < NumElems; ++i) {
6179     SDValue Elt = Op.getOperand(i);
6180     if (Elt.getOpcode() == ISD::UNDEF)
6181       continue;
6182     Values.insert(Elt);
6183     if (Elt.getOpcode() != ISD::Constant &&
6184         Elt.getOpcode() != ISD::ConstantFP)
6185       IsAllConstants = false;
6186     if (X86::isZeroNode(Elt))
6187       NumZero++;
6188     else {
6189       NonZeros |= (1 << i);
6190       NumNonZero++;
6191     }
6192   }
6193
6194   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6195   if (NumNonZero == 0)
6196     return DAG.getUNDEF(VT);
6197
6198   // Special case for single non-zero, non-undef, element.
6199   if (NumNonZero == 1) {
6200     unsigned Idx = countTrailingZeros(NonZeros);
6201     SDValue Item = Op.getOperand(Idx);
6202
6203     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6204     // the value are obviously zero, truncate the value to i32 and do the
6205     // insertion that way.  Only do this if the value is non-constant or if the
6206     // value is a constant being inserted into element 0.  It is cheaper to do
6207     // a constant pool load than it is to do a movd + shuffle.
6208     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6209         (!IsAllConstants || Idx == 0)) {
6210       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6211         // Handle SSE only.
6212         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6213         EVT VecVT = MVT::v4i32;
6214         unsigned VecElts = 4;
6215
6216         // Truncate the value (which may itself be a constant) to i32, and
6217         // convert it to a vector with movd (S2V+shuffle to zero extend).
6218         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6219         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6220         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6221
6222         // Now we have our 32-bit value zero extended in the low element of
6223         // a vector.  If Idx != 0, swizzle it into place.
6224         if (Idx != 0) {
6225           SmallVector<int, 4> Mask;
6226           Mask.push_back(Idx);
6227           for (unsigned i = 1; i != VecElts; ++i)
6228             Mask.push_back(i);
6229           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6230                                       &Mask[0]);
6231         }
6232         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6233       }
6234     }
6235
6236     // If we have a constant or non-constant insertion into the low element of
6237     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6238     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6239     // depending on what the source datatype is.
6240     if (Idx == 0) {
6241       if (NumZero == 0)
6242         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6243
6244       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6245           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6246         if (VT.is256BitVector() || VT.is512BitVector()) {
6247           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6248           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6249                              Item, DAG.getIntPtrConstant(0));
6250         }
6251         assert(VT.is128BitVector() && "Expected an SSE value type!");
6252         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6253         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6254         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6255       }
6256
6257       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6258         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6259         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6260         if (VT.is256BitVector()) {
6261           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6262           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6263         } else {
6264           assert(VT.is128BitVector() && "Expected an SSE value type!");
6265           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6266         }
6267         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6268       }
6269     }
6270
6271     // Is it a vector logical left shift?
6272     if (NumElems == 2 && Idx == 1 &&
6273         X86::isZeroNode(Op.getOperand(0)) &&
6274         !X86::isZeroNode(Op.getOperand(1))) {
6275       unsigned NumBits = VT.getSizeInBits();
6276       return getVShift(true, VT,
6277                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6278                                    VT, Op.getOperand(1)),
6279                        NumBits/2, DAG, *this, dl);
6280     }
6281
6282     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6283       return SDValue();
6284
6285     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6286     // is a non-constant being inserted into an element other than the low one,
6287     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6288     // movd/movss) to move this into the low element, then shuffle it into
6289     // place.
6290     if (EVTBits == 32) {
6291       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6292
6293       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6294       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6295       SmallVector<int, 8> MaskVec;
6296       for (unsigned i = 0; i != NumElems; ++i)
6297         MaskVec.push_back(i == Idx ? 0 : 1);
6298       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6299     }
6300   }
6301
6302   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6303   if (Values.size() == 1) {
6304     if (EVTBits == 32) {
6305       // Instead of a shuffle like this:
6306       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6307       // Check if it's possible to issue this instead.
6308       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6309       unsigned Idx = countTrailingZeros(NonZeros);
6310       SDValue Item = Op.getOperand(Idx);
6311       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6312         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6313     }
6314     return SDValue();
6315   }
6316
6317   // A vector full of immediates; various special cases are already
6318   // handled, so this is best done with a single constant-pool load.
6319   if (IsAllConstants)
6320     return SDValue();
6321
6322   // For AVX-length vectors, build the individual 128-bit pieces and use
6323   // shuffles to put them in place.
6324   if (VT.is256BitVector() || VT.is512BitVector()) {
6325     SmallVector<SDValue, 64> V;
6326     for (unsigned i = 0; i != NumElems; ++i)
6327       V.push_back(Op.getOperand(i));
6328
6329     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6330
6331     // Build both the lower and upper subvector.
6332     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6333                                 makeArrayRef(&V[0], NumElems/2));
6334     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6335                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6336
6337     // Recreate the wider vector with the lower and upper part.
6338     if (VT.is256BitVector())
6339       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6340     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6341   }
6342
6343   // Let legalizer expand 2-wide build_vectors.
6344   if (EVTBits == 64) {
6345     if (NumNonZero == 1) {
6346       // One half is zero or undef.
6347       unsigned Idx = countTrailingZeros(NonZeros);
6348       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6349                                  Op.getOperand(Idx));
6350       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6351     }
6352     return SDValue();
6353   }
6354
6355   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6356   if (EVTBits == 8 && NumElems == 16) {
6357     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6358                                         Subtarget, *this);
6359     if (V.getNode()) return V;
6360   }
6361
6362   if (EVTBits == 16 && NumElems == 8) {
6363     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6364                                       Subtarget, *this);
6365     if (V.getNode()) return V;
6366   }
6367
6368   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6369   if (EVTBits == 32 && NumElems == 4) {
6370     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6371                                       NumZero, DAG, Subtarget, *this);
6372     if (V.getNode())
6373       return V;
6374   }
6375
6376   // If element VT is == 32 bits, turn it into a number of shuffles.
6377   SmallVector<SDValue, 8> V(NumElems);
6378   if (NumElems == 4 && NumZero > 0) {
6379     for (unsigned i = 0; i < 4; ++i) {
6380       bool isZero = !(NonZeros & (1 << i));
6381       if (isZero)
6382         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6383       else
6384         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6385     }
6386
6387     for (unsigned i = 0; i < 2; ++i) {
6388       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6389         default: break;
6390         case 0:
6391           V[i] = V[i*2];  // Must be a zero vector.
6392           break;
6393         case 1:
6394           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6395           break;
6396         case 2:
6397           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6398           break;
6399         case 3:
6400           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6401           break;
6402       }
6403     }
6404
6405     bool Reverse1 = (NonZeros & 0x3) == 2;
6406     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6407     int MaskVec[] = {
6408       Reverse1 ? 1 : 0,
6409       Reverse1 ? 0 : 1,
6410       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6411       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6412     };
6413     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6414   }
6415
6416   if (Values.size() > 1 && VT.is128BitVector()) {
6417     // Check for a build vector of consecutive loads.
6418     for (unsigned i = 0; i < NumElems; ++i)
6419       V[i] = Op.getOperand(i);
6420
6421     // Check for elements which are consecutive loads.
6422     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6423     if (LD.getNode())
6424       return LD;
6425
6426     // Check for a build vector from mostly shuffle plus few inserting.
6427     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6428     if (Sh.getNode())
6429       return Sh;
6430
6431     // For SSE 4.1, use insertps to put the high elements into the low element.
6432     if (getSubtarget()->hasSSE41()) {
6433       SDValue Result;
6434       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6435         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6436       else
6437         Result = DAG.getUNDEF(VT);
6438
6439       for (unsigned i = 1; i < NumElems; ++i) {
6440         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6441         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6442                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6443       }
6444       return Result;
6445     }
6446
6447     // Otherwise, expand into a number of unpckl*, start by extending each of
6448     // our (non-undef) elements to the full vector width with the element in the
6449     // bottom slot of the vector (which generates no code for SSE).
6450     for (unsigned i = 0; i < NumElems; ++i) {
6451       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6452         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6453       else
6454         V[i] = DAG.getUNDEF(VT);
6455     }
6456
6457     // Next, we iteratively mix elements, e.g. for v4f32:
6458     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6459     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6460     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6461     unsigned EltStride = NumElems >> 1;
6462     while (EltStride != 0) {
6463       for (unsigned i = 0; i < EltStride; ++i) {
6464         // If V[i+EltStride] is undef and this is the first round of mixing,
6465         // then it is safe to just drop this shuffle: V[i] is already in the
6466         // right place, the one element (since it's the first round) being
6467         // inserted as undef can be dropped.  This isn't safe for successive
6468         // rounds because they will permute elements within both vectors.
6469         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6470             EltStride == NumElems/2)
6471           continue;
6472
6473         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6474       }
6475       EltStride >>= 1;
6476     }
6477     return V[0];
6478   }
6479   return SDValue();
6480 }
6481
6482 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6483 // to create 256-bit vectors from two other 128-bit ones.
6484 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6485   SDLoc dl(Op);
6486   MVT ResVT = Op.getSimpleValueType();
6487
6488   assert((ResVT.is256BitVector() ||
6489           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6490
6491   SDValue V1 = Op.getOperand(0);
6492   SDValue V2 = Op.getOperand(1);
6493   unsigned NumElems = ResVT.getVectorNumElements();
6494   if(ResVT.is256BitVector())
6495     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6496
6497   if (Op.getNumOperands() == 4) {
6498     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6499                                 ResVT.getVectorNumElements()/2);
6500     SDValue V3 = Op.getOperand(2);
6501     SDValue V4 = Op.getOperand(3);
6502     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6503       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6504   }
6505   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6506 }
6507
6508 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6509   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6510   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6511          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6512           Op.getNumOperands() == 4)));
6513
6514   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6515   // from two other 128-bit ones.
6516
6517   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6518   return LowerAVXCONCAT_VECTORS(Op, DAG);
6519 }
6520
6521 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6522                         bool hasInt256, unsigned *MaskOut = nullptr) {
6523   MVT EltVT = VT.getVectorElementType();
6524
6525   // There is no blend with immediate in AVX-512.
6526   if (VT.is512BitVector())
6527     return false;
6528
6529   if (!hasSSE41 || EltVT == MVT::i8)
6530     return false;
6531   if (!hasInt256 && VT == MVT::v16i16)
6532     return false;
6533
6534   unsigned MaskValue = 0;
6535   unsigned NumElems = VT.getVectorNumElements();
6536   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6537   unsigned NumLanes = (NumElems - 1) / 8 + 1;
6538   unsigned NumElemsInLane = NumElems / NumLanes;
6539
6540   // Blend for v16i16 should be symetric for the both lanes.
6541   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6542
6543     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6544     int EltIdx = MaskVals[i];
6545
6546     if ((EltIdx < 0 || EltIdx == (int)i) &&
6547         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6548       continue;
6549
6550     if (((unsigned)EltIdx == (i + NumElems)) &&
6551         (SndLaneEltIdx < 0 ||
6552          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6553       MaskValue |= (1 << i);
6554     else
6555       return false;
6556   }
6557
6558   if (MaskOut)
6559     *MaskOut = MaskValue;
6560   return true;
6561 }
6562
6563 // Try to lower a shuffle node into a simple blend instruction.
6564 // This function assumes isBlendMask returns true for this
6565 // SuffleVectorSDNode
6566 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6567                                           unsigned MaskValue,
6568                                           const X86Subtarget *Subtarget,
6569                                           SelectionDAG &DAG) {
6570   MVT VT = SVOp->getSimpleValueType(0);
6571   MVT EltVT = VT.getVectorElementType();
6572   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6573                      Subtarget->hasInt256() && "Trying to lower a "
6574                                                "VECTOR_SHUFFLE to a Blend but "
6575                                                "with the wrong mask"));
6576   SDValue V1 = SVOp->getOperand(0);
6577   SDValue V2 = SVOp->getOperand(1);
6578   SDLoc dl(SVOp);
6579   unsigned NumElems = VT.getVectorNumElements();
6580
6581   // Convert i32 vectors to floating point if it is not AVX2.
6582   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6583   MVT BlendVT = VT;
6584   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6585     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6586                                NumElems);
6587     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6588     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6589   }
6590
6591   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6592                             DAG.getConstant(MaskValue, MVT::i32));
6593   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6594 }
6595
6596 /// In vector type \p VT, return true if the element at index \p InputIdx
6597 /// falls on a different 128-bit lane than \p OutputIdx.
6598 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6599                                      unsigned OutputIdx) {
6600   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6601   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6602 }
6603
6604 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6605 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6606 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6607 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6608 /// zero.
6609 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6610                          SelectionDAG &DAG) {
6611   MVT VT = V1.getSimpleValueType();
6612   assert(VT.is128BitVector() || VT.is256BitVector());
6613
6614   MVT EltVT = VT.getVectorElementType();
6615   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6616   unsigned NumElts = VT.getVectorNumElements();
6617
6618   SmallVector<SDValue, 32> PshufbMask;
6619   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6620     int InputIdx = MaskVals[OutputIdx];
6621     unsigned InputByteIdx;
6622
6623     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6624       InputByteIdx = 0x80;
6625     else {
6626       // Cross lane is not allowed.
6627       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6628         return SDValue();
6629       InputByteIdx = InputIdx * EltSizeInBytes;
6630       // Index is an byte offset within the 128-bit lane.
6631       InputByteIdx &= 0xf;
6632     }
6633
6634     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6635       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6636       if (InputByteIdx != 0x80)
6637         ++InputByteIdx;
6638     }
6639   }
6640
6641   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6642   if (ShufVT != VT)
6643     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6644   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6645                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6646 }
6647
6648 // v8i16 shuffles - Prefer shuffles in the following order:
6649 // 1. [all]   pshuflw, pshufhw, optional move
6650 // 2. [ssse3] 1 x pshufb
6651 // 3. [ssse3] 2 x pshufb + 1 x por
6652 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6653 static SDValue
6654 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6655                          SelectionDAG &DAG) {
6656   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6657   SDValue V1 = SVOp->getOperand(0);
6658   SDValue V2 = SVOp->getOperand(1);
6659   SDLoc dl(SVOp);
6660   SmallVector<int, 8> MaskVals;
6661
6662   // Determine if more than 1 of the words in each of the low and high quadwords
6663   // of the result come from the same quadword of one of the two inputs.  Undef
6664   // mask values count as coming from any quadword, for better codegen.
6665   //
6666   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6667   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6668   unsigned LoQuad[] = { 0, 0, 0, 0 };
6669   unsigned HiQuad[] = { 0, 0, 0, 0 };
6670   // Indices of quads used.
6671   std::bitset<4> InputQuads;
6672   for (unsigned i = 0; i < 8; ++i) {
6673     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6674     int EltIdx = SVOp->getMaskElt(i);
6675     MaskVals.push_back(EltIdx);
6676     if (EltIdx < 0) {
6677       ++Quad[0];
6678       ++Quad[1];
6679       ++Quad[2];
6680       ++Quad[3];
6681       continue;
6682     }
6683     ++Quad[EltIdx / 4];
6684     InputQuads.set(EltIdx / 4);
6685   }
6686
6687   int BestLoQuad = -1;
6688   unsigned MaxQuad = 1;
6689   for (unsigned i = 0; i < 4; ++i) {
6690     if (LoQuad[i] > MaxQuad) {
6691       BestLoQuad = i;
6692       MaxQuad = LoQuad[i];
6693     }
6694   }
6695
6696   int BestHiQuad = -1;
6697   MaxQuad = 1;
6698   for (unsigned i = 0; i < 4; ++i) {
6699     if (HiQuad[i] > MaxQuad) {
6700       BestHiQuad = i;
6701       MaxQuad = HiQuad[i];
6702     }
6703   }
6704
6705   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6706   // of the two input vectors, shuffle them into one input vector so only a
6707   // single pshufb instruction is necessary. If there are more than 2 input
6708   // quads, disable the next transformation since it does not help SSSE3.
6709   bool V1Used = InputQuads[0] || InputQuads[1];
6710   bool V2Used = InputQuads[2] || InputQuads[3];
6711   if (Subtarget->hasSSSE3()) {
6712     if (InputQuads.count() == 2 && V1Used && V2Used) {
6713       BestLoQuad = InputQuads[0] ? 0 : 1;
6714       BestHiQuad = InputQuads[2] ? 2 : 3;
6715     }
6716     if (InputQuads.count() > 2) {
6717       BestLoQuad = -1;
6718       BestHiQuad = -1;
6719     }
6720   }
6721
6722   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6723   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6724   // words from all 4 input quadwords.
6725   SDValue NewV;
6726   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6727     int MaskV[] = {
6728       BestLoQuad < 0 ? 0 : BestLoQuad,
6729       BestHiQuad < 0 ? 1 : BestHiQuad
6730     };
6731     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6732                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6733                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6734     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6735
6736     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6737     // source words for the shuffle, to aid later transformations.
6738     bool AllWordsInNewV = true;
6739     bool InOrder[2] = { true, true };
6740     for (unsigned i = 0; i != 8; ++i) {
6741       int idx = MaskVals[i];
6742       if (idx != (int)i)
6743         InOrder[i/4] = false;
6744       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6745         continue;
6746       AllWordsInNewV = false;
6747       break;
6748     }
6749
6750     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6751     if (AllWordsInNewV) {
6752       for (int i = 0; i != 8; ++i) {
6753         int idx = MaskVals[i];
6754         if (idx < 0)
6755           continue;
6756         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6757         if ((idx != i) && idx < 4)
6758           pshufhw = false;
6759         if ((idx != i) && idx > 3)
6760           pshuflw = false;
6761       }
6762       V1 = NewV;
6763       V2Used = false;
6764       BestLoQuad = 0;
6765       BestHiQuad = 1;
6766     }
6767
6768     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6769     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6770     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6771       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6772       unsigned TargetMask = 0;
6773       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6774                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6775       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6776       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6777                              getShufflePSHUFLWImmediate(SVOp);
6778       V1 = NewV.getOperand(0);
6779       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6780     }
6781   }
6782
6783   // Promote splats to a larger type which usually leads to more efficient code.
6784   // FIXME: Is this true if pshufb is available?
6785   if (SVOp->isSplat())
6786     return PromoteSplat(SVOp, DAG);
6787
6788   // If we have SSSE3, and all words of the result are from 1 input vector,
6789   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6790   // is present, fall back to case 4.
6791   if (Subtarget->hasSSSE3()) {
6792     SmallVector<SDValue,16> pshufbMask;
6793
6794     // If we have elements from both input vectors, set the high bit of the
6795     // shuffle mask element to zero out elements that come from V2 in the V1
6796     // mask, and elements that come from V1 in the V2 mask, so that the two
6797     // results can be OR'd together.
6798     bool TwoInputs = V1Used && V2Used;
6799     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6800     if (!TwoInputs)
6801       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6802
6803     // Calculate the shuffle mask for the second input, shuffle it, and
6804     // OR it with the first shuffled input.
6805     CommuteVectorShuffleMask(MaskVals, 8);
6806     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6807     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6808     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6809   }
6810
6811   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6812   // and update MaskVals with new element order.
6813   std::bitset<8> InOrder;
6814   if (BestLoQuad >= 0) {
6815     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6816     for (int i = 0; i != 4; ++i) {
6817       int idx = MaskVals[i];
6818       if (idx < 0) {
6819         InOrder.set(i);
6820       } else if ((idx / 4) == BestLoQuad) {
6821         MaskV[i] = idx & 3;
6822         InOrder.set(i);
6823       }
6824     }
6825     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6826                                 &MaskV[0]);
6827
6828     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6829       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6830       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6831                                   NewV.getOperand(0),
6832                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6833     }
6834   }
6835
6836   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6837   // and update MaskVals with the new element order.
6838   if (BestHiQuad >= 0) {
6839     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6840     for (unsigned i = 4; i != 8; ++i) {
6841       int idx = MaskVals[i];
6842       if (idx < 0) {
6843         InOrder.set(i);
6844       } else if ((idx / 4) == BestHiQuad) {
6845         MaskV[i] = (idx & 3) + 4;
6846         InOrder.set(i);
6847       }
6848     }
6849     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6850                                 &MaskV[0]);
6851
6852     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6853       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6854       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6855                                   NewV.getOperand(0),
6856                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6857     }
6858   }
6859
6860   // In case BestHi & BestLo were both -1, which means each quadword has a word
6861   // from each of the four input quadwords, calculate the InOrder bitvector now
6862   // before falling through to the insert/extract cleanup.
6863   if (BestLoQuad == -1 && BestHiQuad == -1) {
6864     NewV = V1;
6865     for (int i = 0; i != 8; ++i)
6866       if (MaskVals[i] < 0 || MaskVals[i] == i)
6867         InOrder.set(i);
6868   }
6869
6870   // The other elements are put in the right place using pextrw and pinsrw.
6871   for (unsigned i = 0; i != 8; ++i) {
6872     if (InOrder[i])
6873       continue;
6874     int EltIdx = MaskVals[i];
6875     if (EltIdx < 0)
6876       continue;
6877     SDValue ExtOp = (EltIdx < 8) ?
6878       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6879                   DAG.getIntPtrConstant(EltIdx)) :
6880       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6881                   DAG.getIntPtrConstant(EltIdx - 8));
6882     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6883                        DAG.getIntPtrConstant(i));
6884   }
6885   return NewV;
6886 }
6887
6888 /// \brief v16i16 shuffles
6889 ///
6890 /// FIXME: We only support generation of a single pshufb currently.  We can
6891 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6892 /// well (e.g 2 x pshufb + 1 x por).
6893 static SDValue
6894 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6895   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6896   SDValue V1 = SVOp->getOperand(0);
6897   SDValue V2 = SVOp->getOperand(1);
6898   SDLoc dl(SVOp);
6899
6900   if (V2.getOpcode() != ISD::UNDEF)
6901     return SDValue();
6902
6903   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6904   return getPSHUFB(MaskVals, V1, dl, DAG);
6905 }
6906
6907 // v16i8 shuffles - Prefer shuffles in the following order:
6908 // 1. [ssse3] 1 x pshufb
6909 // 2. [ssse3] 2 x pshufb + 1 x por
6910 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6911 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6912                                         const X86Subtarget* Subtarget,
6913                                         SelectionDAG &DAG) {
6914   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6915   SDValue V1 = SVOp->getOperand(0);
6916   SDValue V2 = SVOp->getOperand(1);
6917   SDLoc dl(SVOp);
6918   ArrayRef<int> MaskVals = SVOp->getMask();
6919
6920   // Promote splats to a larger type which usually leads to more efficient code.
6921   // FIXME: Is this true if pshufb is available?
6922   if (SVOp->isSplat())
6923     return PromoteSplat(SVOp, DAG);
6924
6925   // If we have SSSE3, case 1 is generated when all result bytes come from
6926   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6927   // present, fall back to case 3.
6928
6929   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6930   if (Subtarget->hasSSSE3()) {
6931     SmallVector<SDValue,16> pshufbMask;
6932
6933     // If all result elements are from one input vector, then only translate
6934     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6935     //
6936     // Otherwise, we have elements from both input vectors, and must zero out
6937     // elements that come from V2 in the first mask, and V1 in the second mask
6938     // so that we can OR them together.
6939     for (unsigned i = 0; i != 16; ++i) {
6940       int EltIdx = MaskVals[i];
6941       if (EltIdx < 0 || EltIdx >= 16)
6942         EltIdx = 0x80;
6943       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6944     }
6945     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6946                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6947                                  MVT::v16i8, pshufbMask));
6948
6949     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6950     // the 2nd operand if it's undefined or zero.
6951     if (V2.getOpcode() == ISD::UNDEF ||
6952         ISD::isBuildVectorAllZeros(V2.getNode()))
6953       return V1;
6954
6955     // Calculate the shuffle mask for the second input, shuffle it, and
6956     // OR it with the first shuffled input.
6957     pshufbMask.clear();
6958     for (unsigned i = 0; i != 16; ++i) {
6959       int EltIdx = MaskVals[i];
6960       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6961       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6962     }
6963     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6964                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6965                                  MVT::v16i8, pshufbMask));
6966     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6967   }
6968
6969   // No SSSE3 - Calculate in place words and then fix all out of place words
6970   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6971   // the 16 different words that comprise the two doublequadword input vectors.
6972   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6973   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6974   SDValue NewV = V1;
6975   for (int i = 0; i != 8; ++i) {
6976     int Elt0 = MaskVals[i*2];
6977     int Elt1 = MaskVals[i*2+1];
6978
6979     // This word of the result is all undef, skip it.
6980     if (Elt0 < 0 && Elt1 < 0)
6981       continue;
6982
6983     // This word of the result is already in the correct place, skip it.
6984     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6985       continue;
6986
6987     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6988     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6989     SDValue InsElt;
6990
6991     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6992     // using a single extract together, load it and store it.
6993     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6994       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6995                            DAG.getIntPtrConstant(Elt1 / 2));
6996       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6997                         DAG.getIntPtrConstant(i));
6998       continue;
6999     }
7000
7001     // If Elt1 is defined, extract it from the appropriate source.  If the
7002     // source byte is not also odd, shift the extracted word left 8 bits
7003     // otherwise clear the bottom 8 bits if we need to do an or.
7004     if (Elt1 >= 0) {
7005       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7006                            DAG.getIntPtrConstant(Elt1 / 2));
7007       if ((Elt1 & 1) == 0)
7008         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7009                              DAG.getConstant(8,
7010                                   TLI.getShiftAmountTy(InsElt.getValueType())));
7011       else if (Elt0 >= 0)
7012         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7013                              DAG.getConstant(0xFF00, MVT::i16));
7014     }
7015     // If Elt0 is defined, extract it from the appropriate source.  If the
7016     // source byte is not also even, shift the extracted word right 8 bits. If
7017     // Elt1 was also defined, OR the extracted values together before
7018     // inserting them in the result.
7019     if (Elt0 >= 0) {
7020       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7021                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7022       if ((Elt0 & 1) != 0)
7023         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7024                               DAG.getConstant(8,
7025                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
7026       else if (Elt1 >= 0)
7027         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7028                              DAG.getConstant(0x00FF, MVT::i16));
7029       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7030                          : InsElt0;
7031     }
7032     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7033                        DAG.getIntPtrConstant(i));
7034   }
7035   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7036 }
7037
7038 // v32i8 shuffles - Translate to VPSHUFB if possible.
7039 static
7040 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7041                                  const X86Subtarget *Subtarget,
7042                                  SelectionDAG &DAG) {
7043   MVT VT = SVOp->getSimpleValueType(0);
7044   SDValue V1 = SVOp->getOperand(0);
7045   SDValue V2 = SVOp->getOperand(1);
7046   SDLoc dl(SVOp);
7047   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7048
7049   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7050   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7051   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7052
7053   // VPSHUFB may be generated if
7054   // (1) one of input vector is undefined or zeroinitializer.
7055   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7056   // And (2) the mask indexes don't cross the 128-bit lane.
7057   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7058       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7059     return SDValue();
7060
7061   if (V1IsAllZero && !V2IsAllZero) {
7062     CommuteVectorShuffleMask(MaskVals, 32);
7063     V1 = V2;
7064   }
7065   return getPSHUFB(MaskVals, V1, dl, DAG);
7066 }
7067
7068 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7069 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7070 /// done when every pair / quad of shuffle mask elements point to elements in
7071 /// the right sequence. e.g.
7072 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7073 static
7074 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7075                                  SelectionDAG &DAG) {
7076   MVT VT = SVOp->getSimpleValueType(0);
7077   SDLoc dl(SVOp);
7078   unsigned NumElems = VT.getVectorNumElements();
7079   MVT NewVT;
7080   unsigned Scale;
7081   switch (VT.SimpleTy) {
7082   default: llvm_unreachable("Unexpected!");
7083   case MVT::v2i64:
7084   case MVT::v2f64:
7085            return SDValue(SVOp, 0);
7086   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
7087   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
7088   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
7089   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
7090   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7091   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
7092   }
7093
7094   SmallVector<int, 8> MaskVec;
7095   for (unsigned i = 0; i != NumElems; i += Scale) {
7096     int StartIdx = -1;
7097     for (unsigned j = 0; j != Scale; ++j) {
7098       int EltIdx = SVOp->getMaskElt(i+j);
7099       if (EltIdx < 0)
7100         continue;
7101       if (StartIdx < 0)
7102         StartIdx = (EltIdx / Scale);
7103       if (EltIdx != (int)(StartIdx*Scale + j))
7104         return SDValue();
7105     }
7106     MaskVec.push_back(StartIdx);
7107   }
7108
7109   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7110   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7111   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7112 }
7113
7114 /// getVZextMovL - Return a zero-extending vector move low node.
7115 ///
7116 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7117                             SDValue SrcOp, SelectionDAG &DAG,
7118                             const X86Subtarget *Subtarget, SDLoc dl) {
7119   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7120     LoadSDNode *LD = nullptr;
7121     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7122       LD = dyn_cast<LoadSDNode>(SrcOp);
7123     if (!LD) {
7124       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7125       // instead.
7126       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7127       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7128           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7129           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7130           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7131         // PR2108
7132         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7133         return DAG.getNode(ISD::BITCAST, dl, VT,
7134                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7135                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7136                                                    OpVT,
7137                                                    SrcOp.getOperand(0)
7138                                                           .getOperand(0))));
7139       }
7140     }
7141   }
7142
7143   return DAG.getNode(ISD::BITCAST, dl, VT,
7144                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7145                                  DAG.getNode(ISD::BITCAST, dl,
7146                                              OpVT, SrcOp)));
7147 }
7148
7149 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7150 /// which could not be matched by any known target speficic shuffle
7151 static SDValue
7152 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7153
7154   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7155   if (NewOp.getNode())
7156     return NewOp;
7157
7158   MVT VT = SVOp->getSimpleValueType(0);
7159
7160   unsigned NumElems = VT.getVectorNumElements();
7161   unsigned NumLaneElems = NumElems / 2;
7162
7163   SDLoc dl(SVOp);
7164   MVT EltVT = VT.getVectorElementType();
7165   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7166   SDValue Output[2];
7167
7168   SmallVector<int, 16> Mask;
7169   for (unsigned l = 0; l < 2; ++l) {
7170     // Build a shuffle mask for the output, discovering on the fly which
7171     // input vectors to use as shuffle operands (recorded in InputUsed).
7172     // If building a suitable shuffle vector proves too hard, then bail
7173     // out with UseBuildVector set.
7174     bool UseBuildVector = false;
7175     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7176     unsigned LaneStart = l * NumLaneElems;
7177     for (unsigned i = 0; i != NumLaneElems; ++i) {
7178       // The mask element.  This indexes into the input.
7179       int Idx = SVOp->getMaskElt(i+LaneStart);
7180       if (Idx < 0) {
7181         // the mask element does not index into any input vector.
7182         Mask.push_back(-1);
7183         continue;
7184       }
7185
7186       // The input vector this mask element indexes into.
7187       int Input = Idx / NumLaneElems;
7188
7189       // Turn the index into an offset from the start of the input vector.
7190       Idx -= Input * NumLaneElems;
7191
7192       // Find or create a shuffle vector operand to hold this input.
7193       unsigned OpNo;
7194       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7195         if (InputUsed[OpNo] == Input)
7196           // This input vector is already an operand.
7197           break;
7198         if (InputUsed[OpNo] < 0) {
7199           // Create a new operand for this input vector.
7200           InputUsed[OpNo] = Input;
7201           break;
7202         }
7203       }
7204
7205       if (OpNo >= array_lengthof(InputUsed)) {
7206         // More than two input vectors used!  Give up on trying to create a
7207         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7208         UseBuildVector = true;
7209         break;
7210       }
7211
7212       // Add the mask index for the new shuffle vector.
7213       Mask.push_back(Idx + OpNo * NumLaneElems);
7214     }
7215
7216     if (UseBuildVector) {
7217       SmallVector<SDValue, 16> SVOps;
7218       for (unsigned i = 0; i != NumLaneElems; ++i) {
7219         // The mask element.  This indexes into the input.
7220         int Idx = SVOp->getMaskElt(i+LaneStart);
7221         if (Idx < 0) {
7222           SVOps.push_back(DAG.getUNDEF(EltVT));
7223           continue;
7224         }
7225
7226         // The input vector this mask element indexes into.
7227         int Input = Idx / NumElems;
7228
7229         // Turn the index into an offset from the start of the input vector.
7230         Idx -= Input * NumElems;
7231
7232         // Extract the vector element by hand.
7233         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7234                                     SVOp->getOperand(Input),
7235                                     DAG.getIntPtrConstant(Idx)));
7236       }
7237
7238       // Construct the output using a BUILD_VECTOR.
7239       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7240     } else if (InputUsed[0] < 0) {
7241       // No input vectors were used! The result is undefined.
7242       Output[l] = DAG.getUNDEF(NVT);
7243     } else {
7244       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7245                                         (InputUsed[0] % 2) * NumLaneElems,
7246                                         DAG, dl);
7247       // If only one input was used, use an undefined vector for the other.
7248       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7249         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7250                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7251       // At least one input vector was used. Create a new shuffle vector.
7252       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7253     }
7254
7255     Mask.clear();
7256   }
7257
7258   // Concatenate the result back
7259   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7260 }
7261
7262 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7263 /// 4 elements, and match them with several different shuffle types.
7264 static SDValue
7265 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7266   SDValue V1 = SVOp->getOperand(0);
7267   SDValue V2 = SVOp->getOperand(1);
7268   SDLoc dl(SVOp);
7269   MVT VT = SVOp->getSimpleValueType(0);
7270
7271   assert(VT.is128BitVector() && "Unsupported vector size");
7272
7273   std::pair<int, int> Locs[4];
7274   int Mask1[] = { -1, -1, -1, -1 };
7275   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7276
7277   unsigned NumHi = 0;
7278   unsigned NumLo = 0;
7279   for (unsigned i = 0; i != 4; ++i) {
7280     int Idx = PermMask[i];
7281     if (Idx < 0) {
7282       Locs[i] = std::make_pair(-1, -1);
7283     } else {
7284       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7285       if (Idx < 4) {
7286         Locs[i] = std::make_pair(0, NumLo);
7287         Mask1[NumLo] = Idx;
7288         NumLo++;
7289       } else {
7290         Locs[i] = std::make_pair(1, NumHi);
7291         if (2+NumHi < 4)
7292           Mask1[2+NumHi] = Idx;
7293         NumHi++;
7294       }
7295     }
7296   }
7297
7298   if (NumLo <= 2 && NumHi <= 2) {
7299     // If no more than two elements come from either vector. This can be
7300     // implemented with two shuffles. First shuffle gather the elements.
7301     // The second shuffle, which takes the first shuffle as both of its
7302     // vector operands, put the elements into the right order.
7303     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7304
7305     int Mask2[] = { -1, -1, -1, -1 };
7306
7307     for (unsigned i = 0; i != 4; ++i)
7308       if (Locs[i].first != -1) {
7309         unsigned Idx = (i < 2) ? 0 : 4;
7310         Idx += Locs[i].first * 2 + Locs[i].second;
7311         Mask2[i] = Idx;
7312       }
7313
7314     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7315   }
7316
7317   if (NumLo == 3 || NumHi == 3) {
7318     // Otherwise, we must have three elements from one vector, call it X, and
7319     // one element from the other, call it Y.  First, use a shufps to build an
7320     // intermediate vector with the one element from Y and the element from X
7321     // that will be in the same half in the final destination (the indexes don't
7322     // matter). Then, use a shufps to build the final vector, taking the half
7323     // containing the element from Y from the intermediate, and the other half
7324     // from X.
7325     if (NumHi == 3) {
7326       // Normalize it so the 3 elements come from V1.
7327       CommuteVectorShuffleMask(PermMask, 4);
7328       std::swap(V1, V2);
7329     }
7330
7331     // Find the element from V2.
7332     unsigned HiIndex;
7333     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7334       int Val = PermMask[HiIndex];
7335       if (Val < 0)
7336         continue;
7337       if (Val >= 4)
7338         break;
7339     }
7340
7341     Mask1[0] = PermMask[HiIndex];
7342     Mask1[1] = -1;
7343     Mask1[2] = PermMask[HiIndex^1];
7344     Mask1[3] = -1;
7345     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7346
7347     if (HiIndex >= 2) {
7348       Mask1[0] = PermMask[0];
7349       Mask1[1] = PermMask[1];
7350       Mask1[2] = HiIndex & 1 ? 6 : 4;
7351       Mask1[3] = HiIndex & 1 ? 4 : 6;
7352       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7353     }
7354
7355     Mask1[0] = HiIndex & 1 ? 2 : 0;
7356     Mask1[1] = HiIndex & 1 ? 0 : 2;
7357     Mask1[2] = PermMask[2];
7358     Mask1[3] = PermMask[3];
7359     if (Mask1[2] >= 0)
7360       Mask1[2] += 4;
7361     if (Mask1[3] >= 0)
7362       Mask1[3] += 4;
7363     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7364   }
7365
7366   // Break it into (shuffle shuffle_hi, shuffle_lo).
7367   int LoMask[] = { -1, -1, -1, -1 };
7368   int HiMask[] = { -1, -1, -1, -1 };
7369
7370   int *MaskPtr = LoMask;
7371   unsigned MaskIdx = 0;
7372   unsigned LoIdx = 0;
7373   unsigned HiIdx = 2;
7374   for (unsigned i = 0; i != 4; ++i) {
7375     if (i == 2) {
7376       MaskPtr = HiMask;
7377       MaskIdx = 1;
7378       LoIdx = 0;
7379       HiIdx = 2;
7380     }
7381     int Idx = PermMask[i];
7382     if (Idx < 0) {
7383       Locs[i] = std::make_pair(-1, -1);
7384     } else if (Idx < 4) {
7385       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7386       MaskPtr[LoIdx] = Idx;
7387       LoIdx++;
7388     } else {
7389       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7390       MaskPtr[HiIdx] = Idx;
7391       HiIdx++;
7392     }
7393   }
7394
7395   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7396   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7397   int MaskOps[] = { -1, -1, -1, -1 };
7398   for (unsigned i = 0; i != 4; ++i)
7399     if (Locs[i].first != -1)
7400       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7401   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7402 }
7403
7404 static bool MayFoldVectorLoad(SDValue V) {
7405   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7406     V = V.getOperand(0);
7407
7408   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7409     V = V.getOperand(0);
7410   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7411       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7412     // BUILD_VECTOR (load), undef
7413     V = V.getOperand(0);
7414
7415   return MayFoldLoad(V);
7416 }
7417
7418 static
7419 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7420   MVT VT = Op.getSimpleValueType();
7421
7422   // Canonizalize to v2f64.
7423   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7424   return DAG.getNode(ISD::BITCAST, dl, VT,
7425                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7426                                           V1, DAG));
7427 }
7428
7429 static
7430 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7431                         bool HasSSE2) {
7432   SDValue V1 = Op.getOperand(0);
7433   SDValue V2 = Op.getOperand(1);
7434   MVT VT = Op.getSimpleValueType();
7435
7436   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7437
7438   if (HasSSE2 && VT == MVT::v2f64)
7439     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7440
7441   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7442   return DAG.getNode(ISD::BITCAST, dl, VT,
7443                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7444                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7445                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7446 }
7447
7448 static
7449 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7450   SDValue V1 = Op.getOperand(0);
7451   SDValue V2 = Op.getOperand(1);
7452   MVT VT = Op.getSimpleValueType();
7453
7454   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7455          "unsupported shuffle type");
7456
7457   if (V2.getOpcode() == ISD::UNDEF)
7458     V2 = V1;
7459
7460   // v4i32 or v4f32
7461   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7462 }
7463
7464 static
7465 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7466   SDValue V1 = Op.getOperand(0);
7467   SDValue V2 = Op.getOperand(1);
7468   MVT VT = Op.getSimpleValueType();
7469   unsigned NumElems = VT.getVectorNumElements();
7470
7471   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7472   // operand of these instructions is only memory, so check if there's a
7473   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7474   // same masks.
7475   bool CanFoldLoad = false;
7476
7477   // Trivial case, when V2 comes from a load.
7478   if (MayFoldVectorLoad(V2))
7479     CanFoldLoad = true;
7480
7481   // When V1 is a load, it can be folded later into a store in isel, example:
7482   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7483   //    turns into:
7484   //  (MOVLPSmr addr:$src1, VR128:$src2)
7485   // So, recognize this potential and also use MOVLPS or MOVLPD
7486   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7487     CanFoldLoad = true;
7488
7489   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7490   if (CanFoldLoad) {
7491     if (HasSSE2 && NumElems == 2)
7492       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7493
7494     if (NumElems == 4)
7495       // If we don't care about the second element, proceed to use movss.
7496       if (SVOp->getMaskElt(1) != -1)
7497         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7498   }
7499
7500   // movl and movlp will both match v2i64, but v2i64 is never matched by
7501   // movl earlier because we make it strict to avoid messing with the movlp load
7502   // folding logic (see the code above getMOVLP call). Match it here then,
7503   // this is horrible, but will stay like this until we move all shuffle
7504   // matching to x86 specific nodes. Note that for the 1st condition all
7505   // types are matched with movsd.
7506   if (HasSSE2) {
7507     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7508     // as to remove this logic from here, as much as possible
7509     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7510       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7511     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7512   }
7513
7514   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7515
7516   // Invert the operand order and use SHUFPS to match it.
7517   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7518                               getShuffleSHUFImmediate(SVOp), DAG);
7519 }
7520
7521 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7522                                          SelectionDAG &DAG) {
7523   SDLoc dl(Load);
7524   MVT VT = Load->getSimpleValueType(0);
7525   MVT EVT = VT.getVectorElementType();
7526   SDValue Addr = Load->getOperand(1);
7527   SDValue NewAddr = DAG.getNode(
7528       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7529       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7530
7531   SDValue NewLoad =
7532       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7533                   DAG.getMachineFunction().getMachineMemOperand(
7534                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7535   return NewLoad;
7536 }
7537
7538 // It is only safe to call this function if isINSERTPSMask is true for
7539 // this shufflevector mask.
7540 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7541                            SelectionDAG &DAG) {
7542   // Generate an insertps instruction when inserting an f32 from memory onto a
7543   // v4f32 or when copying a member from one v4f32 to another.
7544   // We also use it for transferring i32 from one register to another,
7545   // since it simply copies the same bits.
7546   // If we're transferring an i32 from memory to a specific element in a
7547   // register, we output a generic DAG that will match the PINSRD
7548   // instruction.
7549   MVT VT = SVOp->getSimpleValueType(0);
7550   MVT EVT = VT.getVectorElementType();
7551   SDValue V1 = SVOp->getOperand(0);
7552   SDValue V2 = SVOp->getOperand(1);
7553   auto Mask = SVOp->getMask();
7554   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7555          "unsupported vector type for insertps/pinsrd");
7556
7557   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7558   auto FromV2Predicate = [](const int &i) { return i >= 4; };
7559   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7560
7561   SDValue From;
7562   SDValue To;
7563   unsigned DestIndex;
7564   if (FromV1 == 1) {
7565     From = V1;
7566     To = V2;
7567     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7568                 Mask.begin();
7569   } else {
7570     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7571            "More than one element from V1 and from V2, or no elements from one "
7572            "of the vectors. This case should not have returned true from "
7573            "isINSERTPSMask");
7574     From = V2;
7575     To = V1;
7576     DestIndex =
7577         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7578   }
7579
7580   if (MayFoldLoad(From)) {
7581     // Trivial case, when From comes from a load and is only used by the
7582     // shuffle. Make it use insertps from the vector that we need from that
7583     // load.
7584     SDValue NewLoad =
7585         NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7586     if (!NewLoad.getNode())
7587       return SDValue();
7588
7589     if (EVT == MVT::f32) {
7590       // Create this as a scalar to vector to match the instruction pattern.
7591       SDValue LoadScalarToVector =
7592           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7593       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7594       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7595                          InsertpsMask);
7596     } else { // EVT == MVT::i32
7597       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7598       // instruction, to match the PINSRD instruction, which loads an i32 to a
7599       // certain vector element.
7600       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7601                          DAG.getConstant(DestIndex, MVT::i32));
7602     }
7603   }
7604
7605   // Vector-element-to-vector
7606   unsigned SrcIndex = Mask[DestIndex] % 4;
7607   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7608   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7609 }
7610
7611 // Reduce a vector shuffle to zext.
7612 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7613                                     SelectionDAG &DAG) {
7614   // PMOVZX is only available from SSE41.
7615   if (!Subtarget->hasSSE41())
7616     return SDValue();
7617
7618   MVT VT = Op.getSimpleValueType();
7619
7620   // Only AVX2 support 256-bit vector integer extending.
7621   if (!Subtarget->hasInt256() && VT.is256BitVector())
7622     return SDValue();
7623
7624   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7625   SDLoc DL(Op);
7626   SDValue V1 = Op.getOperand(0);
7627   SDValue V2 = Op.getOperand(1);
7628   unsigned NumElems = VT.getVectorNumElements();
7629
7630   // Extending is an unary operation and the element type of the source vector
7631   // won't be equal to or larger than i64.
7632   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7633       VT.getVectorElementType() == MVT::i64)
7634     return SDValue();
7635
7636   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7637   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7638   while ((1U << Shift) < NumElems) {
7639     if (SVOp->getMaskElt(1U << Shift) == 1)
7640       break;
7641     Shift += 1;
7642     // The maximal ratio is 8, i.e. from i8 to i64.
7643     if (Shift > 3)
7644       return SDValue();
7645   }
7646
7647   // Check the shuffle mask.
7648   unsigned Mask = (1U << Shift) - 1;
7649   for (unsigned i = 0; i != NumElems; ++i) {
7650     int EltIdx = SVOp->getMaskElt(i);
7651     if ((i & Mask) != 0 && EltIdx != -1)
7652       return SDValue();
7653     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7654       return SDValue();
7655   }
7656
7657   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7658   MVT NeVT = MVT::getIntegerVT(NBits);
7659   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7660
7661   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7662     return SDValue();
7663
7664   // Simplify the operand as it's prepared to be fed into shuffle.
7665   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7666   if (V1.getOpcode() == ISD::BITCAST &&
7667       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7668       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7669       V1.getOperand(0).getOperand(0)
7670         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7671     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7672     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7673     ConstantSDNode *CIdx =
7674       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7675     // If it's foldable, i.e. normal load with single use, we will let code
7676     // selection to fold it. Otherwise, we will short the conversion sequence.
7677     if (CIdx && CIdx->getZExtValue() == 0 &&
7678         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7679       MVT FullVT = V.getSimpleValueType();
7680       MVT V1VT = V1.getSimpleValueType();
7681       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7682         // The "ext_vec_elt" node is wider than the result node.
7683         // In this case we should extract subvector from V.
7684         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7685         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7686         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7687                                         FullVT.getVectorNumElements()/Ratio);
7688         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7689                         DAG.getIntPtrConstant(0));
7690       }
7691       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7692     }
7693   }
7694
7695   return DAG.getNode(ISD::BITCAST, DL, VT,
7696                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7697 }
7698
7699 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7700                                       SelectionDAG &DAG) {
7701   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7702   MVT VT = Op.getSimpleValueType();
7703   SDLoc dl(Op);
7704   SDValue V1 = Op.getOperand(0);
7705   SDValue V2 = Op.getOperand(1);
7706
7707   if (isZeroShuffle(SVOp))
7708     return getZeroVector(VT, Subtarget, DAG, dl);
7709
7710   // Handle splat operations
7711   if (SVOp->isSplat()) {
7712     // Use vbroadcast whenever the splat comes from a foldable load
7713     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7714     if (Broadcast.getNode())
7715       return Broadcast;
7716   }
7717
7718   // Check integer expanding shuffles.
7719   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7720   if (NewOp.getNode())
7721     return NewOp;
7722
7723   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7724   // do it!
7725   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7726       VT == MVT::v32i8) {
7727     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7728     if (NewOp.getNode())
7729       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7730   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7731     // FIXME: Figure out a cleaner way to do this.
7732     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7733       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7734       if (NewOp.getNode()) {
7735         MVT NewVT = NewOp.getSimpleValueType();
7736         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7737                                NewVT, true, false))
7738           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7739                               dl);
7740       }
7741     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7742       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7743       if (NewOp.getNode()) {
7744         MVT NewVT = NewOp.getSimpleValueType();
7745         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7746           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7747                               dl);
7748       }
7749     }
7750   }
7751   return SDValue();
7752 }
7753
7754 SDValue
7755 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7756   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7757   SDValue V1 = Op.getOperand(0);
7758   SDValue V2 = Op.getOperand(1);
7759   MVT VT = Op.getSimpleValueType();
7760   SDLoc dl(Op);
7761   unsigned NumElems = VT.getVectorNumElements();
7762   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7763   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7764   bool V1IsSplat = false;
7765   bool V2IsSplat = false;
7766   bool HasSSE2 = Subtarget->hasSSE2();
7767   bool HasFp256    = Subtarget->hasFp256();
7768   bool HasInt256   = Subtarget->hasInt256();
7769   MachineFunction &MF = DAG.getMachineFunction();
7770   bool OptForSize = MF.getFunction()->getAttributes().
7771     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7772
7773   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7774
7775   if (V1IsUndef && V2IsUndef)
7776     return DAG.getUNDEF(VT);
7777
7778   // When we create a shuffle node we put the UNDEF node to second operand,
7779   // but in some cases the first operand may be transformed to UNDEF.
7780   // In this case we should just commute the node.
7781   if (V1IsUndef)
7782     return CommuteVectorShuffle(SVOp, DAG);
7783
7784   // Vector shuffle lowering takes 3 steps:
7785   //
7786   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7787   //    narrowing and commutation of operands should be handled.
7788   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7789   //    shuffle nodes.
7790   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7791   //    so the shuffle can be broken into other shuffles and the legalizer can
7792   //    try the lowering again.
7793   //
7794   // The general idea is that no vector_shuffle operation should be left to
7795   // be matched during isel, all of them must be converted to a target specific
7796   // node here.
7797
7798   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7799   // narrowing and commutation of operands should be handled. The actual code
7800   // doesn't include all of those, work in progress...
7801   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7802   if (NewOp.getNode())
7803     return NewOp;
7804
7805   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7806
7807   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7808   // unpckh_undef). Only use pshufd if speed is more important than size.
7809   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7810     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7811   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7812     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7813
7814   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7815       V2IsUndef && MayFoldVectorLoad(V1))
7816     return getMOVDDup(Op, dl, V1, DAG);
7817
7818   if (isMOVHLPS_v_undef_Mask(M, VT))
7819     return getMOVHighToLow(Op, dl, DAG);
7820
7821   // Use to match splats
7822   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7823       (VT == MVT::v2f64 || VT == MVT::v2i64))
7824     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7825
7826   if (isPSHUFDMask(M, VT)) {
7827     // The actual implementation will match the mask in the if above and then
7828     // during isel it can match several different instructions, not only pshufd
7829     // as its name says, sad but true, emulate the behavior for now...
7830     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7831       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7832
7833     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7834
7835     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7836       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7837
7838     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7839       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7840                                   DAG);
7841
7842     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7843                                 TargetMask, DAG);
7844   }
7845
7846   if (isPALIGNRMask(M, VT, Subtarget))
7847     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7848                                 getShufflePALIGNRImmediate(SVOp),
7849                                 DAG);
7850
7851   // Check if this can be converted into a logical shift.
7852   bool isLeft = false;
7853   unsigned ShAmt = 0;
7854   SDValue ShVal;
7855   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7856   if (isShift && ShVal.hasOneUse()) {
7857     // If the shifted value has multiple uses, it may be cheaper to use
7858     // v_set0 + movlhps or movhlps, etc.
7859     MVT EltVT = VT.getVectorElementType();
7860     ShAmt *= EltVT.getSizeInBits();
7861     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7862   }
7863
7864   if (isMOVLMask(M, VT)) {
7865     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7866       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7867     if (!isMOVLPMask(M, VT)) {
7868       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7869         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7870
7871       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7872         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7873     }
7874   }
7875
7876   // FIXME: fold these into legal mask.
7877   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7878     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7879
7880   if (isMOVHLPSMask(M, VT))
7881     return getMOVHighToLow(Op, dl, DAG);
7882
7883   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7884     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7885
7886   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7887     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7888
7889   if (isMOVLPMask(M, VT))
7890     return getMOVLP(Op, dl, DAG, HasSSE2);
7891
7892   if (ShouldXformToMOVHLPS(M, VT) ||
7893       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7894     return CommuteVectorShuffle(SVOp, DAG);
7895
7896   if (isShift) {
7897     // No better options. Use a vshldq / vsrldq.
7898     MVT EltVT = VT.getVectorElementType();
7899     ShAmt *= EltVT.getSizeInBits();
7900     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7901   }
7902
7903   bool Commuted = false;
7904   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7905   // 1,1,1,1 -> v8i16 though.
7906   V1IsSplat = isSplatVector(V1.getNode());
7907   V2IsSplat = isSplatVector(V2.getNode());
7908
7909   // Canonicalize the splat or undef, if present, to be on the RHS.
7910   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7911     CommuteVectorShuffleMask(M, NumElems);
7912     std::swap(V1, V2);
7913     std::swap(V1IsSplat, V2IsSplat);
7914     Commuted = true;
7915   }
7916
7917   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7918     // Shuffling low element of v1 into undef, just return v1.
7919     if (V2IsUndef)
7920       return V1;
7921     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7922     // the instruction selector will not match, so get a canonical MOVL with
7923     // swapped operands to undo the commute.
7924     return getMOVL(DAG, dl, VT, V2, V1);
7925   }
7926
7927   if (isUNPCKLMask(M, VT, HasInt256))
7928     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7929
7930   if (isUNPCKHMask(M, VT, HasInt256))
7931     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7932
7933   if (V2IsSplat) {
7934     // Normalize mask so all entries that point to V2 points to its first
7935     // element then try to match unpck{h|l} again. If match, return a
7936     // new vector_shuffle with the corrected mask.p
7937     SmallVector<int, 8> NewMask(M.begin(), M.end());
7938     NormalizeMask(NewMask, NumElems);
7939     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7940       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7941     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7942       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7943   }
7944
7945   if (Commuted) {
7946     // Commute is back and try unpck* again.
7947     // FIXME: this seems wrong.
7948     CommuteVectorShuffleMask(M, NumElems);
7949     std::swap(V1, V2);
7950     std::swap(V1IsSplat, V2IsSplat);
7951
7952     if (isUNPCKLMask(M, VT, HasInt256))
7953       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7954
7955     if (isUNPCKHMask(M, VT, HasInt256))
7956       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7957   }
7958
7959   // Normalize the node to match x86 shuffle ops if needed
7960   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7961     return CommuteVectorShuffle(SVOp, DAG);
7962
7963   // The checks below are all present in isShuffleMaskLegal, but they are
7964   // inlined here right now to enable us to directly emit target specific
7965   // nodes, and remove one by one until they don't return Op anymore.
7966
7967   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7968       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7969     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7970       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7971   }
7972
7973   if (isPSHUFHWMask(M, VT, HasInt256))
7974     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7975                                 getShufflePSHUFHWImmediate(SVOp),
7976                                 DAG);
7977
7978   if (isPSHUFLWMask(M, VT, HasInt256))
7979     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7980                                 getShufflePSHUFLWImmediate(SVOp),
7981                                 DAG);
7982
7983   if (isSHUFPMask(M, VT))
7984     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7985                                 getShuffleSHUFImmediate(SVOp), DAG);
7986
7987   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7988     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7989   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7990     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7991
7992   //===--------------------------------------------------------------------===//
7993   // Generate target specific nodes for 128 or 256-bit shuffles only
7994   // supported in the AVX instruction set.
7995   //
7996
7997   // Handle VMOVDDUPY permutations
7998   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7999     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8000
8001   // Handle VPERMILPS/D* permutations
8002   if (isVPERMILPMask(M, VT)) {
8003     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8004       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8005                                   getShuffleSHUFImmediate(SVOp), DAG);
8006     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8007                                 getShuffleSHUFImmediate(SVOp), DAG);
8008   }
8009
8010   unsigned Idx;
8011   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8012     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8013                               Idx*(NumElems/2), DAG, dl);
8014
8015   // Handle VPERM2F128/VPERM2I128 permutations
8016   if (isVPERM2X128Mask(M, VT, HasFp256))
8017     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8018                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8019
8020   unsigned MaskValue;
8021   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8022                   &MaskValue))
8023     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8024
8025   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8026     return getINSERTPS(SVOp, dl, DAG);
8027
8028   unsigned Imm8;
8029   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8030     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8031
8032   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8033       VT.is512BitVector()) {
8034     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8035     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8036     SmallVector<SDValue, 16> permclMask;
8037     for (unsigned i = 0; i != NumElems; ++i) {
8038       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8039     }
8040
8041     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8042     if (V2IsUndef)
8043       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8044       return DAG.getNode(X86ISD::VPERMV, dl, VT,
8045                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8046     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8047                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8048   }
8049
8050   //===--------------------------------------------------------------------===//
8051   // Since no target specific shuffle was selected for this generic one,
8052   // lower it into other known shuffles. FIXME: this isn't true yet, but
8053   // this is the plan.
8054   //
8055
8056   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8057   if (VT == MVT::v8i16) {
8058     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8059     if (NewOp.getNode())
8060       return NewOp;
8061   }
8062
8063   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8064     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8065     if (NewOp.getNode())
8066       return NewOp;
8067   }
8068
8069   if (VT == MVT::v16i8) {
8070     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8071     if (NewOp.getNode())
8072       return NewOp;
8073   }
8074
8075   if (VT == MVT::v32i8) {
8076     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8077     if (NewOp.getNode())
8078       return NewOp;
8079   }
8080
8081   // Handle all 128-bit wide vectors with 4 elements, and match them with
8082   // several different shuffle types.
8083   if (NumElems == 4 && VT.is128BitVector())
8084     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8085
8086   // Handle general 256-bit shuffles
8087   if (VT.is256BitVector())
8088     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8089
8090   return SDValue();
8091 }
8092
8093 // This function assumes its argument is a BUILD_VECTOR of constants or
8094 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8095 // true.
8096 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8097                                     unsigned &MaskValue) {
8098   MaskValue = 0;
8099   unsigned NumElems = BuildVector->getNumOperands();
8100   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8101   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8102   unsigned NumElemsInLane = NumElems / NumLanes;
8103
8104   // Blend for v16i16 should be symetric for the both lanes.
8105   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8106     SDValue EltCond = BuildVector->getOperand(i);
8107     SDValue SndLaneEltCond =
8108         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8109
8110     int Lane1Cond = -1, Lane2Cond = -1;
8111     if (isa<ConstantSDNode>(EltCond))
8112       Lane1Cond = !isZero(EltCond);
8113     if (isa<ConstantSDNode>(SndLaneEltCond))
8114       Lane2Cond = !isZero(SndLaneEltCond);
8115
8116     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8117       // Lane1Cond != 0, means we want the first argument.
8118       // Lane1Cond == 0, means we want the second argument.
8119       // The encoding of this argument is 0 for the first argument, 1
8120       // for the second. Therefore, invert the condition.
8121       MaskValue |= !Lane1Cond << i;
8122     else if (Lane1Cond < 0)
8123       MaskValue |= !Lane2Cond << i;
8124     else
8125       return false;
8126   }
8127   return true;
8128 }
8129
8130 // Try to lower a vselect node into a simple blend instruction.
8131 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8132                                    SelectionDAG &DAG) {
8133   SDValue Cond = Op.getOperand(0);
8134   SDValue LHS = Op.getOperand(1);
8135   SDValue RHS = Op.getOperand(2);
8136   SDLoc dl(Op);
8137   MVT VT = Op.getSimpleValueType();
8138   MVT EltVT = VT.getVectorElementType();
8139   unsigned NumElems = VT.getVectorNumElements();
8140
8141   // There is no blend with immediate in AVX-512.
8142   if (VT.is512BitVector())
8143     return SDValue();
8144
8145   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8146     return SDValue();
8147   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8148     return SDValue();
8149
8150   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8151     return SDValue();
8152
8153   // Check the mask for BLEND and build the value.
8154   unsigned MaskValue = 0;
8155   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8156     return SDValue();
8157
8158   // Convert i32 vectors to floating point if it is not AVX2.
8159   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8160   MVT BlendVT = VT;
8161   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8162     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8163                                NumElems);
8164     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8165     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8166   }
8167
8168   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8169                             DAG.getConstant(MaskValue, MVT::i32));
8170   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8171 }
8172
8173 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8174   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8175   if (BlendOp.getNode())
8176     return BlendOp;
8177
8178   // Some types for vselect were previously set to Expand, not Legal or
8179   // Custom. Return an empty SDValue so we fall-through to Expand, after
8180   // the Custom lowering phase.
8181   MVT VT = Op.getSimpleValueType();
8182   switch (VT.SimpleTy) {
8183   default:
8184     break;
8185   case MVT::v8i16:
8186   case MVT::v16i16:
8187     return SDValue();
8188   }
8189
8190   // We couldn't create a "Blend with immediate" node.
8191   // This node should still be legal, but we'll have to emit a blendv*
8192   // instruction.
8193   return Op;
8194 }
8195
8196 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8197   MVT VT = Op.getSimpleValueType();
8198   SDLoc dl(Op);
8199
8200   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8201     return SDValue();
8202
8203   if (VT.getSizeInBits() == 8) {
8204     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8205                                   Op.getOperand(0), Op.getOperand(1));
8206     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8207                                   DAG.getValueType(VT));
8208     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8209   }
8210
8211   if (VT.getSizeInBits() == 16) {
8212     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8213     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8214     if (Idx == 0)
8215       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8216                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8217                                      DAG.getNode(ISD::BITCAST, dl,
8218                                                  MVT::v4i32,
8219                                                  Op.getOperand(0)),
8220                                      Op.getOperand(1)));
8221     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8222                                   Op.getOperand(0), Op.getOperand(1));
8223     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8224                                   DAG.getValueType(VT));
8225     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8226   }
8227
8228   if (VT == MVT::f32) {
8229     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8230     // the result back to FR32 register. It's only worth matching if the
8231     // result has a single use which is a store or a bitcast to i32.  And in
8232     // the case of a store, it's not worth it if the index is a constant 0,
8233     // because a MOVSSmr can be used instead, which is smaller and faster.
8234     if (!Op.hasOneUse())
8235       return SDValue();
8236     SDNode *User = *Op.getNode()->use_begin();
8237     if ((User->getOpcode() != ISD::STORE ||
8238          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8239           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8240         (User->getOpcode() != ISD::BITCAST ||
8241          User->getValueType(0) != MVT::i32))
8242       return SDValue();
8243     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8244                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8245                                               Op.getOperand(0)),
8246                                               Op.getOperand(1));
8247     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8248   }
8249
8250   if (VT == MVT::i32 || VT == MVT::i64) {
8251     // ExtractPS/pextrq works with constant index.
8252     if (isa<ConstantSDNode>(Op.getOperand(1)))
8253       return Op;
8254   }
8255   return SDValue();
8256 }
8257
8258 /// Extract one bit from mask vector, like v16i1 or v8i1.
8259 /// AVX-512 feature.
8260 SDValue
8261 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8262   SDValue Vec = Op.getOperand(0);
8263   SDLoc dl(Vec);
8264   MVT VecVT = Vec.getSimpleValueType();
8265   SDValue Idx = Op.getOperand(1);
8266   MVT EltVT = Op.getSimpleValueType();
8267
8268   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8269
8270   // variable index can't be handled in mask registers,
8271   // extend vector to VR512
8272   if (!isa<ConstantSDNode>(Idx)) {
8273     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8274     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8275     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8276                               ExtVT.getVectorElementType(), Ext, Idx);
8277     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8278   }
8279
8280   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8281   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8282   unsigned MaxSift = rc->getSize()*8 - 1;
8283   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8284                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8285   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8286                     DAG.getConstant(MaxSift, MVT::i8));
8287   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8288                        DAG.getIntPtrConstant(0));
8289 }
8290
8291 SDValue
8292 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8293                                            SelectionDAG &DAG) const {
8294   SDLoc dl(Op);
8295   SDValue Vec = Op.getOperand(0);
8296   MVT VecVT = Vec.getSimpleValueType();
8297   SDValue Idx = Op.getOperand(1);
8298
8299   if (Op.getSimpleValueType() == MVT::i1)
8300     return ExtractBitFromMaskVector(Op, DAG);
8301
8302   if (!isa<ConstantSDNode>(Idx)) {
8303     if (VecVT.is512BitVector() ||
8304         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8305          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8306
8307       MVT MaskEltVT =
8308         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8309       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8310                                     MaskEltVT.getSizeInBits());
8311
8312       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8313       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8314                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8315                                 Idx, DAG.getConstant(0, getPointerTy()));
8316       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8317       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8318                         Perm, DAG.getConstant(0, getPointerTy()));
8319     }
8320     return SDValue();
8321   }
8322
8323   // If this is a 256-bit vector result, first extract the 128-bit vector and
8324   // then extract the element from the 128-bit vector.
8325   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8326
8327     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8328     // Get the 128-bit vector.
8329     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8330     MVT EltVT = VecVT.getVectorElementType();
8331
8332     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8333
8334     //if (IdxVal >= NumElems/2)
8335     //  IdxVal -= NumElems/2;
8336     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8337     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8338                        DAG.getConstant(IdxVal, MVT::i32));
8339   }
8340
8341   assert(VecVT.is128BitVector() && "Unexpected vector length");
8342
8343   if (Subtarget->hasSSE41()) {
8344     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8345     if (Res.getNode())
8346       return Res;
8347   }
8348
8349   MVT VT = Op.getSimpleValueType();
8350   // TODO: handle v16i8.
8351   if (VT.getSizeInBits() == 16) {
8352     SDValue Vec = Op.getOperand(0);
8353     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8354     if (Idx == 0)
8355       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8356                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8357                                      DAG.getNode(ISD::BITCAST, dl,
8358                                                  MVT::v4i32, Vec),
8359                                      Op.getOperand(1)));
8360     // Transform it so it match pextrw which produces a 32-bit result.
8361     MVT EltVT = MVT::i32;
8362     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8363                                   Op.getOperand(0), Op.getOperand(1));
8364     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8365                                   DAG.getValueType(VT));
8366     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8367   }
8368
8369   if (VT.getSizeInBits() == 32) {
8370     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8371     if (Idx == 0)
8372       return Op;
8373
8374     // SHUFPS the element to the lowest double word, then movss.
8375     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8376     MVT VVT = Op.getOperand(0).getSimpleValueType();
8377     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8378                                        DAG.getUNDEF(VVT), Mask);
8379     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8380                        DAG.getIntPtrConstant(0));
8381   }
8382
8383   if (VT.getSizeInBits() == 64) {
8384     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8385     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8386     //        to match extract_elt for f64.
8387     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8388     if (Idx == 0)
8389       return Op;
8390
8391     // UNPCKHPD the element to the lowest double word, then movsd.
8392     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8393     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8394     int Mask[2] = { 1, -1 };
8395     MVT VVT = Op.getOperand(0).getSimpleValueType();
8396     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8397                                        DAG.getUNDEF(VVT), Mask);
8398     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8399                        DAG.getIntPtrConstant(0));
8400   }
8401
8402   return SDValue();
8403 }
8404
8405 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8406   MVT VT = Op.getSimpleValueType();
8407   MVT EltVT = VT.getVectorElementType();
8408   SDLoc dl(Op);
8409
8410   SDValue N0 = Op.getOperand(0);
8411   SDValue N1 = Op.getOperand(1);
8412   SDValue N2 = Op.getOperand(2);
8413
8414   if (!VT.is128BitVector())
8415     return SDValue();
8416
8417   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8418       isa<ConstantSDNode>(N2)) {
8419     unsigned Opc;
8420     if (VT == MVT::v8i16)
8421       Opc = X86ISD::PINSRW;
8422     else if (VT == MVT::v16i8)
8423       Opc = X86ISD::PINSRB;
8424     else
8425       Opc = X86ISD::PINSRB;
8426
8427     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8428     // argument.
8429     if (N1.getValueType() != MVT::i32)
8430       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8431     if (N2.getValueType() != MVT::i32)
8432       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8433     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8434   }
8435
8436   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8437     // Bits [7:6] of the constant are the source select.  This will always be
8438     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8439     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8440     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8441     // Bits [5:4] of the constant are the destination select.  This is the
8442     //  value of the incoming immediate.
8443     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8444     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8445     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8446     // Create this as a scalar to vector..
8447     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8448     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8449   }
8450
8451   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8452     // PINSR* works with constant index.
8453     return Op;
8454   }
8455   return SDValue();
8456 }
8457
8458 /// Insert one bit to mask vector, like v16i1 or v8i1.
8459 /// AVX-512 feature.
8460 SDValue 
8461 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8462   SDLoc dl(Op);
8463   SDValue Vec = Op.getOperand(0);
8464   SDValue Elt = Op.getOperand(1);
8465   SDValue Idx = Op.getOperand(2);
8466   MVT VecVT = Vec.getSimpleValueType();
8467
8468   if (!isa<ConstantSDNode>(Idx)) {
8469     // Non constant index. Extend source and destination,
8470     // insert element and then truncate the result.
8471     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8472     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8473     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8474       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8475       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8476     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8477   }
8478
8479   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8480   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8481   if (Vec.getOpcode() == ISD::UNDEF)
8482     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8483                        DAG.getConstant(IdxVal, MVT::i8));
8484   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8485   unsigned MaxSift = rc->getSize()*8 - 1;
8486   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8487                     DAG.getConstant(MaxSift, MVT::i8));
8488   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8489                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8490   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8491 }
8492 SDValue
8493 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8494   MVT VT = Op.getSimpleValueType();
8495   MVT EltVT = VT.getVectorElementType();
8496   
8497   if (EltVT == MVT::i1)
8498     return InsertBitToMaskVector(Op, DAG);
8499
8500   SDLoc dl(Op);
8501   SDValue N0 = Op.getOperand(0);
8502   SDValue N1 = Op.getOperand(1);
8503   SDValue N2 = Op.getOperand(2);
8504
8505   // If this is a 256-bit vector result, first extract the 128-bit vector,
8506   // insert the element into the extracted half and then place it back.
8507   if (VT.is256BitVector() || VT.is512BitVector()) {
8508     if (!isa<ConstantSDNode>(N2))
8509       return SDValue();
8510
8511     // Get the desired 128-bit vector half.
8512     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8513     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8514
8515     // Insert the element into the desired half.
8516     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8517     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8518
8519     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8520                     DAG.getConstant(IdxIn128, MVT::i32));
8521
8522     // Insert the changed part back to the 256-bit vector
8523     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8524   }
8525
8526   if (Subtarget->hasSSE41())
8527     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8528
8529   if (EltVT == MVT::i8)
8530     return SDValue();
8531
8532   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8533     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8534     // as its second argument.
8535     if (N1.getValueType() != MVT::i32)
8536       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8537     if (N2.getValueType() != MVT::i32)
8538       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8539     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8540   }
8541   return SDValue();
8542 }
8543
8544 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8545   SDLoc dl(Op);
8546   MVT OpVT = Op.getSimpleValueType();
8547
8548   // If this is a 256-bit vector result, first insert into a 128-bit
8549   // vector and then insert into the 256-bit vector.
8550   if (!OpVT.is128BitVector()) {
8551     // Insert into a 128-bit vector.
8552     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8553     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8554                                  OpVT.getVectorNumElements() / SizeFactor);
8555
8556     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8557
8558     // Insert the 128-bit vector.
8559     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8560   }
8561
8562   if (OpVT == MVT::v1i64 &&
8563       Op.getOperand(0).getValueType() == MVT::i64)
8564     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8565
8566   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8567   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8568   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8569                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8570 }
8571
8572 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8573 // a simple subregister reference or explicit instructions to grab
8574 // upper bits of a vector.
8575 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8576                                       SelectionDAG &DAG) {
8577   SDLoc dl(Op);
8578   SDValue In =  Op.getOperand(0);
8579   SDValue Idx = Op.getOperand(1);
8580   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8581   MVT ResVT   = Op.getSimpleValueType();
8582   MVT InVT    = In.getSimpleValueType();
8583
8584   if (Subtarget->hasFp256()) {
8585     if (ResVT.is128BitVector() &&
8586         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8587         isa<ConstantSDNode>(Idx)) {
8588       return Extract128BitVector(In, IdxVal, DAG, dl);
8589     }
8590     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8591         isa<ConstantSDNode>(Idx)) {
8592       return Extract256BitVector(In, IdxVal, DAG, dl);
8593     }
8594   }
8595   return SDValue();
8596 }
8597
8598 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8599 // simple superregister reference or explicit instructions to insert
8600 // the upper bits of a vector.
8601 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8602                                      SelectionDAG &DAG) {
8603   if (Subtarget->hasFp256()) {
8604     SDLoc dl(Op.getNode());
8605     SDValue Vec = Op.getNode()->getOperand(0);
8606     SDValue SubVec = Op.getNode()->getOperand(1);
8607     SDValue Idx = Op.getNode()->getOperand(2);
8608
8609     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8610          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8611         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8612         isa<ConstantSDNode>(Idx)) {
8613       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8614       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8615     }
8616
8617     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8618         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8619         isa<ConstantSDNode>(Idx)) {
8620       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8621       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8622     }
8623   }
8624   return SDValue();
8625 }
8626
8627 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8628 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8629 // one of the above mentioned nodes. It has to be wrapped because otherwise
8630 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8631 // be used to form addressing mode. These wrapped nodes will be selected
8632 // into MOV32ri.
8633 SDValue
8634 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8635   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8636
8637   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8638   // global base reg.
8639   unsigned char OpFlag = 0;
8640   unsigned WrapperKind = X86ISD::Wrapper;
8641   CodeModel::Model M = getTargetMachine().getCodeModel();
8642
8643   if (Subtarget->isPICStyleRIPRel() &&
8644       (M == CodeModel::Small || M == CodeModel::Kernel))
8645     WrapperKind = X86ISD::WrapperRIP;
8646   else if (Subtarget->isPICStyleGOT())
8647     OpFlag = X86II::MO_GOTOFF;
8648   else if (Subtarget->isPICStyleStubPIC())
8649     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8650
8651   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8652                                              CP->getAlignment(),
8653                                              CP->getOffset(), OpFlag);
8654   SDLoc DL(CP);
8655   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8656   // With PIC, the address is actually $g + Offset.
8657   if (OpFlag) {
8658     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8659                          DAG.getNode(X86ISD::GlobalBaseReg,
8660                                      SDLoc(), getPointerTy()),
8661                          Result);
8662   }
8663
8664   return Result;
8665 }
8666
8667 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8668   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8669
8670   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8671   // global base reg.
8672   unsigned char OpFlag = 0;
8673   unsigned WrapperKind = X86ISD::Wrapper;
8674   CodeModel::Model M = getTargetMachine().getCodeModel();
8675
8676   if (Subtarget->isPICStyleRIPRel() &&
8677       (M == CodeModel::Small || M == CodeModel::Kernel))
8678     WrapperKind = X86ISD::WrapperRIP;
8679   else if (Subtarget->isPICStyleGOT())
8680     OpFlag = X86II::MO_GOTOFF;
8681   else if (Subtarget->isPICStyleStubPIC())
8682     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8683
8684   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8685                                           OpFlag);
8686   SDLoc DL(JT);
8687   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8688
8689   // With PIC, the address is actually $g + Offset.
8690   if (OpFlag)
8691     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8692                          DAG.getNode(X86ISD::GlobalBaseReg,
8693                                      SDLoc(), getPointerTy()),
8694                          Result);
8695
8696   return Result;
8697 }
8698
8699 SDValue
8700 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8701   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8702
8703   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8704   // global base reg.
8705   unsigned char OpFlag = 0;
8706   unsigned WrapperKind = X86ISD::Wrapper;
8707   CodeModel::Model M = getTargetMachine().getCodeModel();
8708
8709   if (Subtarget->isPICStyleRIPRel() &&
8710       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8711     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8712       OpFlag = X86II::MO_GOTPCREL;
8713     WrapperKind = X86ISD::WrapperRIP;
8714   } else if (Subtarget->isPICStyleGOT()) {
8715     OpFlag = X86II::MO_GOT;
8716   } else if (Subtarget->isPICStyleStubPIC()) {
8717     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8718   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8719     OpFlag = X86II::MO_DARWIN_NONLAZY;
8720   }
8721
8722   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8723
8724   SDLoc DL(Op);
8725   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8726
8727   // With PIC, the address is actually $g + Offset.
8728   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8729       !Subtarget->is64Bit()) {
8730     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8731                          DAG.getNode(X86ISD::GlobalBaseReg,
8732                                      SDLoc(), getPointerTy()),
8733                          Result);
8734   }
8735
8736   // For symbols that require a load from a stub to get the address, emit the
8737   // load.
8738   if (isGlobalStubReference(OpFlag))
8739     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8740                          MachinePointerInfo::getGOT(), false, false, false, 0);
8741
8742   return Result;
8743 }
8744
8745 SDValue
8746 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8747   // Create the TargetBlockAddressAddress node.
8748   unsigned char OpFlags =
8749     Subtarget->ClassifyBlockAddressReference();
8750   CodeModel::Model M = getTargetMachine().getCodeModel();
8751   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8752   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8753   SDLoc dl(Op);
8754   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8755                                              OpFlags);
8756
8757   if (Subtarget->isPICStyleRIPRel() &&
8758       (M == CodeModel::Small || M == CodeModel::Kernel))
8759     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8760   else
8761     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8762
8763   // With PIC, the address is actually $g + Offset.
8764   if (isGlobalRelativeToPICBase(OpFlags)) {
8765     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8766                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8767                          Result);
8768   }
8769
8770   return Result;
8771 }
8772
8773 SDValue
8774 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8775                                       int64_t Offset, SelectionDAG &DAG) const {
8776   // Create the TargetGlobalAddress node, folding in the constant
8777   // offset if it is legal.
8778   unsigned char OpFlags =
8779     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8780   CodeModel::Model M = getTargetMachine().getCodeModel();
8781   SDValue Result;
8782   if (OpFlags == X86II::MO_NO_FLAG &&
8783       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8784     // A direct static reference to a global.
8785     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8786     Offset = 0;
8787   } else {
8788     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8789   }
8790
8791   if (Subtarget->isPICStyleRIPRel() &&
8792       (M == CodeModel::Small || M == CodeModel::Kernel))
8793     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8794   else
8795     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8796
8797   // With PIC, the address is actually $g + Offset.
8798   if (isGlobalRelativeToPICBase(OpFlags)) {
8799     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8800                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8801                          Result);
8802   }
8803
8804   // For globals that require a load from a stub to get the address, emit the
8805   // load.
8806   if (isGlobalStubReference(OpFlags))
8807     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8808                          MachinePointerInfo::getGOT(), false, false, false, 0);
8809
8810   // If there was a non-zero offset that we didn't fold, create an explicit
8811   // addition for it.
8812   if (Offset != 0)
8813     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8814                          DAG.getConstant(Offset, getPointerTy()));
8815
8816   return Result;
8817 }
8818
8819 SDValue
8820 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8821   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8822   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8823   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8824 }
8825
8826 static SDValue
8827 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8828            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8829            unsigned char OperandFlags, bool LocalDynamic = false) {
8830   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8831   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8832   SDLoc dl(GA);
8833   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8834                                            GA->getValueType(0),
8835                                            GA->getOffset(),
8836                                            OperandFlags);
8837
8838   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8839                                            : X86ISD::TLSADDR;
8840
8841   if (InFlag) {
8842     SDValue Ops[] = { Chain,  TGA, *InFlag };
8843     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8844   } else {
8845     SDValue Ops[]  = { Chain, TGA };
8846     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8847   }
8848
8849   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8850   MFI->setAdjustsStack(true);
8851
8852   SDValue Flag = Chain.getValue(1);
8853   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8854 }
8855
8856 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8857 static SDValue
8858 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8859                                 const EVT PtrVT) {
8860   SDValue InFlag;
8861   SDLoc dl(GA);  // ? function entry point might be better
8862   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8863                                    DAG.getNode(X86ISD::GlobalBaseReg,
8864                                                SDLoc(), PtrVT), InFlag);
8865   InFlag = Chain.getValue(1);
8866
8867   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8868 }
8869
8870 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8871 static SDValue
8872 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8873                                 const EVT PtrVT) {
8874   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8875                     X86::RAX, X86II::MO_TLSGD);
8876 }
8877
8878 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8879                                            SelectionDAG &DAG,
8880                                            const EVT PtrVT,
8881                                            bool is64Bit) {
8882   SDLoc dl(GA);
8883
8884   // Get the start address of the TLS block for this module.
8885   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8886       .getInfo<X86MachineFunctionInfo>();
8887   MFI->incNumLocalDynamicTLSAccesses();
8888
8889   SDValue Base;
8890   if (is64Bit) {
8891     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8892                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8893   } else {
8894     SDValue InFlag;
8895     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8896         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8897     InFlag = Chain.getValue(1);
8898     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8899                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8900   }
8901
8902   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8903   // of Base.
8904
8905   // Build x@dtpoff.
8906   unsigned char OperandFlags = X86II::MO_DTPOFF;
8907   unsigned WrapperKind = X86ISD::Wrapper;
8908   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8909                                            GA->getValueType(0),
8910                                            GA->getOffset(), OperandFlags);
8911   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8912
8913   // Add x@dtpoff with the base.
8914   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8915 }
8916
8917 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8918 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8919                                    const EVT PtrVT, TLSModel::Model model,
8920                                    bool is64Bit, bool isPIC) {
8921   SDLoc dl(GA);
8922
8923   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8924   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8925                                                          is64Bit ? 257 : 256));
8926
8927   SDValue ThreadPointer =
8928       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8929                   MachinePointerInfo(Ptr), false, false, false, 0);
8930
8931   unsigned char OperandFlags = 0;
8932   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8933   // initialexec.
8934   unsigned WrapperKind = X86ISD::Wrapper;
8935   if (model == TLSModel::LocalExec) {
8936     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8937   } else if (model == TLSModel::InitialExec) {
8938     if (is64Bit) {
8939       OperandFlags = X86II::MO_GOTTPOFF;
8940       WrapperKind = X86ISD::WrapperRIP;
8941     } else {
8942       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8943     }
8944   } else {
8945     llvm_unreachable("Unexpected model");
8946   }
8947
8948   // emit "addl x@ntpoff,%eax" (local exec)
8949   // or "addl x@indntpoff,%eax" (initial exec)
8950   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8951   SDValue TGA =
8952       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8953                                  GA->getOffset(), OperandFlags);
8954   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8955
8956   if (model == TLSModel::InitialExec) {
8957     if (isPIC && !is64Bit) {
8958       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8959                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8960                            Offset);
8961     }
8962
8963     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8964                          MachinePointerInfo::getGOT(), false, false, false, 0);
8965   }
8966
8967   // The address of the thread local variable is the add of the thread
8968   // pointer with the offset of the variable.
8969   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8970 }
8971
8972 SDValue
8973 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8974
8975   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8976   const GlobalValue *GV = GA->getGlobal();
8977
8978   if (Subtarget->isTargetELF()) {
8979     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8980
8981     switch (model) {
8982       case TLSModel::GeneralDynamic:
8983         if (Subtarget->is64Bit())
8984           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8985         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8986       case TLSModel::LocalDynamic:
8987         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8988                                            Subtarget->is64Bit());
8989       case TLSModel::InitialExec:
8990       case TLSModel::LocalExec:
8991         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8992                                    Subtarget->is64Bit(),
8993                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8994     }
8995     llvm_unreachable("Unknown TLS model.");
8996   }
8997
8998   if (Subtarget->isTargetDarwin()) {
8999     // Darwin only has one model of TLS.  Lower to that.
9000     unsigned char OpFlag = 0;
9001     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9002                            X86ISD::WrapperRIP : X86ISD::Wrapper;
9003
9004     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9005     // global base reg.
9006     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
9007                   !Subtarget->is64Bit();
9008     if (PIC32)
9009       OpFlag = X86II::MO_TLVP_PIC_BASE;
9010     else
9011       OpFlag = X86II::MO_TLVP;
9012     SDLoc DL(Op);
9013     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9014                                                 GA->getValueType(0),
9015                                                 GA->getOffset(), OpFlag);
9016     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9017
9018     // With PIC32, the address is actually $g + Offset.
9019     if (PIC32)
9020       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9021                            DAG.getNode(X86ISD::GlobalBaseReg,
9022                                        SDLoc(), getPointerTy()),
9023                            Offset);
9024
9025     // Lowering the machine isd will make sure everything is in the right
9026     // location.
9027     SDValue Chain = DAG.getEntryNode();
9028     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9029     SDValue Args[] = { Chain, Offset };
9030     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9031
9032     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9033     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9034     MFI->setAdjustsStack(true);
9035
9036     // And our return value (tls address) is in the standard call return value
9037     // location.
9038     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9039     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9040                               Chain.getValue(1));
9041   }
9042
9043   if (Subtarget->isTargetKnownWindowsMSVC() ||
9044       Subtarget->isTargetWindowsGNU()) {
9045     // Just use the implicit TLS architecture
9046     // Need to generate someting similar to:
9047     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9048     //                                  ; from TEB
9049     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
9050     //   mov     rcx, qword [rdx+rcx*8]
9051     //   mov     eax, .tls$:tlsvar
9052     //   [rax+rcx] contains the address
9053     // Windows 64bit: gs:0x58
9054     // Windows 32bit: fs:__tls_array
9055
9056     SDLoc dl(GA);
9057     SDValue Chain = DAG.getEntryNode();
9058
9059     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9060     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9061     // use its literal value of 0x2C.
9062     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9063                                         ? Type::getInt8PtrTy(*DAG.getContext(),
9064                                                              256)
9065                                         : Type::getInt32PtrTy(*DAG.getContext(),
9066                                                               257));
9067
9068     SDValue TlsArray =
9069         Subtarget->is64Bit()
9070             ? DAG.getIntPtrConstant(0x58)
9071             : (Subtarget->isTargetWindowsGNU()
9072                    ? DAG.getIntPtrConstant(0x2C)
9073                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9074
9075     SDValue ThreadPointer =
9076         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9077                     MachinePointerInfo(Ptr), false, false, false, 0);
9078
9079     // Load the _tls_index variable
9080     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9081     if (Subtarget->is64Bit())
9082       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9083                            IDX, MachinePointerInfo(), MVT::i32,
9084                            false, false, 0);
9085     else
9086       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9087                         false, false, false, 0);
9088
9089     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9090                                     getPointerTy());
9091     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9092
9093     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9094     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9095                       false, false, false, 0);
9096
9097     // Get the offset of start of .tls section
9098     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9099                                              GA->getValueType(0),
9100                                              GA->getOffset(), X86II::MO_SECREL);
9101     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9102
9103     // The address of the thread local variable is the add of the thread
9104     // pointer with the offset of the variable.
9105     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9106   }
9107
9108   llvm_unreachable("TLS not implemented for this target.");
9109 }
9110
9111 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9112 /// and take a 2 x i32 value to shift plus a shift amount.
9113 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9114   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9115   MVT VT = Op.getSimpleValueType();
9116   unsigned VTBits = VT.getSizeInBits();
9117   SDLoc dl(Op);
9118   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9119   SDValue ShOpLo = Op.getOperand(0);
9120   SDValue ShOpHi = Op.getOperand(1);
9121   SDValue ShAmt  = Op.getOperand(2);
9122   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9123   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9124   // during isel.
9125   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9126                                   DAG.getConstant(VTBits - 1, MVT::i8));
9127   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9128                                      DAG.getConstant(VTBits - 1, MVT::i8))
9129                        : DAG.getConstant(0, VT);
9130
9131   SDValue Tmp2, Tmp3;
9132   if (Op.getOpcode() == ISD::SHL_PARTS) {
9133     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9134     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9135   } else {
9136     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9137     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9138   }
9139
9140   // If the shift amount is larger or equal than the width of a part we can't
9141   // rely on the results of shld/shrd. Insert a test and select the appropriate
9142   // values for large shift amounts.
9143   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9144                                 DAG.getConstant(VTBits, MVT::i8));
9145   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9146                              AndNode, DAG.getConstant(0, MVT::i8));
9147
9148   SDValue Hi, Lo;
9149   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9150   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9151   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9152
9153   if (Op.getOpcode() == ISD::SHL_PARTS) {
9154     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9155     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9156   } else {
9157     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9158     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9159   }
9160
9161   SDValue Ops[2] = { Lo, Hi };
9162   return DAG.getMergeValues(Ops, dl);
9163 }
9164
9165 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9166                                            SelectionDAG &DAG) const {
9167   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9168
9169   if (SrcVT.isVector())
9170     return SDValue();
9171
9172   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9173          "Unknown SINT_TO_FP to lower!");
9174
9175   // These are really Legal; return the operand so the caller accepts it as
9176   // Legal.
9177   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9178     return Op;
9179   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9180       Subtarget->is64Bit()) {
9181     return Op;
9182   }
9183
9184   SDLoc dl(Op);
9185   unsigned Size = SrcVT.getSizeInBits()/8;
9186   MachineFunction &MF = DAG.getMachineFunction();
9187   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9188   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9189   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9190                                StackSlot,
9191                                MachinePointerInfo::getFixedStack(SSFI),
9192                                false, false, 0);
9193   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9194 }
9195
9196 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9197                                      SDValue StackSlot,
9198                                      SelectionDAG &DAG) const {
9199   // Build the FILD
9200   SDLoc DL(Op);
9201   SDVTList Tys;
9202   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9203   if (useSSE)
9204     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9205   else
9206     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9207
9208   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9209
9210   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9211   MachineMemOperand *MMO;
9212   if (FI) {
9213     int SSFI = FI->getIndex();
9214     MMO =
9215       DAG.getMachineFunction()
9216       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9217                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9218   } else {
9219     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9220     StackSlot = StackSlot.getOperand(1);
9221   }
9222   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9223   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9224                                            X86ISD::FILD, DL,
9225                                            Tys, Ops, SrcVT, MMO);
9226
9227   if (useSSE) {
9228     Chain = Result.getValue(1);
9229     SDValue InFlag = Result.getValue(2);
9230
9231     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9232     // shouldn't be necessary except that RFP cannot be live across
9233     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9234     MachineFunction &MF = DAG.getMachineFunction();
9235     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9236     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9237     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9238     Tys = DAG.getVTList(MVT::Other);
9239     SDValue Ops[] = {
9240       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9241     };
9242     MachineMemOperand *MMO =
9243       DAG.getMachineFunction()
9244       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9245                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9246
9247     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9248                                     Ops, Op.getValueType(), MMO);
9249     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9250                          MachinePointerInfo::getFixedStack(SSFI),
9251                          false, false, false, 0);
9252   }
9253
9254   return Result;
9255 }
9256
9257 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9258 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9259                                                SelectionDAG &DAG) const {
9260   // This algorithm is not obvious. Here it is what we're trying to output:
9261   /*
9262      movq       %rax,  %xmm0
9263      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9264      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9265      #ifdef __SSE3__
9266        haddpd   %xmm0, %xmm0
9267      #else
9268        pshufd   $0x4e, %xmm0, %xmm1
9269        addpd    %xmm1, %xmm0
9270      #endif
9271   */
9272
9273   SDLoc dl(Op);
9274   LLVMContext *Context = DAG.getContext();
9275
9276   // Build some magic constants.
9277   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9278   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9279   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9280
9281   SmallVector<Constant*,2> CV1;
9282   CV1.push_back(
9283     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9284                                       APInt(64, 0x4330000000000000ULL))));
9285   CV1.push_back(
9286     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9287                                       APInt(64, 0x4530000000000000ULL))));
9288   Constant *C1 = ConstantVector::get(CV1);
9289   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9290
9291   // Load the 64-bit value into an XMM register.
9292   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9293                             Op.getOperand(0));
9294   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9295                               MachinePointerInfo::getConstantPool(),
9296                               false, false, false, 16);
9297   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9298                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9299                               CLod0);
9300
9301   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9302                               MachinePointerInfo::getConstantPool(),
9303                               false, false, false, 16);
9304   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9305   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9306   SDValue Result;
9307
9308   if (Subtarget->hasSSE3()) {
9309     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9310     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9311   } else {
9312     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9313     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9314                                            S2F, 0x4E, DAG);
9315     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9316                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9317                          Sub);
9318   }
9319
9320   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9321                      DAG.getIntPtrConstant(0));
9322 }
9323
9324 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9325 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9326                                                SelectionDAG &DAG) const {
9327   SDLoc dl(Op);
9328   // FP constant to bias correct the final result.
9329   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9330                                    MVT::f64);
9331
9332   // Load the 32-bit value into an XMM register.
9333   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9334                              Op.getOperand(0));
9335
9336   // Zero out the upper parts of the register.
9337   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9338
9339   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9340                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9341                      DAG.getIntPtrConstant(0));
9342
9343   // Or the load with the bias.
9344   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9345                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9346                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9347                                                    MVT::v2f64, Load)),
9348                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9349                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9350                                                    MVT::v2f64, Bias)));
9351   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9352                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9353                    DAG.getIntPtrConstant(0));
9354
9355   // Subtract the bias.
9356   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9357
9358   // Handle final rounding.
9359   EVT DestVT = Op.getValueType();
9360
9361   if (DestVT.bitsLT(MVT::f64))
9362     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9363                        DAG.getIntPtrConstant(0));
9364   if (DestVT.bitsGT(MVT::f64))
9365     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9366
9367   // Handle final rounding.
9368   return Sub;
9369 }
9370
9371 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9372                                                SelectionDAG &DAG) const {
9373   SDValue N0 = Op.getOperand(0);
9374   MVT SVT = N0.getSimpleValueType();
9375   SDLoc dl(Op);
9376
9377   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9378           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9379          "Custom UINT_TO_FP is not supported!");
9380
9381   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9382   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9383                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9384 }
9385
9386 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9387                                            SelectionDAG &DAG) const {
9388   SDValue N0 = Op.getOperand(0);
9389   SDLoc dl(Op);
9390
9391   if (Op.getValueType().isVector())
9392     return lowerUINT_TO_FP_vec(Op, DAG);
9393
9394   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9395   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9396   // the optimization here.
9397   if (DAG.SignBitIsZero(N0))
9398     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9399
9400   MVT SrcVT = N0.getSimpleValueType();
9401   MVT DstVT = Op.getSimpleValueType();
9402   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9403     return LowerUINT_TO_FP_i64(Op, DAG);
9404   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9405     return LowerUINT_TO_FP_i32(Op, DAG);
9406   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9407     return SDValue();
9408
9409   // Make a 64-bit buffer, and use it to build an FILD.
9410   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9411   if (SrcVT == MVT::i32) {
9412     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9413     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9414                                      getPointerTy(), StackSlot, WordOff);
9415     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9416                                   StackSlot, MachinePointerInfo(),
9417                                   false, false, 0);
9418     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9419                                   OffsetSlot, MachinePointerInfo(),
9420                                   false, false, 0);
9421     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9422     return Fild;
9423   }
9424
9425   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9426   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9427                                StackSlot, MachinePointerInfo(),
9428                                false, false, 0);
9429   // For i64 source, we need to add the appropriate power of 2 if the input
9430   // was negative.  This is the same as the optimization in
9431   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9432   // we must be careful to do the computation in x87 extended precision, not
9433   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9434   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9435   MachineMemOperand *MMO =
9436     DAG.getMachineFunction()
9437     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9438                           MachineMemOperand::MOLoad, 8, 8);
9439
9440   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9441   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9442   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9443                                          MVT::i64, MMO);
9444
9445   APInt FF(32, 0x5F800000ULL);
9446
9447   // Check whether the sign bit is set.
9448   SDValue SignSet = DAG.getSetCC(dl,
9449                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9450                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9451                                  ISD::SETLT);
9452
9453   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9454   SDValue FudgePtr = DAG.getConstantPool(
9455                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9456                                          getPointerTy());
9457
9458   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9459   SDValue Zero = DAG.getIntPtrConstant(0);
9460   SDValue Four = DAG.getIntPtrConstant(4);
9461   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9462                                Zero, Four);
9463   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9464
9465   // Load the value out, extending it from f32 to f80.
9466   // FIXME: Avoid the extend by constructing the right constant pool?
9467   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9468                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9469                                  MVT::f32, false, false, 4);
9470   // Extend everything to 80 bits to force it to be done on x87.
9471   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9472   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9473 }
9474
9475 std::pair<SDValue,SDValue>
9476 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9477                                     bool IsSigned, bool IsReplace) const {
9478   SDLoc DL(Op);
9479
9480   EVT DstTy = Op.getValueType();
9481
9482   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9483     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9484     DstTy = MVT::i64;
9485   }
9486
9487   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9488          DstTy.getSimpleVT() >= MVT::i16 &&
9489          "Unknown FP_TO_INT to lower!");
9490
9491   // These are really Legal.
9492   if (DstTy == MVT::i32 &&
9493       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9494     return std::make_pair(SDValue(), SDValue());
9495   if (Subtarget->is64Bit() &&
9496       DstTy == MVT::i64 &&
9497       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9498     return std::make_pair(SDValue(), SDValue());
9499
9500   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9501   // stack slot, or into the FTOL runtime function.
9502   MachineFunction &MF = DAG.getMachineFunction();
9503   unsigned MemSize = DstTy.getSizeInBits()/8;
9504   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9505   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9506
9507   unsigned Opc;
9508   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9509     Opc = X86ISD::WIN_FTOL;
9510   else
9511     switch (DstTy.getSimpleVT().SimpleTy) {
9512     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9513     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9514     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9515     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9516     }
9517
9518   SDValue Chain = DAG.getEntryNode();
9519   SDValue Value = Op.getOperand(0);
9520   EVT TheVT = Op.getOperand(0).getValueType();
9521   // FIXME This causes a redundant load/store if the SSE-class value is already
9522   // in memory, such as if it is on the callstack.
9523   if (isScalarFPTypeInSSEReg(TheVT)) {
9524     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9525     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9526                          MachinePointerInfo::getFixedStack(SSFI),
9527                          false, false, 0);
9528     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9529     SDValue Ops[] = {
9530       Chain, StackSlot, DAG.getValueType(TheVT)
9531     };
9532
9533     MachineMemOperand *MMO =
9534       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9535                               MachineMemOperand::MOLoad, MemSize, MemSize);
9536     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9537     Chain = Value.getValue(1);
9538     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9539     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9540   }
9541
9542   MachineMemOperand *MMO =
9543     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9544                             MachineMemOperand::MOStore, MemSize, MemSize);
9545
9546   if (Opc != X86ISD::WIN_FTOL) {
9547     // Build the FP_TO_INT*_IN_MEM
9548     SDValue Ops[] = { Chain, Value, StackSlot };
9549     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9550                                            Ops, DstTy, MMO);
9551     return std::make_pair(FIST, StackSlot);
9552   } else {
9553     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9554       DAG.getVTList(MVT::Other, MVT::Glue),
9555       Chain, Value);
9556     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9557       MVT::i32, ftol.getValue(1));
9558     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9559       MVT::i32, eax.getValue(2));
9560     SDValue Ops[] = { eax, edx };
9561     SDValue pair = IsReplace
9562       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9563       : DAG.getMergeValues(Ops, DL);
9564     return std::make_pair(pair, SDValue());
9565   }
9566 }
9567
9568 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9569                               const X86Subtarget *Subtarget) {
9570   MVT VT = Op->getSimpleValueType(0);
9571   SDValue In = Op->getOperand(0);
9572   MVT InVT = In.getSimpleValueType();
9573   SDLoc dl(Op);
9574
9575   // Optimize vectors in AVX mode:
9576   //
9577   //   v8i16 -> v8i32
9578   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9579   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9580   //   Concat upper and lower parts.
9581   //
9582   //   v4i32 -> v4i64
9583   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9584   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9585   //   Concat upper and lower parts.
9586   //
9587
9588   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9589       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9590       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9591     return SDValue();
9592
9593   if (Subtarget->hasInt256())
9594     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9595
9596   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9597   SDValue Undef = DAG.getUNDEF(InVT);
9598   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9599   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9600   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9601
9602   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9603                              VT.getVectorNumElements()/2);
9604
9605   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9606   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9607
9608   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9609 }
9610
9611 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9612                                         SelectionDAG &DAG) {
9613   MVT VT = Op->getSimpleValueType(0);
9614   SDValue In = Op->getOperand(0);
9615   MVT InVT = In.getSimpleValueType();
9616   SDLoc DL(Op);
9617   unsigned int NumElts = VT.getVectorNumElements();
9618   if (NumElts != 8 && NumElts != 16)
9619     return SDValue();
9620
9621   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9622     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9623
9624   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9626   // Now we have only mask extension
9627   assert(InVT.getVectorElementType() == MVT::i1);
9628   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9629   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9630   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9631   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9632   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9633                            MachinePointerInfo::getConstantPool(),
9634                            false, false, false, Alignment);
9635
9636   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9637   if (VT.is512BitVector())
9638     return Brcst;
9639   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9640 }
9641
9642 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9643                                SelectionDAG &DAG) {
9644   if (Subtarget->hasFp256()) {
9645     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9646     if (Res.getNode())
9647       return Res;
9648   }
9649
9650   return SDValue();
9651 }
9652
9653 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9654                                 SelectionDAG &DAG) {
9655   SDLoc DL(Op);
9656   MVT VT = Op.getSimpleValueType();
9657   SDValue In = Op.getOperand(0);
9658   MVT SVT = In.getSimpleValueType();
9659
9660   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9661     return LowerZERO_EXTEND_AVX512(Op, DAG);
9662
9663   if (Subtarget->hasFp256()) {
9664     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9665     if (Res.getNode())
9666       return Res;
9667   }
9668
9669   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9670          VT.getVectorNumElements() != SVT.getVectorNumElements());
9671   return SDValue();
9672 }
9673
9674 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9675   SDLoc DL(Op);
9676   MVT VT = Op.getSimpleValueType();
9677   SDValue In = Op.getOperand(0);
9678   MVT InVT = In.getSimpleValueType();
9679
9680   if (VT == MVT::i1) {
9681     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9682            "Invalid scalar TRUNCATE operation");
9683     if (InVT == MVT::i32)
9684       return SDValue();
9685     if (InVT.getSizeInBits() == 64)
9686       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9687     else if (InVT.getSizeInBits() < 32)
9688       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9689     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9690   }
9691   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9692          "Invalid TRUNCATE operation");
9693
9694   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9695     if (VT.getVectorElementType().getSizeInBits() >=8)
9696       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9697
9698     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9699     unsigned NumElts = InVT.getVectorNumElements();
9700     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9701     if (InVT.getSizeInBits() < 512) {
9702       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9703       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9704       InVT = ExtVT;
9705     }
9706     
9707     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9708     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9709     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9710     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9711     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9712                            MachinePointerInfo::getConstantPool(),
9713                            false, false, false, Alignment);
9714     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9715     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9716     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9717   }
9718
9719   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9720     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9721     if (Subtarget->hasInt256()) {
9722       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9723       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9724       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9725                                 ShufMask);
9726       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9727                          DAG.getIntPtrConstant(0));
9728     }
9729
9730     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9731                                DAG.getIntPtrConstant(0));
9732     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9733                                DAG.getIntPtrConstant(2));
9734     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9735     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9736     static const int ShufMask[] = {0, 2, 4, 6};
9737     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9738   }
9739
9740   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9741     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9742     if (Subtarget->hasInt256()) {
9743       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9744
9745       SmallVector<SDValue,32> pshufbMask;
9746       for (unsigned i = 0; i < 2; ++i) {
9747         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9748         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9749         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9750         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9751         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9752         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9753         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9754         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9755         for (unsigned j = 0; j < 8; ++j)
9756           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9757       }
9758       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9759       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9760       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9761
9762       static const int ShufMask[] = {0,  2,  -1,  -1};
9763       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9764                                 &ShufMask[0]);
9765       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9766                        DAG.getIntPtrConstant(0));
9767       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9768     }
9769
9770     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9771                                DAG.getIntPtrConstant(0));
9772
9773     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9774                                DAG.getIntPtrConstant(4));
9775
9776     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9777     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9778
9779     // The PSHUFB mask:
9780     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9781                                    -1, -1, -1, -1, -1, -1, -1, -1};
9782
9783     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9784     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9785     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9786
9787     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9788     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9789
9790     // The MOVLHPS Mask:
9791     static const int ShufMask2[] = {0, 1, 4, 5};
9792     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9793     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9794   }
9795
9796   // Handle truncation of V256 to V128 using shuffles.
9797   if (!VT.is128BitVector() || !InVT.is256BitVector())
9798     return SDValue();
9799
9800   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9801
9802   unsigned NumElems = VT.getVectorNumElements();
9803   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9804
9805   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9806   // Prepare truncation shuffle mask
9807   for (unsigned i = 0; i != NumElems; ++i)
9808     MaskVec[i] = i * 2;
9809   SDValue V = DAG.getVectorShuffle(NVT, DL,
9810                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9811                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9812   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9813                      DAG.getIntPtrConstant(0));
9814 }
9815
9816 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9817                                            SelectionDAG &DAG) const {
9818   assert(!Op.getSimpleValueType().isVector());
9819
9820   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9821     /*IsSigned=*/ true, /*IsReplace=*/ false);
9822   SDValue FIST = Vals.first, StackSlot = Vals.second;
9823   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9824   if (!FIST.getNode()) return Op;
9825
9826   if (StackSlot.getNode())
9827     // Load the result.
9828     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9829                        FIST, StackSlot, MachinePointerInfo(),
9830                        false, false, false, 0);
9831
9832   // The node is the result.
9833   return FIST;
9834 }
9835
9836 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9837                                            SelectionDAG &DAG) const {
9838   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9839     /*IsSigned=*/ false, /*IsReplace=*/ false);
9840   SDValue FIST = Vals.first, StackSlot = Vals.second;
9841   assert(FIST.getNode() && "Unexpected failure");
9842
9843   if (StackSlot.getNode())
9844     // Load the result.
9845     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9846                        FIST, StackSlot, MachinePointerInfo(),
9847                        false, false, false, 0);
9848
9849   // The node is the result.
9850   return FIST;
9851 }
9852
9853 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9854   SDLoc DL(Op);
9855   MVT VT = Op.getSimpleValueType();
9856   SDValue In = Op.getOperand(0);
9857   MVT SVT = In.getSimpleValueType();
9858
9859   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9860
9861   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9862                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9863                                  In, DAG.getUNDEF(SVT)));
9864 }
9865
9866 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9867   LLVMContext *Context = DAG.getContext();
9868   SDLoc dl(Op);
9869   MVT VT = Op.getSimpleValueType();
9870   MVT EltVT = VT;
9871   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9872   if (VT.isVector()) {
9873     EltVT = VT.getVectorElementType();
9874     NumElts = VT.getVectorNumElements();
9875   }
9876   Constant *C;
9877   if (EltVT == MVT::f64)
9878     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9879                                           APInt(64, ~(1ULL << 63))));
9880   else
9881     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9882                                           APInt(32, ~(1U << 31))));
9883   C = ConstantVector::getSplat(NumElts, C);
9884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9885   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9886   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9887   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9888                              MachinePointerInfo::getConstantPool(),
9889                              false, false, false, Alignment);
9890   if (VT.isVector()) {
9891     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9892     return DAG.getNode(ISD::BITCAST, dl, VT,
9893                        DAG.getNode(ISD::AND, dl, ANDVT,
9894                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9895                                                Op.getOperand(0)),
9896                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9897   }
9898   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9899 }
9900
9901 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9902   LLVMContext *Context = DAG.getContext();
9903   SDLoc dl(Op);
9904   MVT VT = Op.getSimpleValueType();
9905   MVT EltVT = VT;
9906   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9907   if (VT.isVector()) {
9908     EltVT = VT.getVectorElementType();
9909     NumElts = VT.getVectorNumElements();
9910   }
9911   Constant *C;
9912   if (EltVT == MVT::f64)
9913     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9914                                           APInt(64, 1ULL << 63)));
9915   else
9916     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9917                                           APInt(32, 1U << 31)));
9918   C = ConstantVector::getSplat(NumElts, C);
9919   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9920   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9921   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9922   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9923                              MachinePointerInfo::getConstantPool(),
9924                              false, false, false, Alignment);
9925   if (VT.isVector()) {
9926     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9927     return DAG.getNode(ISD::BITCAST, dl, VT,
9928                        DAG.getNode(ISD::XOR, dl, XORVT,
9929                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9930                                                Op.getOperand(0)),
9931                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9932   }
9933
9934   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9935 }
9936
9937 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9938   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9939   LLVMContext *Context = DAG.getContext();
9940   SDValue Op0 = Op.getOperand(0);
9941   SDValue Op1 = Op.getOperand(1);
9942   SDLoc dl(Op);
9943   MVT VT = Op.getSimpleValueType();
9944   MVT SrcVT = Op1.getSimpleValueType();
9945
9946   // If second operand is smaller, extend it first.
9947   if (SrcVT.bitsLT(VT)) {
9948     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9949     SrcVT = VT;
9950   }
9951   // And if it is bigger, shrink it first.
9952   if (SrcVT.bitsGT(VT)) {
9953     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9954     SrcVT = VT;
9955   }
9956
9957   // At this point the operands and the result should have the same
9958   // type, and that won't be f80 since that is not custom lowered.
9959
9960   // First get the sign bit of second operand.
9961   SmallVector<Constant*,4> CV;
9962   if (SrcVT == MVT::f64) {
9963     const fltSemantics &Sem = APFloat::IEEEdouble;
9964     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9965     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9966   } else {
9967     const fltSemantics &Sem = APFloat::IEEEsingle;
9968     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9969     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9970     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9971     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9972   }
9973   Constant *C = ConstantVector::get(CV);
9974   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9975   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9976                               MachinePointerInfo::getConstantPool(),
9977                               false, false, false, 16);
9978   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9979
9980   // Shift sign bit right or left if the two operands have different types.
9981   if (SrcVT.bitsGT(VT)) {
9982     // Op0 is MVT::f32, Op1 is MVT::f64.
9983     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9984     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9985                           DAG.getConstant(32, MVT::i32));
9986     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9987     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9988                           DAG.getIntPtrConstant(0));
9989   }
9990
9991   // Clear first operand sign bit.
9992   CV.clear();
9993   if (VT == MVT::f64) {
9994     const fltSemantics &Sem = APFloat::IEEEdouble;
9995     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9996                                                    APInt(64, ~(1ULL << 63)))));
9997     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9998   } else {
9999     const fltSemantics &Sem = APFloat::IEEEsingle;
10000     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10001                                                    APInt(32, ~(1U << 31)))));
10002     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10003     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10004     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10005   }
10006   C = ConstantVector::get(CV);
10007   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10008   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10009                               MachinePointerInfo::getConstantPool(),
10010                               false, false, false, 16);
10011   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10012
10013   // Or the value with the sign bit.
10014   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10015 }
10016
10017 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10018   SDValue N0 = Op.getOperand(0);
10019   SDLoc dl(Op);
10020   MVT VT = Op.getSimpleValueType();
10021
10022   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10023   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10024                                   DAG.getConstant(1, VT));
10025   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10026 }
10027
10028 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10029 //
10030 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10031                                       SelectionDAG &DAG) {
10032   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10033
10034   if (!Subtarget->hasSSE41())
10035     return SDValue();
10036
10037   if (!Op->hasOneUse())
10038     return SDValue();
10039
10040   SDNode *N = Op.getNode();
10041   SDLoc DL(N);
10042
10043   SmallVector<SDValue, 8> Opnds;
10044   DenseMap<SDValue, unsigned> VecInMap;
10045   SmallVector<SDValue, 8> VecIns;
10046   EVT VT = MVT::Other;
10047
10048   // Recognize a special case where a vector is casted into wide integer to
10049   // test all 0s.
10050   Opnds.push_back(N->getOperand(0));
10051   Opnds.push_back(N->getOperand(1));
10052
10053   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10054     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10055     // BFS traverse all OR'd operands.
10056     if (I->getOpcode() == ISD::OR) {
10057       Opnds.push_back(I->getOperand(0));
10058       Opnds.push_back(I->getOperand(1));
10059       // Re-evaluate the number of nodes to be traversed.
10060       e += 2; // 2 more nodes (LHS and RHS) are pushed.
10061       continue;
10062     }
10063
10064     // Quit if a non-EXTRACT_VECTOR_ELT
10065     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10066       return SDValue();
10067
10068     // Quit if without a constant index.
10069     SDValue Idx = I->getOperand(1);
10070     if (!isa<ConstantSDNode>(Idx))
10071       return SDValue();
10072
10073     SDValue ExtractedFromVec = I->getOperand(0);
10074     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10075     if (M == VecInMap.end()) {
10076       VT = ExtractedFromVec.getValueType();
10077       // Quit if not 128/256-bit vector.
10078       if (!VT.is128BitVector() && !VT.is256BitVector())
10079         return SDValue();
10080       // Quit if not the same type.
10081       if (VecInMap.begin() != VecInMap.end() &&
10082           VT != VecInMap.begin()->first.getValueType())
10083         return SDValue();
10084       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10085       VecIns.push_back(ExtractedFromVec);
10086     }
10087     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10088   }
10089
10090   assert((VT.is128BitVector() || VT.is256BitVector()) &&
10091          "Not extracted from 128-/256-bit vector.");
10092
10093   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10094
10095   for (DenseMap<SDValue, unsigned>::const_iterator
10096         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10097     // Quit if not all elements are used.
10098     if (I->second != FullMask)
10099       return SDValue();
10100   }
10101
10102   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10103
10104   // Cast all vectors into TestVT for PTEST.
10105   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10106     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10107
10108   // If more than one full vectors are evaluated, OR them first before PTEST.
10109   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10110     // Each iteration will OR 2 nodes and append the result until there is only
10111     // 1 node left, i.e. the final OR'd value of all vectors.
10112     SDValue LHS = VecIns[Slot];
10113     SDValue RHS = VecIns[Slot + 1];
10114     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10115   }
10116
10117   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10118                      VecIns.back(), VecIns.back());
10119 }
10120
10121 /// \brief return true if \c Op has a use that doesn't just read flags.
10122 static bool hasNonFlagsUse(SDValue Op) {
10123   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10124        ++UI) {
10125     SDNode *User = *UI;
10126     unsigned UOpNo = UI.getOperandNo();
10127     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10128       // Look pass truncate.
10129       UOpNo = User->use_begin().getOperandNo();
10130       User = *User->use_begin();
10131     }
10132
10133     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10134         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10135       return true;
10136   }
10137   return false;
10138 }
10139
10140 /// Emit nodes that will be selected as "test Op0,Op0", or something
10141 /// equivalent.
10142 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10143                                     SelectionDAG &DAG) const {
10144   if (Op.getValueType() == MVT::i1)
10145     // KORTEST instruction should be selected
10146     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10147                        DAG.getConstant(0, Op.getValueType()));
10148
10149   // CF and OF aren't always set the way we want. Determine which
10150   // of these we need.
10151   bool NeedCF = false;
10152   bool NeedOF = false;
10153   switch (X86CC) {
10154   default: break;
10155   case X86::COND_A: case X86::COND_AE:
10156   case X86::COND_B: case X86::COND_BE:
10157     NeedCF = true;
10158     break;
10159   case X86::COND_G: case X86::COND_GE:
10160   case X86::COND_L: case X86::COND_LE:
10161   case X86::COND_O: case X86::COND_NO: {
10162     // Check if we really need to set the
10163     // Overflow flag. If NoSignedWrap is present
10164     // that is not actually needed.
10165     switch (Op->getOpcode()) {
10166     case ISD::ADD:
10167     case ISD::SUB:
10168     case ISD::MUL:
10169     case ISD::SHL: {
10170       const BinaryWithFlagsSDNode *BinNode =
10171           cast<BinaryWithFlagsSDNode>(Op.getNode());
10172       if (BinNode->hasNoSignedWrap())
10173         break;
10174     }
10175     default:
10176       NeedOF = true;
10177       break;
10178     }
10179     break;
10180   }
10181   }
10182   // See if we can use the EFLAGS value from the operand instead of
10183   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10184   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10185   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10186     // Emit a CMP with 0, which is the TEST pattern.
10187     //if (Op.getValueType() == MVT::i1)
10188     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10189     //                     DAG.getConstant(0, MVT::i1));
10190     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10191                        DAG.getConstant(0, Op.getValueType()));
10192   }
10193   unsigned Opcode = 0;
10194   unsigned NumOperands = 0;
10195
10196   // Truncate operations may prevent the merge of the SETCC instruction
10197   // and the arithmetic instruction before it. Attempt to truncate the operands
10198   // of the arithmetic instruction and use a reduced bit-width instruction.
10199   bool NeedTruncation = false;
10200   SDValue ArithOp = Op;
10201   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10202     SDValue Arith = Op->getOperand(0);
10203     // Both the trunc and the arithmetic op need to have one user each.
10204     if (Arith->hasOneUse())
10205       switch (Arith.getOpcode()) {
10206         default: break;
10207         case ISD::ADD:
10208         case ISD::SUB:
10209         case ISD::AND:
10210         case ISD::OR:
10211         case ISD::XOR: {
10212           NeedTruncation = true;
10213           ArithOp = Arith;
10214         }
10215       }
10216   }
10217
10218   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10219   // which may be the result of a CAST.  We use the variable 'Op', which is the
10220   // non-casted variable when we check for possible users.
10221   switch (ArithOp.getOpcode()) {
10222   case ISD::ADD:
10223     // Due to an isel shortcoming, be conservative if this add is likely to be
10224     // selected as part of a load-modify-store instruction. When the root node
10225     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10226     // uses of other nodes in the match, such as the ADD in this case. This
10227     // leads to the ADD being left around and reselected, with the result being
10228     // two adds in the output.  Alas, even if none our users are stores, that
10229     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10230     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10231     // climbing the DAG back to the root, and it doesn't seem to be worth the
10232     // effort.
10233     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10234          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10235       if (UI->getOpcode() != ISD::CopyToReg &&
10236           UI->getOpcode() != ISD::SETCC &&
10237           UI->getOpcode() != ISD::STORE)
10238         goto default_case;
10239
10240     if (ConstantSDNode *C =
10241         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10242       // An add of one will be selected as an INC.
10243       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10244         Opcode = X86ISD::INC;
10245         NumOperands = 1;
10246         break;
10247       }
10248
10249       // An add of negative one (subtract of one) will be selected as a DEC.
10250       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10251         Opcode = X86ISD::DEC;
10252         NumOperands = 1;
10253         break;
10254       }
10255     }
10256
10257     // Otherwise use a regular EFLAGS-setting add.
10258     Opcode = X86ISD::ADD;
10259     NumOperands = 2;
10260     break;
10261   case ISD::SHL:
10262   case ISD::SRL:
10263     // If we have a constant logical shift that's only used in a comparison
10264     // against zero turn it into an equivalent AND. This allows turning it into
10265     // a TEST instruction later.
10266     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10267         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10268       EVT VT = Op.getValueType();
10269       unsigned BitWidth = VT.getSizeInBits();
10270       unsigned ShAmt = Op->getConstantOperandVal(1);
10271       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10272         break;
10273       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10274                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10275                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10276       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10277         break;
10278       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10279                                 DAG.getConstant(Mask, VT));
10280       DAG.ReplaceAllUsesWith(Op, New);
10281       Op = New;
10282     }
10283     break;
10284
10285   case ISD::AND:
10286     // If the primary and result isn't used, don't bother using X86ISD::AND,
10287     // because a TEST instruction will be better.
10288     if (!hasNonFlagsUse(Op))
10289       break;
10290     // FALL THROUGH
10291   case ISD::SUB:
10292   case ISD::OR:
10293   case ISD::XOR:
10294     // Due to the ISEL shortcoming noted above, be conservative if this op is
10295     // likely to be selected as part of a load-modify-store instruction.
10296     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10297            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10298       if (UI->getOpcode() == ISD::STORE)
10299         goto default_case;
10300
10301     // Otherwise use a regular EFLAGS-setting instruction.
10302     switch (ArithOp.getOpcode()) {
10303     default: llvm_unreachable("unexpected operator!");
10304     case ISD::SUB: Opcode = X86ISD::SUB; break;
10305     case ISD::XOR: Opcode = X86ISD::XOR; break;
10306     case ISD::AND: Opcode = X86ISD::AND; break;
10307     case ISD::OR: {
10308       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10309         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10310         if (EFLAGS.getNode())
10311           return EFLAGS;
10312       }
10313       Opcode = X86ISD::OR;
10314       break;
10315     }
10316     }
10317
10318     NumOperands = 2;
10319     break;
10320   case X86ISD::ADD:
10321   case X86ISD::SUB:
10322   case X86ISD::INC:
10323   case X86ISD::DEC:
10324   case X86ISD::OR:
10325   case X86ISD::XOR:
10326   case X86ISD::AND:
10327     return SDValue(Op.getNode(), 1);
10328   default:
10329   default_case:
10330     break;
10331   }
10332
10333   // If we found that truncation is beneficial, perform the truncation and
10334   // update 'Op'.
10335   if (NeedTruncation) {
10336     EVT VT = Op.getValueType();
10337     SDValue WideVal = Op->getOperand(0);
10338     EVT WideVT = WideVal.getValueType();
10339     unsigned ConvertedOp = 0;
10340     // Use a target machine opcode to prevent further DAGCombine
10341     // optimizations that may separate the arithmetic operations
10342     // from the setcc node.
10343     switch (WideVal.getOpcode()) {
10344       default: break;
10345       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10346       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10347       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10348       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10349       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10350     }
10351
10352     if (ConvertedOp) {
10353       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10354       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10355         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10356         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10357         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10358       }
10359     }
10360   }
10361
10362   if (Opcode == 0)
10363     // Emit a CMP with 0, which is the TEST pattern.
10364     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10365                        DAG.getConstant(0, Op.getValueType()));
10366
10367   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10368   SmallVector<SDValue, 4> Ops;
10369   for (unsigned i = 0; i != NumOperands; ++i)
10370     Ops.push_back(Op.getOperand(i));
10371
10372   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10373   DAG.ReplaceAllUsesWith(Op, New);
10374   return SDValue(New.getNode(), 1);
10375 }
10376
10377 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10378 /// equivalent.
10379 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10380                                    SDLoc dl, SelectionDAG &DAG) const {
10381   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10382     if (C->getAPIntValue() == 0)
10383       return EmitTest(Op0, X86CC, dl, DAG);
10384
10385      if (Op0.getValueType() == MVT::i1)
10386        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10387   }
10388  
10389   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10390        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10391     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10392     // This avoids subregister aliasing issues. Keep the smaller reference 
10393     // if we're optimizing for size, however, as that'll allow better folding 
10394     // of memory operations.
10395     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10396         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10397              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10398         !Subtarget->isAtom()) {
10399       unsigned ExtendOp =
10400           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10401       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10402       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10403     }
10404     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10405     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10406     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10407                               Op0, Op1);
10408     return SDValue(Sub.getNode(), 1);
10409   }
10410   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10411 }
10412
10413 /// Convert a comparison if required by the subtarget.
10414 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10415                                                  SelectionDAG &DAG) const {
10416   // If the subtarget does not support the FUCOMI instruction, floating-point
10417   // comparisons have to be converted.
10418   if (Subtarget->hasCMov() ||
10419       Cmp.getOpcode() != X86ISD::CMP ||
10420       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10421       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10422     return Cmp;
10423
10424   // The instruction selector will select an FUCOM instruction instead of
10425   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10426   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10427   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10428   SDLoc dl(Cmp);
10429   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10430   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10431   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10432                             DAG.getConstant(8, MVT::i8));
10433   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10434   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10435 }
10436
10437 static bool isAllOnes(SDValue V) {
10438   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10439   return C && C->isAllOnesValue();
10440 }
10441
10442 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10443 /// if it's possible.
10444 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10445                                      SDLoc dl, SelectionDAG &DAG) const {
10446   SDValue Op0 = And.getOperand(0);
10447   SDValue Op1 = And.getOperand(1);
10448   if (Op0.getOpcode() == ISD::TRUNCATE)
10449     Op0 = Op0.getOperand(0);
10450   if (Op1.getOpcode() == ISD::TRUNCATE)
10451     Op1 = Op1.getOperand(0);
10452
10453   SDValue LHS, RHS;
10454   if (Op1.getOpcode() == ISD::SHL)
10455     std::swap(Op0, Op1);
10456   if (Op0.getOpcode() == ISD::SHL) {
10457     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10458       if (And00C->getZExtValue() == 1) {
10459         // If we looked past a truncate, check that it's only truncating away
10460         // known zeros.
10461         unsigned BitWidth = Op0.getValueSizeInBits();
10462         unsigned AndBitWidth = And.getValueSizeInBits();
10463         if (BitWidth > AndBitWidth) {
10464           APInt Zeros, Ones;
10465           DAG.computeKnownBits(Op0, Zeros, Ones);
10466           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10467             return SDValue();
10468         }
10469         LHS = Op1;
10470         RHS = Op0.getOperand(1);
10471       }
10472   } else if (Op1.getOpcode() == ISD::Constant) {
10473     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10474     uint64_t AndRHSVal = AndRHS->getZExtValue();
10475     SDValue AndLHS = Op0;
10476
10477     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10478       LHS = AndLHS.getOperand(0);
10479       RHS = AndLHS.getOperand(1);
10480     }
10481
10482     // Use BT if the immediate can't be encoded in a TEST instruction.
10483     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10484       LHS = AndLHS;
10485       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10486     }
10487   }
10488
10489   if (LHS.getNode()) {
10490     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10491     // instruction.  Since the shift amount is in-range-or-undefined, we know
10492     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10493     // the encoding for the i16 version is larger than the i32 version.
10494     // Also promote i16 to i32 for performance / code size reason.
10495     if (LHS.getValueType() == MVT::i8 ||
10496         LHS.getValueType() == MVT::i16)
10497       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10498
10499     // If the operand types disagree, extend the shift amount to match.  Since
10500     // BT ignores high bits (like shifts) we can use anyextend.
10501     if (LHS.getValueType() != RHS.getValueType())
10502       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10503
10504     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10505     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10506     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10507                        DAG.getConstant(Cond, MVT::i8), BT);
10508   }
10509
10510   return SDValue();
10511 }
10512
10513 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10514 /// mask CMPs.
10515 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10516                               SDValue &Op1) {
10517   unsigned SSECC;
10518   bool Swap = false;
10519
10520   // SSE Condition code mapping:
10521   //  0 - EQ
10522   //  1 - LT
10523   //  2 - LE
10524   //  3 - UNORD
10525   //  4 - NEQ
10526   //  5 - NLT
10527   //  6 - NLE
10528   //  7 - ORD
10529   switch (SetCCOpcode) {
10530   default: llvm_unreachable("Unexpected SETCC condition");
10531   case ISD::SETOEQ:
10532   case ISD::SETEQ:  SSECC = 0; break;
10533   case ISD::SETOGT:
10534   case ISD::SETGT:  Swap = true; // Fallthrough
10535   case ISD::SETLT:
10536   case ISD::SETOLT: SSECC = 1; break;
10537   case ISD::SETOGE:
10538   case ISD::SETGE:  Swap = true; // Fallthrough
10539   case ISD::SETLE:
10540   case ISD::SETOLE: SSECC = 2; break;
10541   case ISD::SETUO:  SSECC = 3; break;
10542   case ISD::SETUNE:
10543   case ISD::SETNE:  SSECC = 4; break;
10544   case ISD::SETULE: Swap = true; // Fallthrough
10545   case ISD::SETUGE: SSECC = 5; break;
10546   case ISD::SETULT: Swap = true; // Fallthrough
10547   case ISD::SETUGT: SSECC = 6; break;
10548   case ISD::SETO:   SSECC = 7; break;
10549   case ISD::SETUEQ:
10550   case ISD::SETONE: SSECC = 8; break;
10551   }
10552   if (Swap)
10553     std::swap(Op0, Op1);
10554
10555   return SSECC;
10556 }
10557
10558 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10559 // ones, and then concatenate the result back.
10560 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10561   MVT VT = Op.getSimpleValueType();
10562
10563   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10564          "Unsupported value type for operation");
10565
10566   unsigned NumElems = VT.getVectorNumElements();
10567   SDLoc dl(Op);
10568   SDValue CC = Op.getOperand(2);
10569
10570   // Extract the LHS vectors
10571   SDValue LHS = Op.getOperand(0);
10572   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10573   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10574
10575   // Extract the RHS vectors
10576   SDValue RHS = Op.getOperand(1);
10577   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10578   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10579
10580   // Issue the operation on the smaller types and concatenate the result back
10581   MVT EltVT = VT.getVectorElementType();
10582   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10583   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10584                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10585                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10586 }
10587
10588 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10589                                      const X86Subtarget *Subtarget) {
10590   SDValue Op0 = Op.getOperand(0);
10591   SDValue Op1 = Op.getOperand(1);
10592   SDValue CC = Op.getOperand(2);
10593   MVT VT = Op.getSimpleValueType();
10594   SDLoc dl(Op);
10595
10596   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10597          Op.getValueType().getScalarType() == MVT::i1 &&
10598          "Cannot set masked compare for this operation");
10599
10600   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10601   unsigned  Opc = 0;
10602   bool Unsigned = false;
10603   bool Swap = false;
10604   unsigned SSECC;
10605   switch (SetCCOpcode) {
10606   default: llvm_unreachable("Unexpected SETCC condition");
10607   case ISD::SETNE:  SSECC = 4; break;
10608   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10609   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10610   case ISD::SETLT:  Swap = true; //fall-through
10611   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10612   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10613   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10614   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10615   case ISD::SETULE: Unsigned = true; //fall-through
10616   case ISD::SETLE:  SSECC = 2; break;
10617   }
10618
10619   if (Swap)
10620     std::swap(Op0, Op1);
10621   if (Opc)
10622     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10623   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10624   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10625                      DAG.getConstant(SSECC, MVT::i8));
10626 }
10627
10628 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10629 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10630 /// return an empty value.
10631 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10632 {
10633   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10634   if (!BV)
10635     return SDValue();
10636
10637   MVT VT = Op1.getSimpleValueType();
10638   MVT EVT = VT.getVectorElementType();
10639   unsigned n = VT.getVectorNumElements();
10640   SmallVector<SDValue, 8> ULTOp1;
10641
10642   for (unsigned i = 0; i < n; ++i) {
10643     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10644     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10645       return SDValue();
10646
10647     // Avoid underflow.
10648     APInt Val = Elt->getAPIntValue();
10649     if (Val == 0)
10650       return SDValue();
10651
10652     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10653   }
10654
10655   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10656 }
10657
10658 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10659                            SelectionDAG &DAG) {
10660   SDValue Op0 = Op.getOperand(0);
10661   SDValue Op1 = Op.getOperand(1);
10662   SDValue CC = Op.getOperand(2);
10663   MVT VT = Op.getSimpleValueType();
10664   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10665   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10666   SDLoc dl(Op);
10667
10668   if (isFP) {
10669 #ifndef NDEBUG
10670     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10671     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10672 #endif
10673
10674     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10675     unsigned Opc = X86ISD::CMPP;
10676     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10677       assert(VT.getVectorNumElements() <= 16);
10678       Opc = X86ISD::CMPM;
10679     }
10680     // In the two special cases we can't handle, emit two comparisons.
10681     if (SSECC == 8) {
10682       unsigned CC0, CC1;
10683       unsigned CombineOpc;
10684       if (SetCCOpcode == ISD::SETUEQ) {
10685         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10686       } else {
10687         assert(SetCCOpcode == ISD::SETONE);
10688         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10689       }
10690
10691       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10692                                  DAG.getConstant(CC0, MVT::i8));
10693       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10694                                  DAG.getConstant(CC1, MVT::i8));
10695       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10696     }
10697     // Handle all other FP comparisons here.
10698     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10699                        DAG.getConstant(SSECC, MVT::i8));
10700   }
10701
10702   // Break 256-bit integer vector compare into smaller ones.
10703   if (VT.is256BitVector() && !Subtarget->hasInt256())
10704     return Lower256IntVSETCC(Op, DAG);
10705
10706   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10707   EVT OpVT = Op1.getValueType();
10708   if (Subtarget->hasAVX512()) {
10709     if (Op1.getValueType().is512BitVector() ||
10710         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10711       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10712
10713     // In AVX-512 architecture setcc returns mask with i1 elements,
10714     // But there is no compare instruction for i8 and i16 elements.
10715     // We are not talking about 512-bit operands in this case, these
10716     // types are illegal.
10717     if (MaskResult &&
10718         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10719          OpVT.getVectorElementType().getSizeInBits() >= 8))
10720       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10721                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10722   }
10723
10724   // We are handling one of the integer comparisons here.  Since SSE only has
10725   // GT and EQ comparisons for integer, swapping operands and multiple
10726   // operations may be required for some comparisons.
10727   unsigned Opc;
10728   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10729   bool Subus = false;
10730
10731   switch (SetCCOpcode) {
10732   default: llvm_unreachable("Unexpected SETCC condition");
10733   case ISD::SETNE:  Invert = true;
10734   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10735   case ISD::SETLT:  Swap = true;
10736   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10737   case ISD::SETGE:  Swap = true;
10738   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10739                     Invert = true; break;
10740   case ISD::SETULT: Swap = true;
10741   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10742                     FlipSigns = true; break;
10743   case ISD::SETUGE: Swap = true;
10744   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10745                     FlipSigns = true; Invert = true; break;
10746   }
10747
10748   // Special case: Use min/max operations for SETULE/SETUGE
10749   MVT VET = VT.getVectorElementType();
10750   bool hasMinMax =
10751        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10752     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10753
10754   if (hasMinMax) {
10755     switch (SetCCOpcode) {
10756     default: break;
10757     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10758     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10759     }
10760
10761     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10762   }
10763
10764   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10765   if (!MinMax && hasSubus) {
10766     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10767     // Op0 u<= Op1:
10768     //   t = psubus Op0, Op1
10769     //   pcmpeq t, <0..0>
10770     switch (SetCCOpcode) {
10771     default: break;
10772     case ISD::SETULT: {
10773       // If the comparison is against a constant we can turn this into a
10774       // setule.  With psubus, setule does not require a swap.  This is
10775       // beneficial because the constant in the register is no longer
10776       // destructed as the destination so it can be hoisted out of a loop.
10777       // Only do this pre-AVX since vpcmp* is no longer destructive.
10778       if (Subtarget->hasAVX())
10779         break;
10780       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10781       if (ULEOp1.getNode()) {
10782         Op1 = ULEOp1;
10783         Subus = true; Invert = false; Swap = false;
10784       }
10785       break;
10786     }
10787     // Psubus is better than flip-sign because it requires no inversion.
10788     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10789     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10790     }
10791
10792     if (Subus) {
10793       Opc = X86ISD::SUBUS;
10794       FlipSigns = false;
10795     }
10796   }
10797
10798   if (Swap)
10799     std::swap(Op0, Op1);
10800
10801   // Check that the operation in question is available (most are plain SSE2,
10802   // but PCMPGTQ and PCMPEQQ have different requirements).
10803   if (VT == MVT::v2i64) {
10804     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10805       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10806
10807       // First cast everything to the right type.
10808       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10809       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10810
10811       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10812       // bits of the inputs before performing those operations. The lower
10813       // compare is always unsigned.
10814       SDValue SB;
10815       if (FlipSigns) {
10816         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10817       } else {
10818         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10819         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10820         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10821                          Sign, Zero, Sign, Zero);
10822       }
10823       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10824       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10825
10826       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10827       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10828       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10829
10830       // Create masks for only the low parts/high parts of the 64 bit integers.
10831       static const int MaskHi[] = { 1, 1, 3, 3 };
10832       static const int MaskLo[] = { 0, 0, 2, 2 };
10833       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10834       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10835       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10836
10837       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10838       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10839
10840       if (Invert)
10841         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10842
10843       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10844     }
10845
10846     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10847       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10848       // pcmpeqd + pshufd + pand.
10849       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10850
10851       // First cast everything to the right type.
10852       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10853       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10854
10855       // Do the compare.
10856       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10857
10858       // Make sure the lower and upper halves are both all-ones.
10859       static const int Mask[] = { 1, 0, 3, 2 };
10860       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10861       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10862
10863       if (Invert)
10864         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10865
10866       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10867     }
10868   }
10869
10870   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10871   // bits of the inputs before performing those operations.
10872   if (FlipSigns) {
10873     EVT EltVT = VT.getVectorElementType();
10874     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10875     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10876     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10877   }
10878
10879   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10880
10881   // If the logical-not of the result is required, perform that now.
10882   if (Invert)
10883     Result = DAG.getNOT(dl, Result, VT);
10884
10885   if (MinMax)
10886     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10887
10888   if (Subus)
10889     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10890                          getZeroVector(VT, Subtarget, DAG, dl));
10891
10892   return Result;
10893 }
10894
10895 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10896
10897   MVT VT = Op.getSimpleValueType();
10898
10899   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10900
10901   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10902          && "SetCC type must be 8-bit or 1-bit integer");
10903   SDValue Op0 = Op.getOperand(0);
10904   SDValue Op1 = Op.getOperand(1);
10905   SDLoc dl(Op);
10906   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10907
10908   // Optimize to BT if possible.
10909   // Lower (X & (1 << N)) == 0 to BT(X, N).
10910   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10911   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10912   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10913       Op1.getOpcode() == ISD::Constant &&
10914       cast<ConstantSDNode>(Op1)->isNullValue() &&
10915       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10916     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10917     if (NewSetCC.getNode())
10918       return NewSetCC;
10919   }
10920
10921   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10922   // these.
10923   if (Op1.getOpcode() == ISD::Constant &&
10924       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10925        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10926       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10927
10928     // If the input is a setcc, then reuse the input setcc or use a new one with
10929     // the inverted condition.
10930     if (Op0.getOpcode() == X86ISD::SETCC) {
10931       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10932       bool Invert = (CC == ISD::SETNE) ^
10933         cast<ConstantSDNode>(Op1)->isNullValue();
10934       if (!Invert)
10935         return Op0;
10936
10937       CCode = X86::GetOppositeBranchCondition(CCode);
10938       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10939                                   DAG.getConstant(CCode, MVT::i8),
10940                                   Op0.getOperand(1));
10941       if (VT == MVT::i1)
10942         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10943       return SetCC;
10944     }
10945   }
10946   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10947       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10948       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10949
10950     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10951     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10952   }
10953
10954   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10955   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10956   if (X86CC == X86::COND_INVALID)
10957     return SDValue();
10958
10959   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10960   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10961   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10962                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10963   if (VT == MVT::i1)
10964     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10965   return SetCC;
10966 }
10967
10968 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10969 static bool isX86LogicalCmp(SDValue Op) {
10970   unsigned Opc = Op.getNode()->getOpcode();
10971   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10972       Opc == X86ISD::SAHF)
10973     return true;
10974   if (Op.getResNo() == 1 &&
10975       (Opc == X86ISD::ADD ||
10976        Opc == X86ISD::SUB ||
10977        Opc == X86ISD::ADC ||
10978        Opc == X86ISD::SBB ||
10979        Opc == X86ISD::SMUL ||
10980        Opc == X86ISD::UMUL ||
10981        Opc == X86ISD::INC ||
10982        Opc == X86ISD::DEC ||
10983        Opc == X86ISD::OR ||
10984        Opc == X86ISD::XOR ||
10985        Opc == X86ISD::AND))
10986     return true;
10987
10988   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10989     return true;
10990
10991   return false;
10992 }
10993
10994 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10995   if (V.getOpcode() != ISD::TRUNCATE)
10996     return false;
10997
10998   SDValue VOp0 = V.getOperand(0);
10999   unsigned InBits = VOp0.getValueSizeInBits();
11000   unsigned Bits = V.getValueSizeInBits();
11001   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11002 }
11003
11004 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11005   bool addTest = true;
11006   SDValue Cond  = Op.getOperand(0);
11007   SDValue Op1 = Op.getOperand(1);
11008   SDValue Op2 = Op.getOperand(2);
11009   SDLoc DL(Op);
11010   EVT VT = Op1.getValueType();
11011   SDValue CC;
11012
11013   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11014   // are available. Otherwise fp cmovs get lowered into a less efficient branch
11015   // sequence later on.
11016   if (Cond.getOpcode() == ISD::SETCC &&
11017       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11018        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11019       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11020     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11021     int SSECC = translateX86FSETCC(
11022         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11023
11024     if (SSECC != 8) {
11025       if (Subtarget->hasAVX512()) {
11026         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11027                                   DAG.getConstant(SSECC, MVT::i8));
11028         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11029       }
11030       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11031                                 DAG.getConstant(SSECC, MVT::i8));
11032       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11033       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11034       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11035     }
11036   }
11037
11038   if (Cond.getOpcode() == ISD::SETCC) {
11039     SDValue NewCond = LowerSETCC(Cond, DAG);
11040     if (NewCond.getNode())
11041       Cond = NewCond;
11042   }
11043
11044   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11045   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11046   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11047   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11048   if (Cond.getOpcode() == X86ISD::SETCC &&
11049       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11050       isZero(Cond.getOperand(1).getOperand(1))) {
11051     SDValue Cmp = Cond.getOperand(1);
11052
11053     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11054
11055     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11056         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11057       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11058
11059       SDValue CmpOp0 = Cmp.getOperand(0);
11060       // Apply further optimizations for special cases
11061       // (select (x != 0), -1, 0) -> neg & sbb
11062       // (select (x == 0), 0, -1) -> neg & sbb
11063       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11064         if (YC->isNullValue() &&
11065             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11066           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11067           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11068                                     DAG.getConstant(0, CmpOp0.getValueType()),
11069                                     CmpOp0);
11070           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11071                                     DAG.getConstant(X86::COND_B, MVT::i8),
11072                                     SDValue(Neg.getNode(), 1));
11073           return Res;
11074         }
11075
11076       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11077                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11078       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11079
11080       SDValue Res =   // Res = 0 or -1.
11081         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11082                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11083
11084       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11085         Res = DAG.getNOT(DL, Res, Res.getValueType());
11086
11087       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11088       if (!N2C || !N2C->isNullValue())
11089         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11090       return Res;
11091     }
11092   }
11093
11094   // Look past (and (setcc_carry (cmp ...)), 1).
11095   if (Cond.getOpcode() == ISD::AND &&
11096       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11097     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11098     if (C && C->getAPIntValue() == 1)
11099       Cond = Cond.getOperand(0);
11100   }
11101
11102   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11103   // setting operand in place of the X86ISD::SETCC.
11104   unsigned CondOpcode = Cond.getOpcode();
11105   if (CondOpcode == X86ISD::SETCC ||
11106       CondOpcode == X86ISD::SETCC_CARRY) {
11107     CC = Cond.getOperand(0);
11108
11109     SDValue Cmp = Cond.getOperand(1);
11110     unsigned Opc = Cmp.getOpcode();
11111     MVT VT = Op.getSimpleValueType();
11112
11113     bool IllegalFPCMov = false;
11114     if (VT.isFloatingPoint() && !VT.isVector() &&
11115         !isScalarFPTypeInSSEReg(VT))  // FPStack?
11116       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11117
11118     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11119         Opc == X86ISD::BT) { // FIXME
11120       Cond = Cmp;
11121       addTest = false;
11122     }
11123   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11124              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11125              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11126               Cond.getOperand(0).getValueType() != MVT::i8)) {
11127     SDValue LHS = Cond.getOperand(0);
11128     SDValue RHS = Cond.getOperand(1);
11129     unsigned X86Opcode;
11130     unsigned X86Cond;
11131     SDVTList VTs;
11132     switch (CondOpcode) {
11133     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11134     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11135     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11136     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11137     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11138     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11139     default: llvm_unreachable("unexpected overflowing operator");
11140     }
11141     if (CondOpcode == ISD::UMULO)
11142       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11143                           MVT::i32);
11144     else
11145       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11146
11147     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11148
11149     if (CondOpcode == ISD::UMULO)
11150       Cond = X86Op.getValue(2);
11151     else
11152       Cond = X86Op.getValue(1);
11153
11154     CC = DAG.getConstant(X86Cond, MVT::i8);
11155     addTest = false;
11156   }
11157
11158   if (addTest) {
11159     // Look pass the truncate if the high bits are known zero.
11160     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11161         Cond = Cond.getOperand(0);
11162
11163     // We know the result of AND is compared against zero. Try to match
11164     // it to BT.
11165     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11166       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11167       if (NewSetCC.getNode()) {
11168         CC = NewSetCC.getOperand(0);
11169         Cond = NewSetCC.getOperand(1);
11170         addTest = false;
11171       }
11172     }
11173   }
11174
11175   if (addTest) {
11176     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11177     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11178   }
11179
11180   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11181   // a <  b ?  0 : -1 -> RES = setcc_carry
11182   // a >= b ? -1 :  0 -> RES = setcc_carry
11183   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11184   if (Cond.getOpcode() == X86ISD::SUB) {
11185     Cond = ConvertCmpIfNecessary(Cond, DAG);
11186     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11187
11188     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11189         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11190       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11191                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11192       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11193         return DAG.getNOT(DL, Res, Res.getValueType());
11194       return Res;
11195     }
11196   }
11197
11198   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11199   // widen the cmov and push the truncate through. This avoids introducing a new
11200   // branch during isel and doesn't add any extensions.
11201   if (Op.getValueType() == MVT::i8 &&
11202       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11203     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11204     if (T1.getValueType() == T2.getValueType() &&
11205         // Blacklist CopyFromReg to avoid partial register stalls.
11206         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11207       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11208       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11209       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11210     }
11211   }
11212
11213   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11214   // condition is true.
11215   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11216   SDValue Ops[] = { Op2, Op1, CC, Cond };
11217   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11218 }
11219
11220 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11221   MVT VT = Op->getSimpleValueType(0);
11222   SDValue In = Op->getOperand(0);
11223   MVT InVT = In.getSimpleValueType();
11224   SDLoc dl(Op);
11225
11226   unsigned int NumElts = VT.getVectorNumElements();
11227   if (NumElts != 8 && NumElts != 16)
11228     return SDValue();
11229
11230   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11231     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11232
11233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11234   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11235
11236   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11237   Constant *C = ConstantInt::get(*DAG.getContext(),
11238     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11239
11240   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11241   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11242   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11243                           MachinePointerInfo::getConstantPool(),
11244                           false, false, false, Alignment);
11245   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11246   if (VT.is512BitVector())
11247     return Brcst;
11248   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11249 }
11250
11251 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11252                                 SelectionDAG &DAG) {
11253   MVT VT = Op->getSimpleValueType(0);
11254   SDValue In = Op->getOperand(0);
11255   MVT InVT = In.getSimpleValueType();
11256   SDLoc dl(Op);
11257
11258   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11259     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11260
11261   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11262       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11263       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11264     return SDValue();
11265
11266   if (Subtarget->hasInt256())
11267     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11268
11269   // Optimize vectors in AVX mode
11270   // Sign extend  v8i16 to v8i32 and
11271   //              v4i32 to v4i64
11272   //
11273   // Divide input vector into two parts
11274   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11275   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11276   // concat the vectors to original VT
11277
11278   unsigned NumElems = InVT.getVectorNumElements();
11279   SDValue Undef = DAG.getUNDEF(InVT);
11280
11281   SmallVector<int,8> ShufMask1(NumElems, -1);
11282   for (unsigned i = 0; i != NumElems/2; ++i)
11283     ShufMask1[i] = i;
11284
11285   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11286
11287   SmallVector<int,8> ShufMask2(NumElems, -1);
11288   for (unsigned i = 0; i != NumElems/2; ++i)
11289     ShufMask2[i] = i + NumElems/2;
11290
11291   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11292
11293   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11294                                 VT.getVectorNumElements()/2);
11295
11296   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11297   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11298
11299   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11300 }
11301
11302 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11303 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11304 // from the AND / OR.
11305 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11306   Opc = Op.getOpcode();
11307   if (Opc != ISD::OR && Opc != ISD::AND)
11308     return false;
11309   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11310           Op.getOperand(0).hasOneUse() &&
11311           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11312           Op.getOperand(1).hasOneUse());
11313 }
11314
11315 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11316 // 1 and that the SETCC node has a single use.
11317 static bool isXor1OfSetCC(SDValue Op) {
11318   if (Op.getOpcode() != ISD::XOR)
11319     return false;
11320   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11321   if (N1C && N1C->getAPIntValue() == 1) {
11322     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11323       Op.getOperand(0).hasOneUse();
11324   }
11325   return false;
11326 }
11327
11328 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11329   bool addTest = true;
11330   SDValue Chain = Op.getOperand(0);
11331   SDValue Cond  = Op.getOperand(1);
11332   SDValue Dest  = Op.getOperand(2);
11333   SDLoc dl(Op);
11334   SDValue CC;
11335   bool Inverted = false;
11336
11337   if (Cond.getOpcode() == ISD::SETCC) {
11338     // Check for setcc([su]{add,sub,mul}o == 0).
11339     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11340         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11341         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11342         Cond.getOperand(0).getResNo() == 1 &&
11343         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11344          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11345          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11346          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11347          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11348          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11349       Inverted = true;
11350       Cond = Cond.getOperand(0);
11351     } else {
11352       SDValue NewCond = LowerSETCC(Cond, DAG);
11353       if (NewCond.getNode())
11354         Cond = NewCond;
11355     }
11356   }
11357 #if 0
11358   // FIXME: LowerXALUO doesn't handle these!!
11359   else if (Cond.getOpcode() == X86ISD::ADD  ||
11360            Cond.getOpcode() == X86ISD::SUB  ||
11361            Cond.getOpcode() == X86ISD::SMUL ||
11362            Cond.getOpcode() == X86ISD::UMUL)
11363     Cond = LowerXALUO(Cond, DAG);
11364 #endif
11365
11366   // Look pass (and (setcc_carry (cmp ...)), 1).
11367   if (Cond.getOpcode() == ISD::AND &&
11368       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11369     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11370     if (C && C->getAPIntValue() == 1)
11371       Cond = Cond.getOperand(0);
11372   }
11373
11374   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11375   // setting operand in place of the X86ISD::SETCC.
11376   unsigned CondOpcode = Cond.getOpcode();
11377   if (CondOpcode == X86ISD::SETCC ||
11378       CondOpcode == X86ISD::SETCC_CARRY) {
11379     CC = Cond.getOperand(0);
11380
11381     SDValue Cmp = Cond.getOperand(1);
11382     unsigned Opc = Cmp.getOpcode();
11383     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11384     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11385       Cond = Cmp;
11386       addTest = false;
11387     } else {
11388       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11389       default: break;
11390       case X86::COND_O:
11391       case X86::COND_B:
11392         // These can only come from an arithmetic instruction with overflow,
11393         // e.g. SADDO, UADDO.
11394         Cond = Cond.getNode()->getOperand(1);
11395         addTest = false;
11396         break;
11397       }
11398     }
11399   }
11400   CondOpcode = Cond.getOpcode();
11401   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11402       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11403       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11404        Cond.getOperand(0).getValueType() != MVT::i8)) {
11405     SDValue LHS = Cond.getOperand(0);
11406     SDValue RHS = Cond.getOperand(1);
11407     unsigned X86Opcode;
11408     unsigned X86Cond;
11409     SDVTList VTs;
11410     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11411     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11412     // X86ISD::INC).
11413     switch (CondOpcode) {
11414     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11415     case ISD::SADDO:
11416       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11417         if (C->isOne()) {
11418           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11419           break;
11420         }
11421       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11422     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11423     case ISD::SSUBO:
11424       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11425         if (C->isOne()) {
11426           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11427           break;
11428         }
11429       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11430     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11431     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11432     default: llvm_unreachable("unexpected overflowing operator");
11433     }
11434     if (Inverted)
11435       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11436     if (CondOpcode == ISD::UMULO)
11437       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11438                           MVT::i32);
11439     else
11440       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11441
11442     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11443
11444     if (CondOpcode == ISD::UMULO)
11445       Cond = X86Op.getValue(2);
11446     else
11447       Cond = X86Op.getValue(1);
11448
11449     CC = DAG.getConstant(X86Cond, MVT::i8);
11450     addTest = false;
11451   } else {
11452     unsigned CondOpc;
11453     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11454       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11455       if (CondOpc == ISD::OR) {
11456         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11457         // two branches instead of an explicit OR instruction with a
11458         // separate test.
11459         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11460             isX86LogicalCmp(Cmp)) {
11461           CC = Cond.getOperand(0).getOperand(0);
11462           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11463                               Chain, Dest, CC, Cmp);
11464           CC = Cond.getOperand(1).getOperand(0);
11465           Cond = Cmp;
11466           addTest = false;
11467         }
11468       } else { // ISD::AND
11469         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11470         // two branches instead of an explicit AND instruction with a
11471         // separate test. However, we only do this if this block doesn't
11472         // have a fall-through edge, because this requires an explicit
11473         // jmp when the condition is false.
11474         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11475             isX86LogicalCmp(Cmp) &&
11476             Op.getNode()->hasOneUse()) {
11477           X86::CondCode CCode =
11478             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11479           CCode = X86::GetOppositeBranchCondition(CCode);
11480           CC = DAG.getConstant(CCode, MVT::i8);
11481           SDNode *User = *Op.getNode()->use_begin();
11482           // Look for an unconditional branch following this conditional branch.
11483           // We need this because we need to reverse the successors in order
11484           // to implement FCMP_OEQ.
11485           if (User->getOpcode() == ISD::BR) {
11486             SDValue FalseBB = User->getOperand(1);
11487             SDNode *NewBR =
11488               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11489             assert(NewBR == User);
11490             (void)NewBR;
11491             Dest = FalseBB;
11492
11493             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11494                                 Chain, Dest, CC, Cmp);
11495             X86::CondCode CCode =
11496               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11497             CCode = X86::GetOppositeBranchCondition(CCode);
11498             CC = DAG.getConstant(CCode, MVT::i8);
11499             Cond = Cmp;
11500             addTest = false;
11501           }
11502         }
11503       }
11504     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11505       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11506       // It should be transformed during dag combiner except when the condition
11507       // is set by a arithmetics with overflow node.
11508       X86::CondCode CCode =
11509         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11510       CCode = X86::GetOppositeBranchCondition(CCode);
11511       CC = DAG.getConstant(CCode, MVT::i8);
11512       Cond = Cond.getOperand(0).getOperand(1);
11513       addTest = false;
11514     } else if (Cond.getOpcode() == ISD::SETCC &&
11515                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11516       // For FCMP_OEQ, we can emit
11517       // two branches instead of an explicit AND instruction with a
11518       // separate test. However, we only do this if this block doesn't
11519       // have a fall-through edge, because this requires an explicit
11520       // jmp when the condition is false.
11521       if (Op.getNode()->hasOneUse()) {
11522         SDNode *User = *Op.getNode()->use_begin();
11523         // Look for an unconditional branch following this conditional branch.
11524         // We need this because we need to reverse the successors in order
11525         // to implement FCMP_OEQ.
11526         if (User->getOpcode() == ISD::BR) {
11527           SDValue FalseBB = User->getOperand(1);
11528           SDNode *NewBR =
11529             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11530           assert(NewBR == User);
11531           (void)NewBR;
11532           Dest = FalseBB;
11533
11534           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11535                                     Cond.getOperand(0), Cond.getOperand(1));
11536           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11537           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11538           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11539                               Chain, Dest, CC, Cmp);
11540           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11541           Cond = Cmp;
11542           addTest = false;
11543         }
11544       }
11545     } else if (Cond.getOpcode() == ISD::SETCC &&
11546                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11547       // For FCMP_UNE, we can emit
11548       // two branches instead of an explicit AND instruction with a
11549       // separate test. However, we only do this if this block doesn't
11550       // have a fall-through edge, because this requires an explicit
11551       // jmp when the condition is false.
11552       if (Op.getNode()->hasOneUse()) {
11553         SDNode *User = *Op.getNode()->use_begin();
11554         // Look for an unconditional branch following this conditional branch.
11555         // We need this because we need to reverse the successors in order
11556         // to implement FCMP_UNE.
11557         if (User->getOpcode() == ISD::BR) {
11558           SDValue FalseBB = User->getOperand(1);
11559           SDNode *NewBR =
11560             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11561           assert(NewBR == User);
11562           (void)NewBR;
11563
11564           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11565                                     Cond.getOperand(0), Cond.getOperand(1));
11566           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11567           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11568           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11569                               Chain, Dest, CC, Cmp);
11570           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11571           Cond = Cmp;
11572           addTest = false;
11573           Dest = FalseBB;
11574         }
11575       }
11576     }
11577   }
11578
11579   if (addTest) {
11580     // Look pass the truncate if the high bits are known zero.
11581     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11582         Cond = Cond.getOperand(0);
11583
11584     // We know the result of AND is compared against zero. Try to match
11585     // it to BT.
11586     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11587       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11588       if (NewSetCC.getNode()) {
11589         CC = NewSetCC.getOperand(0);
11590         Cond = NewSetCC.getOperand(1);
11591         addTest = false;
11592       }
11593     }
11594   }
11595
11596   if (addTest) {
11597     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11598     CC = DAG.getConstant(X86Cond, MVT::i8);
11599     Cond = EmitTest(Cond, X86Cond, dl, DAG);
11600   }
11601   Cond = ConvertCmpIfNecessary(Cond, DAG);
11602   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11603                      Chain, Dest, CC, Cond);
11604 }
11605
11606 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11607 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11608 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11609 // that the guard pages used by the OS virtual memory manager are allocated in
11610 // correct sequence.
11611 SDValue
11612 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11613                                            SelectionDAG &DAG) const {
11614   MachineFunction &MF = DAG.getMachineFunction();
11615   bool SplitStack = MF.shouldSplitStack();
11616   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11617                SplitStack;
11618   SDLoc dl(Op);
11619
11620   if (!Lower) {
11621     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11622     SDNode* Node = Op.getNode();
11623
11624     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11625     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11626         " not tell us which reg is the stack pointer!");
11627     EVT VT = Node->getValueType(0);
11628     SDValue Tmp1 = SDValue(Node, 0);
11629     SDValue Tmp2 = SDValue(Node, 1);
11630     SDValue Tmp3 = Node->getOperand(2);
11631     SDValue Chain = Tmp1.getOperand(0);
11632
11633     // Chain the dynamic stack allocation so that it doesn't modify the stack
11634     // pointer when other instructions are using the stack.
11635     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11636         SDLoc(Node));
11637
11638     SDValue Size = Tmp2.getOperand(1);
11639     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11640     Chain = SP.getValue(1);
11641     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11642     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11643     unsigned StackAlign = TFI.getStackAlignment();
11644     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11645     if (Align > StackAlign)
11646       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11647           DAG.getConstant(-(uint64_t)Align, VT));
11648     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11649
11650     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11651         DAG.getIntPtrConstant(0, true), SDValue(),
11652         SDLoc(Node));
11653
11654     SDValue Ops[2] = { Tmp1, Tmp2 };
11655     return DAG.getMergeValues(Ops, dl);
11656   }
11657
11658   // Get the inputs.
11659   SDValue Chain = Op.getOperand(0);
11660   SDValue Size  = Op.getOperand(1);
11661   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11662   EVT VT = Op.getNode()->getValueType(0);
11663
11664   bool Is64Bit = Subtarget->is64Bit();
11665   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11666
11667   if (SplitStack) {
11668     MachineRegisterInfo &MRI = MF.getRegInfo();
11669
11670     if (Is64Bit) {
11671       // The 64 bit implementation of segmented stacks needs to clobber both r10
11672       // r11. This makes it impossible to use it along with nested parameters.
11673       const Function *F = MF.getFunction();
11674
11675       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11676            I != E; ++I)
11677         if (I->hasNestAttr())
11678           report_fatal_error("Cannot use segmented stacks with functions that "
11679                              "have nested arguments.");
11680     }
11681
11682     const TargetRegisterClass *AddrRegClass =
11683       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11684     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11685     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11686     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11687                                 DAG.getRegister(Vreg, SPTy));
11688     SDValue Ops1[2] = { Value, Chain };
11689     return DAG.getMergeValues(Ops1, dl);
11690   } else {
11691     SDValue Flag;
11692     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11693
11694     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11695     Flag = Chain.getValue(1);
11696     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11697
11698     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11699
11700     const X86RegisterInfo *RegInfo =
11701       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11702     unsigned SPReg = RegInfo->getStackRegister();
11703     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11704     Chain = SP.getValue(1);
11705
11706     if (Align) {
11707       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11708                        DAG.getConstant(-(uint64_t)Align, VT));
11709       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11710     }
11711
11712     SDValue Ops1[2] = { SP, Chain };
11713     return DAG.getMergeValues(Ops1, dl);
11714   }
11715 }
11716
11717 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11718   MachineFunction &MF = DAG.getMachineFunction();
11719   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11720
11721   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11722   SDLoc DL(Op);
11723
11724   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11725     // vastart just stores the address of the VarArgsFrameIndex slot into the
11726     // memory location argument.
11727     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11728                                    getPointerTy());
11729     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11730                         MachinePointerInfo(SV), false, false, 0);
11731   }
11732
11733   // __va_list_tag:
11734   //   gp_offset         (0 - 6 * 8)
11735   //   fp_offset         (48 - 48 + 8 * 16)
11736   //   overflow_arg_area (point to parameters coming in memory).
11737   //   reg_save_area
11738   SmallVector<SDValue, 8> MemOps;
11739   SDValue FIN = Op.getOperand(1);
11740   // Store gp_offset
11741   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11742                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11743                                                MVT::i32),
11744                                FIN, MachinePointerInfo(SV), false, false, 0);
11745   MemOps.push_back(Store);
11746
11747   // Store fp_offset
11748   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11749                     FIN, DAG.getIntPtrConstant(4));
11750   Store = DAG.getStore(Op.getOperand(0), DL,
11751                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11752                                        MVT::i32),
11753                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11754   MemOps.push_back(Store);
11755
11756   // Store ptr to overflow_arg_area
11757   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11758                     FIN, DAG.getIntPtrConstant(4));
11759   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11760                                     getPointerTy());
11761   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11762                        MachinePointerInfo(SV, 8),
11763                        false, false, 0);
11764   MemOps.push_back(Store);
11765
11766   // Store ptr to reg_save_area.
11767   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11768                     FIN, DAG.getIntPtrConstant(8));
11769   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11770                                     getPointerTy());
11771   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11772                        MachinePointerInfo(SV, 16), false, false, 0);
11773   MemOps.push_back(Store);
11774   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11775 }
11776
11777 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11778   assert(Subtarget->is64Bit() &&
11779          "LowerVAARG only handles 64-bit va_arg!");
11780   assert((Subtarget->isTargetLinux() ||
11781           Subtarget->isTargetDarwin()) &&
11782           "Unhandled target in LowerVAARG");
11783   assert(Op.getNode()->getNumOperands() == 4);
11784   SDValue Chain = Op.getOperand(0);
11785   SDValue SrcPtr = Op.getOperand(1);
11786   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11787   unsigned Align = Op.getConstantOperandVal(3);
11788   SDLoc dl(Op);
11789
11790   EVT ArgVT = Op.getNode()->getValueType(0);
11791   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11792   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11793   uint8_t ArgMode;
11794
11795   // Decide which area this value should be read from.
11796   // TODO: Implement the AMD64 ABI in its entirety. This simple
11797   // selection mechanism works only for the basic types.
11798   if (ArgVT == MVT::f80) {
11799     llvm_unreachable("va_arg for f80 not yet implemented");
11800   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11801     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11802   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11803     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11804   } else {
11805     llvm_unreachable("Unhandled argument type in LowerVAARG");
11806   }
11807
11808   if (ArgMode == 2) {
11809     // Sanity Check: Make sure using fp_offset makes sense.
11810     assert(!getTargetMachine().Options.UseSoftFloat &&
11811            !(DAG.getMachineFunction()
11812                 .getFunction()->getAttributes()
11813                 .hasAttribute(AttributeSet::FunctionIndex,
11814                               Attribute::NoImplicitFloat)) &&
11815            Subtarget->hasSSE1());
11816   }
11817
11818   // Insert VAARG_64 node into the DAG
11819   // VAARG_64 returns two values: Variable Argument Address, Chain
11820   SmallVector<SDValue, 11> InstOps;
11821   InstOps.push_back(Chain);
11822   InstOps.push_back(SrcPtr);
11823   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11824   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11825   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11826   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11827   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11828                                           VTs, InstOps, MVT::i64,
11829                                           MachinePointerInfo(SV),
11830                                           /*Align=*/0,
11831                                           /*Volatile=*/false,
11832                                           /*ReadMem=*/true,
11833                                           /*WriteMem=*/true);
11834   Chain = VAARG.getValue(1);
11835
11836   // Load the next argument and return it
11837   return DAG.getLoad(ArgVT, dl,
11838                      Chain,
11839                      VAARG,
11840                      MachinePointerInfo(),
11841                      false, false, false, 0);
11842 }
11843
11844 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11845                            SelectionDAG &DAG) {
11846   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11847   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11848   SDValue Chain = Op.getOperand(0);
11849   SDValue DstPtr = Op.getOperand(1);
11850   SDValue SrcPtr = Op.getOperand(2);
11851   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11852   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11853   SDLoc DL(Op);
11854
11855   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11856                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11857                        false,
11858                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11859 }
11860
11861 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11862 // amount is a constant. Takes immediate version of shift as input.
11863 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11864                                           SDValue SrcOp, uint64_t ShiftAmt,
11865                                           SelectionDAG &DAG) {
11866   MVT ElementType = VT.getVectorElementType();
11867
11868   // Fold this packed shift into its first operand if ShiftAmt is 0.
11869   if (ShiftAmt == 0)
11870     return SrcOp;
11871
11872   // Check for ShiftAmt >= element width
11873   if (ShiftAmt >= ElementType.getSizeInBits()) {
11874     if (Opc == X86ISD::VSRAI)
11875       ShiftAmt = ElementType.getSizeInBits() - 1;
11876     else
11877       return DAG.getConstant(0, VT);
11878   }
11879
11880   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11881          && "Unknown target vector shift-by-constant node");
11882
11883   // Fold this packed vector shift into a build vector if SrcOp is a
11884   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11885   if (VT == SrcOp.getSimpleValueType() &&
11886       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11887     SmallVector<SDValue, 8> Elts;
11888     unsigned NumElts = SrcOp->getNumOperands();
11889     ConstantSDNode *ND;
11890
11891     switch(Opc) {
11892     default: llvm_unreachable(nullptr);
11893     case X86ISD::VSHLI:
11894       for (unsigned i=0; i!=NumElts; ++i) {
11895         SDValue CurrentOp = SrcOp->getOperand(i);
11896         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11897           Elts.push_back(CurrentOp);
11898           continue;
11899         }
11900         ND = cast<ConstantSDNode>(CurrentOp);
11901         const APInt &C = ND->getAPIntValue();
11902         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11903       }
11904       break;
11905     case X86ISD::VSRLI:
11906       for (unsigned i=0; i!=NumElts; ++i) {
11907         SDValue CurrentOp = SrcOp->getOperand(i);
11908         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11909           Elts.push_back(CurrentOp);
11910           continue;
11911         }
11912         ND = cast<ConstantSDNode>(CurrentOp);
11913         const APInt &C = ND->getAPIntValue();
11914         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11915       }
11916       break;
11917     case X86ISD::VSRAI:
11918       for (unsigned i=0; i!=NumElts; ++i) {
11919         SDValue CurrentOp = SrcOp->getOperand(i);
11920         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11921           Elts.push_back(CurrentOp);
11922           continue;
11923         }
11924         ND = cast<ConstantSDNode>(CurrentOp);
11925         const APInt &C = ND->getAPIntValue();
11926         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11927       }
11928       break;
11929     }
11930
11931     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11932   }
11933
11934   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11935 }
11936
11937 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11938 // may or may not be a constant. Takes immediate version of shift as input.
11939 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11940                                    SDValue SrcOp, SDValue ShAmt,
11941                                    SelectionDAG &DAG) {
11942   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11943
11944   // Catch shift-by-constant.
11945   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11946     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11947                                       CShAmt->getZExtValue(), DAG);
11948
11949   // Change opcode to non-immediate version
11950   switch (Opc) {
11951     default: llvm_unreachable("Unknown target vector shift node");
11952     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11953     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11954     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11955   }
11956
11957   // Need to build a vector containing shift amount
11958   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11959   SDValue ShOps[4];
11960   ShOps[0] = ShAmt;
11961   ShOps[1] = DAG.getConstant(0, MVT::i32);
11962   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11963   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11964
11965   // The return type has to be a 128-bit type with the same element
11966   // type as the input type.
11967   MVT EltVT = VT.getVectorElementType();
11968   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11969
11970   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11971   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11972 }
11973
11974 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11975   SDLoc dl(Op);
11976   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11977   switch (IntNo) {
11978   default: return SDValue();    // Don't custom lower most intrinsics.
11979   // Comparison intrinsics.
11980   case Intrinsic::x86_sse_comieq_ss:
11981   case Intrinsic::x86_sse_comilt_ss:
11982   case Intrinsic::x86_sse_comile_ss:
11983   case Intrinsic::x86_sse_comigt_ss:
11984   case Intrinsic::x86_sse_comige_ss:
11985   case Intrinsic::x86_sse_comineq_ss:
11986   case Intrinsic::x86_sse_ucomieq_ss:
11987   case Intrinsic::x86_sse_ucomilt_ss:
11988   case Intrinsic::x86_sse_ucomile_ss:
11989   case Intrinsic::x86_sse_ucomigt_ss:
11990   case Intrinsic::x86_sse_ucomige_ss:
11991   case Intrinsic::x86_sse_ucomineq_ss:
11992   case Intrinsic::x86_sse2_comieq_sd:
11993   case Intrinsic::x86_sse2_comilt_sd:
11994   case Intrinsic::x86_sse2_comile_sd:
11995   case Intrinsic::x86_sse2_comigt_sd:
11996   case Intrinsic::x86_sse2_comige_sd:
11997   case Intrinsic::x86_sse2_comineq_sd:
11998   case Intrinsic::x86_sse2_ucomieq_sd:
11999   case Intrinsic::x86_sse2_ucomilt_sd:
12000   case Intrinsic::x86_sse2_ucomile_sd:
12001   case Intrinsic::x86_sse2_ucomigt_sd:
12002   case Intrinsic::x86_sse2_ucomige_sd:
12003   case Intrinsic::x86_sse2_ucomineq_sd: {
12004     unsigned Opc;
12005     ISD::CondCode CC;
12006     switch (IntNo) {
12007     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12008     case Intrinsic::x86_sse_comieq_ss:
12009     case Intrinsic::x86_sse2_comieq_sd:
12010       Opc = X86ISD::COMI;
12011       CC = ISD::SETEQ;
12012       break;
12013     case Intrinsic::x86_sse_comilt_ss:
12014     case Intrinsic::x86_sse2_comilt_sd:
12015       Opc = X86ISD::COMI;
12016       CC = ISD::SETLT;
12017       break;
12018     case Intrinsic::x86_sse_comile_ss:
12019     case Intrinsic::x86_sse2_comile_sd:
12020       Opc = X86ISD::COMI;
12021       CC = ISD::SETLE;
12022       break;
12023     case Intrinsic::x86_sse_comigt_ss:
12024     case Intrinsic::x86_sse2_comigt_sd:
12025       Opc = X86ISD::COMI;
12026       CC = ISD::SETGT;
12027       break;
12028     case Intrinsic::x86_sse_comige_ss:
12029     case Intrinsic::x86_sse2_comige_sd:
12030       Opc = X86ISD::COMI;
12031       CC = ISD::SETGE;
12032       break;
12033     case Intrinsic::x86_sse_comineq_ss:
12034     case Intrinsic::x86_sse2_comineq_sd:
12035       Opc = X86ISD::COMI;
12036       CC = ISD::SETNE;
12037       break;
12038     case Intrinsic::x86_sse_ucomieq_ss:
12039     case Intrinsic::x86_sse2_ucomieq_sd:
12040       Opc = X86ISD::UCOMI;
12041       CC = ISD::SETEQ;
12042       break;
12043     case Intrinsic::x86_sse_ucomilt_ss:
12044     case Intrinsic::x86_sse2_ucomilt_sd:
12045       Opc = X86ISD::UCOMI;
12046       CC = ISD::SETLT;
12047       break;
12048     case Intrinsic::x86_sse_ucomile_ss:
12049     case Intrinsic::x86_sse2_ucomile_sd:
12050       Opc = X86ISD::UCOMI;
12051       CC = ISD::SETLE;
12052       break;
12053     case Intrinsic::x86_sse_ucomigt_ss:
12054     case Intrinsic::x86_sse2_ucomigt_sd:
12055       Opc = X86ISD::UCOMI;
12056       CC = ISD::SETGT;
12057       break;
12058     case Intrinsic::x86_sse_ucomige_ss:
12059     case Intrinsic::x86_sse2_ucomige_sd:
12060       Opc = X86ISD::UCOMI;
12061       CC = ISD::SETGE;
12062       break;
12063     case Intrinsic::x86_sse_ucomineq_ss:
12064     case Intrinsic::x86_sse2_ucomineq_sd:
12065       Opc = X86ISD::UCOMI;
12066       CC = ISD::SETNE;
12067       break;
12068     }
12069
12070     SDValue LHS = Op.getOperand(1);
12071     SDValue RHS = Op.getOperand(2);
12072     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12073     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12074     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12075     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12076                                 DAG.getConstant(X86CC, MVT::i8), Cond);
12077     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12078   }
12079
12080   // Arithmetic intrinsics.
12081   case Intrinsic::x86_sse2_pmulu_dq:
12082   case Intrinsic::x86_avx2_pmulu_dq:
12083     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12084                        Op.getOperand(1), Op.getOperand(2));
12085
12086   case Intrinsic::x86_sse41_pmuldq:
12087   case Intrinsic::x86_avx2_pmul_dq:
12088     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12089                        Op.getOperand(1), Op.getOperand(2));
12090
12091   case Intrinsic::x86_sse2_pmulhu_w:
12092   case Intrinsic::x86_avx2_pmulhu_w:
12093     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12094                        Op.getOperand(1), Op.getOperand(2));
12095
12096   case Intrinsic::x86_sse2_pmulh_w:
12097   case Intrinsic::x86_avx2_pmulh_w:
12098     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12099                        Op.getOperand(1), Op.getOperand(2));
12100
12101   // SSE2/AVX2 sub with unsigned saturation intrinsics
12102   case Intrinsic::x86_sse2_psubus_b:
12103   case Intrinsic::x86_sse2_psubus_w:
12104   case Intrinsic::x86_avx2_psubus_b:
12105   case Intrinsic::x86_avx2_psubus_w:
12106     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12107                        Op.getOperand(1), Op.getOperand(2));
12108
12109   // SSE3/AVX horizontal add/sub intrinsics
12110   case Intrinsic::x86_sse3_hadd_ps:
12111   case Intrinsic::x86_sse3_hadd_pd:
12112   case Intrinsic::x86_avx_hadd_ps_256:
12113   case Intrinsic::x86_avx_hadd_pd_256:
12114   case Intrinsic::x86_sse3_hsub_ps:
12115   case Intrinsic::x86_sse3_hsub_pd:
12116   case Intrinsic::x86_avx_hsub_ps_256:
12117   case Intrinsic::x86_avx_hsub_pd_256:
12118   case Intrinsic::x86_ssse3_phadd_w_128:
12119   case Intrinsic::x86_ssse3_phadd_d_128:
12120   case Intrinsic::x86_avx2_phadd_w:
12121   case Intrinsic::x86_avx2_phadd_d:
12122   case Intrinsic::x86_ssse3_phsub_w_128:
12123   case Intrinsic::x86_ssse3_phsub_d_128:
12124   case Intrinsic::x86_avx2_phsub_w:
12125   case Intrinsic::x86_avx2_phsub_d: {
12126     unsigned Opcode;
12127     switch (IntNo) {
12128     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12129     case Intrinsic::x86_sse3_hadd_ps:
12130     case Intrinsic::x86_sse3_hadd_pd:
12131     case Intrinsic::x86_avx_hadd_ps_256:
12132     case Intrinsic::x86_avx_hadd_pd_256:
12133       Opcode = X86ISD::FHADD;
12134       break;
12135     case Intrinsic::x86_sse3_hsub_ps:
12136     case Intrinsic::x86_sse3_hsub_pd:
12137     case Intrinsic::x86_avx_hsub_ps_256:
12138     case Intrinsic::x86_avx_hsub_pd_256:
12139       Opcode = X86ISD::FHSUB;
12140       break;
12141     case Intrinsic::x86_ssse3_phadd_w_128:
12142     case Intrinsic::x86_ssse3_phadd_d_128:
12143     case Intrinsic::x86_avx2_phadd_w:
12144     case Intrinsic::x86_avx2_phadd_d:
12145       Opcode = X86ISD::HADD;
12146       break;
12147     case Intrinsic::x86_ssse3_phsub_w_128:
12148     case Intrinsic::x86_ssse3_phsub_d_128:
12149     case Intrinsic::x86_avx2_phsub_w:
12150     case Intrinsic::x86_avx2_phsub_d:
12151       Opcode = X86ISD::HSUB;
12152       break;
12153     }
12154     return DAG.getNode(Opcode, dl, Op.getValueType(),
12155                        Op.getOperand(1), Op.getOperand(2));
12156   }
12157
12158   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12159   case Intrinsic::x86_sse2_pmaxu_b:
12160   case Intrinsic::x86_sse41_pmaxuw:
12161   case Intrinsic::x86_sse41_pmaxud:
12162   case Intrinsic::x86_avx2_pmaxu_b:
12163   case Intrinsic::x86_avx2_pmaxu_w:
12164   case Intrinsic::x86_avx2_pmaxu_d:
12165   case Intrinsic::x86_sse2_pminu_b:
12166   case Intrinsic::x86_sse41_pminuw:
12167   case Intrinsic::x86_sse41_pminud:
12168   case Intrinsic::x86_avx2_pminu_b:
12169   case Intrinsic::x86_avx2_pminu_w:
12170   case Intrinsic::x86_avx2_pminu_d:
12171   case Intrinsic::x86_sse41_pmaxsb:
12172   case Intrinsic::x86_sse2_pmaxs_w:
12173   case Intrinsic::x86_sse41_pmaxsd:
12174   case Intrinsic::x86_avx2_pmaxs_b:
12175   case Intrinsic::x86_avx2_pmaxs_w:
12176   case Intrinsic::x86_avx2_pmaxs_d:
12177   case Intrinsic::x86_sse41_pminsb:
12178   case Intrinsic::x86_sse2_pmins_w:
12179   case Intrinsic::x86_sse41_pminsd:
12180   case Intrinsic::x86_avx2_pmins_b:
12181   case Intrinsic::x86_avx2_pmins_w:
12182   case Intrinsic::x86_avx2_pmins_d: {
12183     unsigned Opcode;
12184     switch (IntNo) {
12185     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12186     case Intrinsic::x86_sse2_pmaxu_b:
12187     case Intrinsic::x86_sse41_pmaxuw:
12188     case Intrinsic::x86_sse41_pmaxud:
12189     case Intrinsic::x86_avx2_pmaxu_b:
12190     case Intrinsic::x86_avx2_pmaxu_w:
12191     case Intrinsic::x86_avx2_pmaxu_d:
12192       Opcode = X86ISD::UMAX;
12193       break;
12194     case Intrinsic::x86_sse2_pminu_b:
12195     case Intrinsic::x86_sse41_pminuw:
12196     case Intrinsic::x86_sse41_pminud:
12197     case Intrinsic::x86_avx2_pminu_b:
12198     case Intrinsic::x86_avx2_pminu_w:
12199     case Intrinsic::x86_avx2_pminu_d:
12200       Opcode = X86ISD::UMIN;
12201       break;
12202     case Intrinsic::x86_sse41_pmaxsb:
12203     case Intrinsic::x86_sse2_pmaxs_w:
12204     case Intrinsic::x86_sse41_pmaxsd:
12205     case Intrinsic::x86_avx2_pmaxs_b:
12206     case Intrinsic::x86_avx2_pmaxs_w:
12207     case Intrinsic::x86_avx2_pmaxs_d:
12208       Opcode = X86ISD::SMAX;
12209       break;
12210     case Intrinsic::x86_sse41_pminsb:
12211     case Intrinsic::x86_sse2_pmins_w:
12212     case Intrinsic::x86_sse41_pminsd:
12213     case Intrinsic::x86_avx2_pmins_b:
12214     case Intrinsic::x86_avx2_pmins_w:
12215     case Intrinsic::x86_avx2_pmins_d:
12216       Opcode = X86ISD::SMIN;
12217       break;
12218     }
12219     return DAG.getNode(Opcode, dl, Op.getValueType(),
12220                        Op.getOperand(1), Op.getOperand(2));
12221   }
12222
12223   // SSE/SSE2/AVX floating point max/min intrinsics.
12224   case Intrinsic::x86_sse_max_ps:
12225   case Intrinsic::x86_sse2_max_pd:
12226   case Intrinsic::x86_avx_max_ps_256:
12227   case Intrinsic::x86_avx_max_pd_256:
12228   case Intrinsic::x86_sse_min_ps:
12229   case Intrinsic::x86_sse2_min_pd:
12230   case Intrinsic::x86_avx_min_ps_256:
12231   case Intrinsic::x86_avx_min_pd_256: {
12232     unsigned Opcode;
12233     switch (IntNo) {
12234     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12235     case Intrinsic::x86_sse_max_ps:
12236     case Intrinsic::x86_sse2_max_pd:
12237     case Intrinsic::x86_avx_max_ps_256:
12238     case Intrinsic::x86_avx_max_pd_256:
12239       Opcode = X86ISD::FMAX;
12240       break;
12241     case Intrinsic::x86_sse_min_ps:
12242     case Intrinsic::x86_sse2_min_pd:
12243     case Intrinsic::x86_avx_min_ps_256:
12244     case Intrinsic::x86_avx_min_pd_256:
12245       Opcode = X86ISD::FMIN;
12246       break;
12247     }
12248     return DAG.getNode(Opcode, dl, Op.getValueType(),
12249                        Op.getOperand(1), Op.getOperand(2));
12250   }
12251
12252   // AVX2 variable shift intrinsics
12253   case Intrinsic::x86_avx2_psllv_d:
12254   case Intrinsic::x86_avx2_psllv_q:
12255   case Intrinsic::x86_avx2_psllv_d_256:
12256   case Intrinsic::x86_avx2_psllv_q_256:
12257   case Intrinsic::x86_avx2_psrlv_d:
12258   case Intrinsic::x86_avx2_psrlv_q:
12259   case Intrinsic::x86_avx2_psrlv_d_256:
12260   case Intrinsic::x86_avx2_psrlv_q_256:
12261   case Intrinsic::x86_avx2_psrav_d:
12262   case Intrinsic::x86_avx2_psrav_d_256: {
12263     unsigned Opcode;
12264     switch (IntNo) {
12265     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12266     case Intrinsic::x86_avx2_psllv_d:
12267     case Intrinsic::x86_avx2_psllv_q:
12268     case Intrinsic::x86_avx2_psllv_d_256:
12269     case Intrinsic::x86_avx2_psllv_q_256:
12270       Opcode = ISD::SHL;
12271       break;
12272     case Intrinsic::x86_avx2_psrlv_d:
12273     case Intrinsic::x86_avx2_psrlv_q:
12274     case Intrinsic::x86_avx2_psrlv_d_256:
12275     case Intrinsic::x86_avx2_psrlv_q_256:
12276       Opcode = ISD::SRL;
12277       break;
12278     case Intrinsic::x86_avx2_psrav_d:
12279     case Intrinsic::x86_avx2_psrav_d_256:
12280       Opcode = ISD::SRA;
12281       break;
12282     }
12283     return DAG.getNode(Opcode, dl, Op.getValueType(),
12284                        Op.getOperand(1), Op.getOperand(2));
12285   }
12286
12287   case Intrinsic::x86_ssse3_pshuf_b_128:
12288   case Intrinsic::x86_avx2_pshuf_b:
12289     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12290                        Op.getOperand(1), Op.getOperand(2));
12291
12292   case Intrinsic::x86_ssse3_psign_b_128:
12293   case Intrinsic::x86_ssse3_psign_w_128:
12294   case Intrinsic::x86_ssse3_psign_d_128:
12295   case Intrinsic::x86_avx2_psign_b:
12296   case Intrinsic::x86_avx2_psign_w:
12297   case Intrinsic::x86_avx2_psign_d:
12298     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12299                        Op.getOperand(1), Op.getOperand(2));
12300
12301   case Intrinsic::x86_sse41_insertps:
12302     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12303                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12304
12305   case Intrinsic::x86_avx_vperm2f128_ps_256:
12306   case Intrinsic::x86_avx_vperm2f128_pd_256:
12307   case Intrinsic::x86_avx_vperm2f128_si_256:
12308   case Intrinsic::x86_avx2_vperm2i128:
12309     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12310                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12311
12312   case Intrinsic::x86_avx2_permd:
12313   case Intrinsic::x86_avx2_permps:
12314     // Operands intentionally swapped. Mask is last operand to intrinsic,
12315     // but second operand for node/instruction.
12316     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12317                        Op.getOperand(2), Op.getOperand(1));
12318
12319   case Intrinsic::x86_sse_sqrt_ps:
12320   case Intrinsic::x86_sse2_sqrt_pd:
12321   case Intrinsic::x86_avx_sqrt_ps_256:
12322   case Intrinsic::x86_avx_sqrt_pd_256:
12323     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12324
12325   // ptest and testp intrinsics. The intrinsic these come from are designed to
12326   // return an integer value, not just an instruction so lower it to the ptest
12327   // or testp pattern and a setcc for the result.
12328   case Intrinsic::x86_sse41_ptestz:
12329   case Intrinsic::x86_sse41_ptestc:
12330   case Intrinsic::x86_sse41_ptestnzc:
12331   case Intrinsic::x86_avx_ptestz_256:
12332   case Intrinsic::x86_avx_ptestc_256:
12333   case Intrinsic::x86_avx_ptestnzc_256:
12334   case Intrinsic::x86_avx_vtestz_ps:
12335   case Intrinsic::x86_avx_vtestc_ps:
12336   case Intrinsic::x86_avx_vtestnzc_ps:
12337   case Intrinsic::x86_avx_vtestz_pd:
12338   case Intrinsic::x86_avx_vtestc_pd:
12339   case Intrinsic::x86_avx_vtestnzc_pd:
12340   case Intrinsic::x86_avx_vtestz_ps_256:
12341   case Intrinsic::x86_avx_vtestc_ps_256:
12342   case Intrinsic::x86_avx_vtestnzc_ps_256:
12343   case Intrinsic::x86_avx_vtestz_pd_256:
12344   case Intrinsic::x86_avx_vtestc_pd_256:
12345   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12346     bool IsTestPacked = false;
12347     unsigned X86CC;
12348     switch (IntNo) {
12349     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12350     case Intrinsic::x86_avx_vtestz_ps:
12351     case Intrinsic::x86_avx_vtestz_pd:
12352     case Intrinsic::x86_avx_vtestz_ps_256:
12353     case Intrinsic::x86_avx_vtestz_pd_256:
12354       IsTestPacked = true; // Fallthrough
12355     case Intrinsic::x86_sse41_ptestz:
12356     case Intrinsic::x86_avx_ptestz_256:
12357       // ZF = 1
12358       X86CC = X86::COND_E;
12359       break;
12360     case Intrinsic::x86_avx_vtestc_ps:
12361     case Intrinsic::x86_avx_vtestc_pd:
12362     case Intrinsic::x86_avx_vtestc_ps_256:
12363     case Intrinsic::x86_avx_vtestc_pd_256:
12364       IsTestPacked = true; // Fallthrough
12365     case Intrinsic::x86_sse41_ptestc:
12366     case Intrinsic::x86_avx_ptestc_256:
12367       // CF = 1
12368       X86CC = X86::COND_B;
12369       break;
12370     case Intrinsic::x86_avx_vtestnzc_ps:
12371     case Intrinsic::x86_avx_vtestnzc_pd:
12372     case Intrinsic::x86_avx_vtestnzc_ps_256:
12373     case Intrinsic::x86_avx_vtestnzc_pd_256:
12374       IsTestPacked = true; // Fallthrough
12375     case Intrinsic::x86_sse41_ptestnzc:
12376     case Intrinsic::x86_avx_ptestnzc_256:
12377       // ZF and CF = 0
12378       X86CC = X86::COND_A;
12379       break;
12380     }
12381
12382     SDValue LHS = Op.getOperand(1);
12383     SDValue RHS = Op.getOperand(2);
12384     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12385     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12386     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12387     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12388     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12389   }
12390   case Intrinsic::x86_avx512_kortestz_w:
12391   case Intrinsic::x86_avx512_kortestc_w: {
12392     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12393     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12394     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12395     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12396     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12397     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12398     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12399   }
12400
12401   // SSE/AVX shift intrinsics
12402   case Intrinsic::x86_sse2_psll_w:
12403   case Intrinsic::x86_sse2_psll_d:
12404   case Intrinsic::x86_sse2_psll_q:
12405   case Intrinsic::x86_avx2_psll_w:
12406   case Intrinsic::x86_avx2_psll_d:
12407   case Intrinsic::x86_avx2_psll_q:
12408   case Intrinsic::x86_sse2_psrl_w:
12409   case Intrinsic::x86_sse2_psrl_d:
12410   case Intrinsic::x86_sse2_psrl_q:
12411   case Intrinsic::x86_avx2_psrl_w:
12412   case Intrinsic::x86_avx2_psrl_d:
12413   case Intrinsic::x86_avx2_psrl_q:
12414   case Intrinsic::x86_sse2_psra_w:
12415   case Intrinsic::x86_sse2_psra_d:
12416   case Intrinsic::x86_avx2_psra_w:
12417   case Intrinsic::x86_avx2_psra_d: {
12418     unsigned Opcode;
12419     switch (IntNo) {
12420     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12421     case Intrinsic::x86_sse2_psll_w:
12422     case Intrinsic::x86_sse2_psll_d:
12423     case Intrinsic::x86_sse2_psll_q:
12424     case Intrinsic::x86_avx2_psll_w:
12425     case Intrinsic::x86_avx2_psll_d:
12426     case Intrinsic::x86_avx2_psll_q:
12427       Opcode = X86ISD::VSHL;
12428       break;
12429     case Intrinsic::x86_sse2_psrl_w:
12430     case Intrinsic::x86_sse2_psrl_d:
12431     case Intrinsic::x86_sse2_psrl_q:
12432     case Intrinsic::x86_avx2_psrl_w:
12433     case Intrinsic::x86_avx2_psrl_d:
12434     case Intrinsic::x86_avx2_psrl_q:
12435       Opcode = X86ISD::VSRL;
12436       break;
12437     case Intrinsic::x86_sse2_psra_w:
12438     case Intrinsic::x86_sse2_psra_d:
12439     case Intrinsic::x86_avx2_psra_w:
12440     case Intrinsic::x86_avx2_psra_d:
12441       Opcode = X86ISD::VSRA;
12442       break;
12443     }
12444     return DAG.getNode(Opcode, dl, Op.getValueType(),
12445                        Op.getOperand(1), Op.getOperand(2));
12446   }
12447
12448   // SSE/AVX immediate shift intrinsics
12449   case Intrinsic::x86_sse2_pslli_w:
12450   case Intrinsic::x86_sse2_pslli_d:
12451   case Intrinsic::x86_sse2_pslli_q:
12452   case Intrinsic::x86_avx2_pslli_w:
12453   case Intrinsic::x86_avx2_pslli_d:
12454   case Intrinsic::x86_avx2_pslli_q:
12455   case Intrinsic::x86_sse2_psrli_w:
12456   case Intrinsic::x86_sse2_psrli_d:
12457   case Intrinsic::x86_sse2_psrli_q:
12458   case Intrinsic::x86_avx2_psrli_w:
12459   case Intrinsic::x86_avx2_psrli_d:
12460   case Intrinsic::x86_avx2_psrli_q:
12461   case Intrinsic::x86_sse2_psrai_w:
12462   case Intrinsic::x86_sse2_psrai_d:
12463   case Intrinsic::x86_avx2_psrai_w:
12464   case Intrinsic::x86_avx2_psrai_d: {
12465     unsigned Opcode;
12466     switch (IntNo) {
12467     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12468     case Intrinsic::x86_sse2_pslli_w:
12469     case Intrinsic::x86_sse2_pslli_d:
12470     case Intrinsic::x86_sse2_pslli_q:
12471     case Intrinsic::x86_avx2_pslli_w:
12472     case Intrinsic::x86_avx2_pslli_d:
12473     case Intrinsic::x86_avx2_pslli_q:
12474       Opcode = X86ISD::VSHLI;
12475       break;
12476     case Intrinsic::x86_sse2_psrli_w:
12477     case Intrinsic::x86_sse2_psrli_d:
12478     case Intrinsic::x86_sse2_psrli_q:
12479     case Intrinsic::x86_avx2_psrli_w:
12480     case Intrinsic::x86_avx2_psrli_d:
12481     case Intrinsic::x86_avx2_psrli_q:
12482       Opcode = X86ISD::VSRLI;
12483       break;
12484     case Intrinsic::x86_sse2_psrai_w:
12485     case Intrinsic::x86_sse2_psrai_d:
12486     case Intrinsic::x86_avx2_psrai_w:
12487     case Intrinsic::x86_avx2_psrai_d:
12488       Opcode = X86ISD::VSRAI;
12489       break;
12490     }
12491     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12492                                Op.getOperand(1), Op.getOperand(2), DAG);
12493   }
12494
12495   case Intrinsic::x86_sse42_pcmpistria128:
12496   case Intrinsic::x86_sse42_pcmpestria128:
12497   case Intrinsic::x86_sse42_pcmpistric128:
12498   case Intrinsic::x86_sse42_pcmpestric128:
12499   case Intrinsic::x86_sse42_pcmpistrio128:
12500   case Intrinsic::x86_sse42_pcmpestrio128:
12501   case Intrinsic::x86_sse42_pcmpistris128:
12502   case Intrinsic::x86_sse42_pcmpestris128:
12503   case Intrinsic::x86_sse42_pcmpistriz128:
12504   case Intrinsic::x86_sse42_pcmpestriz128: {
12505     unsigned Opcode;
12506     unsigned X86CC;
12507     switch (IntNo) {
12508     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12509     case Intrinsic::x86_sse42_pcmpistria128:
12510       Opcode = X86ISD::PCMPISTRI;
12511       X86CC = X86::COND_A;
12512       break;
12513     case Intrinsic::x86_sse42_pcmpestria128:
12514       Opcode = X86ISD::PCMPESTRI;
12515       X86CC = X86::COND_A;
12516       break;
12517     case Intrinsic::x86_sse42_pcmpistric128:
12518       Opcode = X86ISD::PCMPISTRI;
12519       X86CC = X86::COND_B;
12520       break;
12521     case Intrinsic::x86_sse42_pcmpestric128:
12522       Opcode = X86ISD::PCMPESTRI;
12523       X86CC = X86::COND_B;
12524       break;
12525     case Intrinsic::x86_sse42_pcmpistrio128:
12526       Opcode = X86ISD::PCMPISTRI;
12527       X86CC = X86::COND_O;
12528       break;
12529     case Intrinsic::x86_sse42_pcmpestrio128:
12530       Opcode = X86ISD::PCMPESTRI;
12531       X86CC = X86::COND_O;
12532       break;
12533     case Intrinsic::x86_sse42_pcmpistris128:
12534       Opcode = X86ISD::PCMPISTRI;
12535       X86CC = X86::COND_S;
12536       break;
12537     case Intrinsic::x86_sse42_pcmpestris128:
12538       Opcode = X86ISD::PCMPESTRI;
12539       X86CC = X86::COND_S;
12540       break;
12541     case Intrinsic::x86_sse42_pcmpistriz128:
12542       Opcode = X86ISD::PCMPISTRI;
12543       X86CC = X86::COND_E;
12544       break;
12545     case Intrinsic::x86_sse42_pcmpestriz128:
12546       Opcode = X86ISD::PCMPESTRI;
12547       X86CC = X86::COND_E;
12548       break;
12549     }
12550     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12551     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12552     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12553     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12554                                 DAG.getConstant(X86CC, MVT::i8),
12555                                 SDValue(PCMP.getNode(), 1));
12556     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12557   }
12558
12559   case Intrinsic::x86_sse42_pcmpistri128:
12560   case Intrinsic::x86_sse42_pcmpestri128: {
12561     unsigned Opcode;
12562     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12563       Opcode = X86ISD::PCMPISTRI;
12564     else
12565       Opcode = X86ISD::PCMPESTRI;
12566
12567     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12568     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12569     return DAG.getNode(Opcode, dl, VTs, NewOps);
12570   }
12571   case Intrinsic::x86_fma_vfmadd_ps:
12572   case Intrinsic::x86_fma_vfmadd_pd:
12573   case Intrinsic::x86_fma_vfmsub_ps:
12574   case Intrinsic::x86_fma_vfmsub_pd:
12575   case Intrinsic::x86_fma_vfnmadd_ps:
12576   case Intrinsic::x86_fma_vfnmadd_pd:
12577   case Intrinsic::x86_fma_vfnmsub_ps:
12578   case Intrinsic::x86_fma_vfnmsub_pd:
12579   case Intrinsic::x86_fma_vfmaddsub_ps:
12580   case Intrinsic::x86_fma_vfmaddsub_pd:
12581   case Intrinsic::x86_fma_vfmsubadd_ps:
12582   case Intrinsic::x86_fma_vfmsubadd_pd:
12583   case Intrinsic::x86_fma_vfmadd_ps_256:
12584   case Intrinsic::x86_fma_vfmadd_pd_256:
12585   case Intrinsic::x86_fma_vfmsub_ps_256:
12586   case Intrinsic::x86_fma_vfmsub_pd_256:
12587   case Intrinsic::x86_fma_vfnmadd_ps_256:
12588   case Intrinsic::x86_fma_vfnmadd_pd_256:
12589   case Intrinsic::x86_fma_vfnmsub_ps_256:
12590   case Intrinsic::x86_fma_vfnmsub_pd_256:
12591   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12592   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12593   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12594   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12595   case Intrinsic::x86_fma_vfmadd_ps_512:
12596   case Intrinsic::x86_fma_vfmadd_pd_512:
12597   case Intrinsic::x86_fma_vfmsub_ps_512:
12598   case Intrinsic::x86_fma_vfmsub_pd_512:
12599   case Intrinsic::x86_fma_vfnmadd_ps_512:
12600   case Intrinsic::x86_fma_vfnmadd_pd_512:
12601   case Intrinsic::x86_fma_vfnmsub_ps_512:
12602   case Intrinsic::x86_fma_vfnmsub_pd_512:
12603   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12604   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12605   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12606   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12607     unsigned Opc;
12608     switch (IntNo) {
12609     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12610     case Intrinsic::x86_fma_vfmadd_ps:
12611     case Intrinsic::x86_fma_vfmadd_pd:
12612     case Intrinsic::x86_fma_vfmadd_ps_256:
12613     case Intrinsic::x86_fma_vfmadd_pd_256:
12614     case Intrinsic::x86_fma_vfmadd_ps_512:
12615     case Intrinsic::x86_fma_vfmadd_pd_512:
12616       Opc = X86ISD::FMADD;
12617       break;
12618     case Intrinsic::x86_fma_vfmsub_ps:
12619     case Intrinsic::x86_fma_vfmsub_pd:
12620     case Intrinsic::x86_fma_vfmsub_ps_256:
12621     case Intrinsic::x86_fma_vfmsub_pd_256:
12622     case Intrinsic::x86_fma_vfmsub_ps_512:
12623     case Intrinsic::x86_fma_vfmsub_pd_512:
12624       Opc = X86ISD::FMSUB;
12625       break;
12626     case Intrinsic::x86_fma_vfnmadd_ps:
12627     case Intrinsic::x86_fma_vfnmadd_pd:
12628     case Intrinsic::x86_fma_vfnmadd_ps_256:
12629     case Intrinsic::x86_fma_vfnmadd_pd_256:
12630     case Intrinsic::x86_fma_vfnmadd_ps_512:
12631     case Intrinsic::x86_fma_vfnmadd_pd_512:
12632       Opc = X86ISD::FNMADD;
12633       break;
12634     case Intrinsic::x86_fma_vfnmsub_ps:
12635     case Intrinsic::x86_fma_vfnmsub_pd:
12636     case Intrinsic::x86_fma_vfnmsub_ps_256:
12637     case Intrinsic::x86_fma_vfnmsub_pd_256:
12638     case Intrinsic::x86_fma_vfnmsub_ps_512:
12639     case Intrinsic::x86_fma_vfnmsub_pd_512:
12640       Opc = X86ISD::FNMSUB;
12641       break;
12642     case Intrinsic::x86_fma_vfmaddsub_ps:
12643     case Intrinsic::x86_fma_vfmaddsub_pd:
12644     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12645     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12646     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12647     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12648       Opc = X86ISD::FMADDSUB;
12649       break;
12650     case Intrinsic::x86_fma_vfmsubadd_ps:
12651     case Intrinsic::x86_fma_vfmsubadd_pd:
12652     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12653     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12654     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12655     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12656       Opc = X86ISD::FMSUBADD;
12657       break;
12658     }
12659
12660     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12661                        Op.getOperand(2), Op.getOperand(3));
12662   }
12663   }
12664 }
12665
12666 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12667                               SDValue Src, SDValue Mask, SDValue Base,
12668                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12669                               const X86Subtarget * Subtarget) {
12670   SDLoc dl(Op);
12671   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12672   assert(C && "Invalid scale type");
12673   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12674   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12675                              Index.getSimpleValueType().getVectorNumElements());
12676   SDValue MaskInReg;
12677   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12678   if (MaskC)
12679     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12680   else
12681     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12682   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12683   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12684   SDValue Segment = DAG.getRegister(0, MVT::i32);
12685   if (Src.getOpcode() == ISD::UNDEF)
12686     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12687   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12688   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12689   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12690   return DAG.getMergeValues(RetOps, dl);
12691 }
12692
12693 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12694                                SDValue Src, SDValue Mask, SDValue Base,
12695                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12696   SDLoc dl(Op);
12697   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12698   assert(C && "Invalid scale type");
12699   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12700   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12701   SDValue Segment = DAG.getRegister(0, MVT::i32);
12702   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12703                              Index.getSimpleValueType().getVectorNumElements());
12704   SDValue MaskInReg;
12705   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12706   if (MaskC)
12707     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12708   else
12709     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12710   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12711   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12712   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12713   return SDValue(Res, 1);
12714 }
12715
12716 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12717                                SDValue Mask, SDValue Base, SDValue Index,
12718                                SDValue ScaleOp, SDValue Chain) {
12719   SDLoc dl(Op);
12720   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12721   assert(C && "Invalid scale type");
12722   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12723   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12724   SDValue Segment = DAG.getRegister(0, MVT::i32);
12725   EVT MaskVT =
12726     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12727   SDValue MaskInReg;
12728   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12729   if (MaskC)
12730     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12731   else
12732     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12733   //SDVTList VTs = DAG.getVTList(MVT::Other);
12734   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12735   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12736   return SDValue(Res, 0);
12737 }
12738
12739 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12740 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12741 // also used to custom lower READCYCLECOUNTER nodes.
12742 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12743                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12744                               SmallVectorImpl<SDValue> &Results) {
12745   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12746   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12747   SDValue LO, HI;
12748
12749   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12750   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12751   // and the EAX register is loaded with the low-order 32 bits.
12752   if (Subtarget->is64Bit()) {
12753     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12754     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12755                             LO.getValue(2));
12756   } else {
12757     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12758     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12759                             LO.getValue(2));
12760   }
12761   SDValue Chain = HI.getValue(1);
12762
12763   if (Opcode == X86ISD::RDTSCP_DAG) {
12764     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12765
12766     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12767     // the ECX register. Add 'ecx' explicitly to the chain.
12768     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12769                                      HI.getValue(2));
12770     // Explicitly store the content of ECX at the location passed in input
12771     // to the 'rdtscp' intrinsic.
12772     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12773                          MachinePointerInfo(), false, false, 0);
12774   }
12775
12776   if (Subtarget->is64Bit()) {
12777     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12778     // the EAX register is loaded with the low-order 32 bits.
12779     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12780                               DAG.getConstant(32, MVT::i8));
12781     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12782     Results.push_back(Chain);
12783     return;
12784   }
12785
12786   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12787   SDValue Ops[] = { LO, HI };
12788   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12789   Results.push_back(Pair);
12790   Results.push_back(Chain);
12791 }
12792
12793 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12794                                      SelectionDAG &DAG) {
12795   SmallVector<SDValue, 2> Results;
12796   SDLoc DL(Op);
12797   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12798                           Results);
12799   return DAG.getMergeValues(Results, DL);
12800 }
12801
12802 enum IntrinsicType {
12803   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12804 };
12805
12806 struct IntrinsicData {
12807   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12808     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12809   IntrinsicType Type;
12810   unsigned      Opc0;
12811   unsigned      Opc1;
12812 };
12813
12814 std::map < unsigned, IntrinsicData> IntrMap;
12815 static void InitIntinsicsMap() {
12816   static bool Initialized = false;
12817   if (Initialized) 
12818     return;
12819   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12820                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12821   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12822                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12823   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12824                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12825   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12826                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12827   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12828                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12829   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12830                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12831   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12832                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12833   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12834                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12835   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12836                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12837
12838   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12839                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12840   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12841                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12842   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12843                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12844   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12845                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12846   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12847                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12848   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12849                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12850   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
12851                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12852   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
12853                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12854    
12855   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
12856                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12857                                                         X86::VGATHERPF1QPSm)));
12858   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
12859                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12860                                                         X86::VGATHERPF1QPDm)));
12861   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
12862                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12863                                                         X86::VGATHERPF1DPDm)));
12864   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
12865                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12866                                                         X86::VGATHERPF1DPSm)));
12867   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
12868                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12869                                                         X86::VSCATTERPF1QPSm)));
12870   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
12871                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12872                                                         X86::VSCATTERPF1QPDm)));
12873   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
12874                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12875                                                         X86::VSCATTERPF1DPDm)));
12876   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
12877                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12878                                                         X86::VSCATTERPF1DPSm)));
12879   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12880                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12881   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12882                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12883   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12884                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12885   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12886                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12887   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12888                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12889   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12890                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12891   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12892                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
12893   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12894                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
12895   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12896                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
12897   Initialized = true;
12898 }
12899
12900 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12901                                       SelectionDAG &DAG) {
12902   InitIntinsicsMap();
12903   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12904   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12905   if (itr == IntrMap.end())
12906     return SDValue();
12907
12908   SDLoc dl(Op);
12909   IntrinsicData Intr = itr->second;
12910   switch(Intr.Type) {
12911   case RDSEED:
12912   case RDRAND: {
12913     // Emit the node with the right value type.
12914     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12915     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12916
12917     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12918     // Otherwise return the value from Rand, which is always 0, casted to i32.
12919     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12920                       DAG.getConstant(1, Op->getValueType(1)),
12921                       DAG.getConstant(X86::COND_B, MVT::i32),
12922                       SDValue(Result.getNode(), 1) };
12923     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12924                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12925                                   Ops);
12926
12927     // Return { result, isValid, chain }.
12928     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12929                        SDValue(Result.getNode(), 2));
12930   }
12931   case GATHER: {
12932   //gather(v1, mask, index, base, scale);
12933     SDValue Chain = Op.getOperand(0);
12934     SDValue Src   = Op.getOperand(2);
12935     SDValue Base  = Op.getOperand(3);
12936     SDValue Index = Op.getOperand(4);
12937     SDValue Mask  = Op.getOperand(5);
12938     SDValue Scale = Op.getOperand(6);
12939     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12940                           Subtarget);
12941   }
12942   case SCATTER: {
12943   //scatter(base, mask, index, v1, scale);
12944     SDValue Chain = Op.getOperand(0);
12945     SDValue Base  = Op.getOperand(2);
12946     SDValue Mask  = Op.getOperand(3);
12947     SDValue Index = Op.getOperand(4);
12948     SDValue Src   = Op.getOperand(5);
12949     SDValue Scale = Op.getOperand(6);
12950     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12951   }
12952   case PREFETCH: {
12953     SDValue Hint = Op.getOperand(6);
12954     unsigned HintVal;
12955     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
12956         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12957       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12958     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12959     SDValue Chain = Op.getOperand(0);
12960     SDValue Mask  = Op.getOperand(2);
12961     SDValue Index = Op.getOperand(3);
12962     SDValue Base  = Op.getOperand(4);
12963     SDValue Scale = Op.getOperand(5);
12964     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12965   }
12966   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12967   case RDTSC: {
12968     SmallVector<SDValue, 2> Results;
12969     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12970     return DAG.getMergeValues(Results, dl);
12971   }
12972   // XTEST intrinsics.
12973   case XTEST: {
12974     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12975     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12976     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12977                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12978                                 InTrans);
12979     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12980     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12981                        Ret, SDValue(InTrans.getNode(), 1));
12982   }
12983   }
12984   llvm_unreachable("Unknown Intrinsic Type");
12985 }
12986
12987 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12988                                            SelectionDAG &DAG) const {
12989   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12990   MFI->setReturnAddressIsTaken(true);
12991
12992   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12993     return SDValue();
12994
12995   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12996   SDLoc dl(Op);
12997   EVT PtrVT = getPointerTy();
12998
12999   if (Depth > 0) {
13000     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13001     const X86RegisterInfo *RegInfo =
13002       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13003     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13004     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13005                        DAG.getNode(ISD::ADD, dl, PtrVT,
13006                                    FrameAddr, Offset),
13007                        MachinePointerInfo(), false, false, false, 0);
13008   }
13009
13010   // Just load the return address.
13011   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13012   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13013                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13014 }
13015
13016 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13017   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13018   MFI->setFrameAddressIsTaken(true);
13019
13020   EVT VT = Op.getValueType();
13021   SDLoc dl(Op);  // FIXME probably not meaningful
13022   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13023   const X86RegisterInfo *RegInfo =
13024     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13025   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13026   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13027           (FrameReg == X86::EBP && VT == MVT::i32)) &&
13028          "Invalid Frame Register!");
13029   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13030   while (Depth--)
13031     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13032                             MachinePointerInfo(),
13033                             false, false, false, 0);
13034   return FrameAddr;
13035 }
13036
13037 // FIXME? Maybe this could be a TableGen attribute on some registers and
13038 // this table could be generated automatically from RegInfo.
13039 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13040                                               EVT VT) const {
13041   unsigned Reg = StringSwitch<unsigned>(RegName)
13042                        .Case("esp", X86::ESP)
13043                        .Case("rsp", X86::RSP)
13044                        .Default(0);
13045   if (Reg)
13046     return Reg;
13047   report_fatal_error("Invalid register name global variable");
13048 }
13049
13050 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13051                                                      SelectionDAG &DAG) const {
13052   const X86RegisterInfo *RegInfo =
13053     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13054   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13055 }
13056
13057 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13058   SDValue Chain     = Op.getOperand(0);
13059   SDValue Offset    = Op.getOperand(1);
13060   SDValue Handler   = Op.getOperand(2);
13061   SDLoc dl      (Op);
13062
13063   EVT PtrVT = getPointerTy();
13064   const X86RegisterInfo *RegInfo =
13065     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13066   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13067   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13068           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13069          "Invalid Frame Register!");
13070   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13071   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13072
13073   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13074                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13075   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13076   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13077                        false, false, 0);
13078   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13079
13080   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13081                      DAG.getRegister(StoreAddrReg, PtrVT));
13082 }
13083
13084 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13085                                                SelectionDAG &DAG) const {
13086   SDLoc DL(Op);
13087   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13088                      DAG.getVTList(MVT::i32, MVT::Other),
13089                      Op.getOperand(0), Op.getOperand(1));
13090 }
13091
13092 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13093                                                 SelectionDAG &DAG) const {
13094   SDLoc DL(Op);
13095   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13096                      Op.getOperand(0), Op.getOperand(1));
13097 }
13098
13099 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13100   return Op.getOperand(0);
13101 }
13102
13103 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13104                                                 SelectionDAG &DAG) const {
13105   SDValue Root = Op.getOperand(0);
13106   SDValue Trmp = Op.getOperand(1); // trampoline
13107   SDValue FPtr = Op.getOperand(2); // nested function
13108   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13109   SDLoc dl (Op);
13110
13111   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13112   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13113
13114   if (Subtarget->is64Bit()) {
13115     SDValue OutChains[6];
13116
13117     // Large code-model.
13118     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
13119     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13120
13121     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13122     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13123
13124     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13125
13126     // Load the pointer to the nested function into R11.
13127     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13128     SDValue Addr = Trmp;
13129     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13130                                 Addr, MachinePointerInfo(TrmpAddr),
13131                                 false, false, 0);
13132
13133     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13134                        DAG.getConstant(2, MVT::i64));
13135     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13136                                 MachinePointerInfo(TrmpAddr, 2),
13137                                 false, false, 2);
13138
13139     // Load the 'nest' parameter value into R10.
13140     // R10 is specified in X86CallingConv.td
13141     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13142     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13143                        DAG.getConstant(10, MVT::i64));
13144     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13145                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13146                                 false, false, 0);
13147
13148     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13149                        DAG.getConstant(12, MVT::i64));
13150     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13151                                 MachinePointerInfo(TrmpAddr, 12),
13152                                 false, false, 2);
13153
13154     // Jump to the nested function.
13155     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13156     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13157                        DAG.getConstant(20, MVT::i64));
13158     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13159                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13160                                 false, false, 0);
13161
13162     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13163     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13164                        DAG.getConstant(22, MVT::i64));
13165     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13166                                 MachinePointerInfo(TrmpAddr, 22),
13167                                 false, false, 0);
13168
13169     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13170   } else {
13171     const Function *Func =
13172       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13173     CallingConv::ID CC = Func->getCallingConv();
13174     unsigned NestReg;
13175
13176     switch (CC) {
13177     default:
13178       llvm_unreachable("Unsupported calling convention");
13179     case CallingConv::C:
13180     case CallingConv::X86_StdCall: {
13181       // Pass 'nest' parameter in ECX.
13182       // Must be kept in sync with X86CallingConv.td
13183       NestReg = X86::ECX;
13184
13185       // Check that ECX wasn't needed by an 'inreg' parameter.
13186       FunctionType *FTy = Func->getFunctionType();
13187       const AttributeSet &Attrs = Func->getAttributes();
13188
13189       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13190         unsigned InRegCount = 0;
13191         unsigned Idx = 1;
13192
13193         for (FunctionType::param_iterator I = FTy->param_begin(),
13194              E = FTy->param_end(); I != E; ++I, ++Idx)
13195           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13196             // FIXME: should only count parameters that are lowered to integers.
13197             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13198
13199         if (InRegCount > 2) {
13200           report_fatal_error("Nest register in use - reduce number of inreg"
13201                              " parameters!");
13202         }
13203       }
13204       break;
13205     }
13206     case CallingConv::X86_FastCall:
13207     case CallingConv::X86_ThisCall:
13208     case CallingConv::Fast:
13209       // Pass 'nest' parameter in EAX.
13210       // Must be kept in sync with X86CallingConv.td
13211       NestReg = X86::EAX;
13212       break;
13213     }
13214
13215     SDValue OutChains[4];
13216     SDValue Addr, Disp;
13217
13218     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13219                        DAG.getConstant(10, MVT::i32));
13220     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13221
13222     // This is storing the opcode for MOV32ri.
13223     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13224     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13225     OutChains[0] = DAG.getStore(Root, dl,
13226                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13227                                 Trmp, MachinePointerInfo(TrmpAddr),
13228                                 false, false, 0);
13229
13230     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13231                        DAG.getConstant(1, MVT::i32));
13232     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13233                                 MachinePointerInfo(TrmpAddr, 1),
13234                                 false, false, 1);
13235
13236     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13237     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13238                        DAG.getConstant(5, MVT::i32));
13239     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13240                                 MachinePointerInfo(TrmpAddr, 5),
13241                                 false, false, 1);
13242
13243     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13244                        DAG.getConstant(6, MVT::i32));
13245     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13246                                 MachinePointerInfo(TrmpAddr, 6),
13247                                 false, false, 1);
13248
13249     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13250   }
13251 }
13252
13253 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13254                                             SelectionDAG &DAG) const {
13255   /*
13256    The rounding mode is in bits 11:10 of FPSR, and has the following
13257    settings:
13258      00 Round to nearest
13259      01 Round to -inf
13260      10 Round to +inf
13261      11 Round to 0
13262
13263   FLT_ROUNDS, on the other hand, expects the following:
13264     -1 Undefined
13265      0 Round to 0
13266      1 Round to nearest
13267      2 Round to +inf
13268      3 Round to -inf
13269
13270   To perform the conversion, we do:
13271     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13272   */
13273
13274   MachineFunction &MF = DAG.getMachineFunction();
13275   const TargetMachine &TM = MF.getTarget();
13276   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13277   unsigned StackAlignment = TFI.getStackAlignment();
13278   MVT VT = Op.getSimpleValueType();
13279   SDLoc DL(Op);
13280
13281   // Save FP Control Word to stack slot
13282   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13283   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13284
13285   MachineMemOperand *MMO =
13286    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13287                            MachineMemOperand::MOStore, 2, 2);
13288
13289   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13290   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13291                                           DAG.getVTList(MVT::Other),
13292                                           Ops, MVT::i16, MMO);
13293
13294   // Load FP Control Word from stack slot
13295   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13296                             MachinePointerInfo(), false, false, false, 0);
13297
13298   // Transform as necessary
13299   SDValue CWD1 =
13300     DAG.getNode(ISD::SRL, DL, MVT::i16,
13301                 DAG.getNode(ISD::AND, DL, MVT::i16,
13302                             CWD, DAG.getConstant(0x800, MVT::i16)),
13303                 DAG.getConstant(11, MVT::i8));
13304   SDValue CWD2 =
13305     DAG.getNode(ISD::SRL, DL, MVT::i16,
13306                 DAG.getNode(ISD::AND, DL, MVT::i16,
13307                             CWD, DAG.getConstant(0x400, MVT::i16)),
13308                 DAG.getConstant(9, MVT::i8));
13309
13310   SDValue RetVal =
13311     DAG.getNode(ISD::AND, DL, MVT::i16,
13312                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13313                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13314                             DAG.getConstant(1, MVT::i16)),
13315                 DAG.getConstant(3, MVT::i16));
13316
13317   return DAG.getNode((VT.getSizeInBits() < 16 ?
13318                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13319 }
13320
13321 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13322   MVT VT = Op.getSimpleValueType();
13323   EVT OpVT = VT;
13324   unsigned NumBits = VT.getSizeInBits();
13325   SDLoc dl(Op);
13326
13327   Op = Op.getOperand(0);
13328   if (VT == MVT::i8) {
13329     // Zero extend to i32 since there is not an i8 bsr.
13330     OpVT = MVT::i32;
13331     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13332   }
13333
13334   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13335   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13336   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13337
13338   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13339   SDValue Ops[] = {
13340     Op,
13341     DAG.getConstant(NumBits+NumBits-1, OpVT),
13342     DAG.getConstant(X86::COND_E, MVT::i8),
13343     Op.getValue(1)
13344   };
13345   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13346
13347   // Finally xor with NumBits-1.
13348   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13349
13350   if (VT == MVT::i8)
13351     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13352   return Op;
13353 }
13354
13355 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13356   MVT VT = Op.getSimpleValueType();
13357   EVT OpVT = VT;
13358   unsigned NumBits = VT.getSizeInBits();
13359   SDLoc dl(Op);
13360
13361   Op = Op.getOperand(0);
13362   if (VT == MVT::i8) {
13363     // Zero extend to i32 since there is not an i8 bsr.
13364     OpVT = MVT::i32;
13365     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13366   }
13367
13368   // Issue a bsr (scan bits in reverse).
13369   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13370   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13371
13372   // And xor with NumBits-1.
13373   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13374
13375   if (VT == MVT::i8)
13376     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13377   return Op;
13378 }
13379
13380 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13381   MVT VT = Op.getSimpleValueType();
13382   unsigned NumBits = VT.getSizeInBits();
13383   SDLoc dl(Op);
13384   Op = Op.getOperand(0);
13385
13386   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13387   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13388   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13389
13390   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13391   SDValue Ops[] = {
13392     Op,
13393     DAG.getConstant(NumBits, VT),
13394     DAG.getConstant(X86::COND_E, MVT::i8),
13395     Op.getValue(1)
13396   };
13397   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13398 }
13399
13400 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13401 // ones, and then concatenate the result back.
13402 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13403   MVT VT = Op.getSimpleValueType();
13404
13405   assert(VT.is256BitVector() && VT.isInteger() &&
13406          "Unsupported value type for operation");
13407
13408   unsigned NumElems = VT.getVectorNumElements();
13409   SDLoc dl(Op);
13410
13411   // Extract the LHS vectors
13412   SDValue LHS = Op.getOperand(0);
13413   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13414   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13415
13416   // Extract the RHS vectors
13417   SDValue RHS = Op.getOperand(1);
13418   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13419   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13420
13421   MVT EltVT = VT.getVectorElementType();
13422   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13423
13424   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13425                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13426                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13427 }
13428
13429 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13430   assert(Op.getSimpleValueType().is256BitVector() &&
13431          Op.getSimpleValueType().isInteger() &&
13432          "Only handle AVX 256-bit vector integer operation");
13433   return Lower256IntArith(Op, DAG);
13434 }
13435
13436 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13437   assert(Op.getSimpleValueType().is256BitVector() &&
13438          Op.getSimpleValueType().isInteger() &&
13439          "Only handle AVX 256-bit vector integer operation");
13440   return Lower256IntArith(Op, DAG);
13441 }
13442
13443 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13444                         SelectionDAG &DAG) {
13445   SDLoc dl(Op);
13446   MVT VT = Op.getSimpleValueType();
13447
13448   // Decompose 256-bit ops into smaller 128-bit ops.
13449   if (VT.is256BitVector() && !Subtarget->hasInt256())
13450     return Lower256IntArith(Op, DAG);
13451
13452   SDValue A = Op.getOperand(0);
13453   SDValue B = Op.getOperand(1);
13454
13455   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13456   if (VT == MVT::v4i32) {
13457     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13458            "Should not custom lower when pmuldq is available!");
13459
13460     // Extract the odd parts.
13461     static const int UnpackMask[] = { 1, -1, 3, -1 };
13462     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13463     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13464
13465     // Multiply the even parts.
13466     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13467     // Now multiply odd parts.
13468     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13469
13470     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13471     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13472
13473     // Merge the two vectors back together with a shuffle. This expands into 2
13474     // shuffles.
13475     static const int ShufMask[] = { 0, 4, 2, 6 };
13476     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13477   }
13478
13479   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13480          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13481
13482   //  Ahi = psrlqi(a, 32);
13483   //  Bhi = psrlqi(b, 32);
13484   //
13485   //  AloBlo = pmuludq(a, b);
13486   //  AloBhi = pmuludq(a, Bhi);
13487   //  AhiBlo = pmuludq(Ahi, b);
13488
13489   //  AloBhi = psllqi(AloBhi, 32);
13490   //  AhiBlo = psllqi(AhiBlo, 32);
13491   //  return AloBlo + AloBhi + AhiBlo;
13492
13493   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13494   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13495
13496   // Bit cast to 32-bit vectors for MULUDQ
13497   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13498                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13499   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13500   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13501   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13502   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13503
13504   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13505   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13506   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13507
13508   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13509   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13510
13511   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13512   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13513 }
13514
13515 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13516   assert(Subtarget->isTargetWin64() && "Unexpected target");
13517   EVT VT = Op.getValueType();
13518   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13519          "Unexpected return type for lowering");
13520
13521   RTLIB::Libcall LC;
13522   bool isSigned;
13523   switch (Op->getOpcode()) {
13524   default: llvm_unreachable("Unexpected request for libcall!");
13525   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13526   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13527   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13528   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13529   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13530   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13531   }
13532
13533   SDLoc dl(Op);
13534   SDValue InChain = DAG.getEntryNode();
13535
13536   TargetLowering::ArgListTy Args;
13537   TargetLowering::ArgListEntry Entry;
13538   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13539     EVT ArgVT = Op->getOperand(i).getValueType();
13540     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13541            "Unexpected argument type for lowering");
13542     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13543     Entry.Node = StackPtr;
13544     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13545                            false, false, 16);
13546     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13547     Entry.Ty = PointerType::get(ArgTy,0);
13548     Entry.isSExt = false;
13549     Entry.isZExt = false;
13550     Args.push_back(Entry);
13551   }
13552
13553   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13554                                          getPointerTy());
13555
13556   TargetLowering::CallLoweringInfo CLI(DAG);
13557   CLI.setDebugLoc(dl).setChain(InChain)
13558     .setCallee(getLibcallCallingConv(LC),
13559                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13560                Callee, &Args, 0)
13561     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13562
13563   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13564   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13565 }
13566
13567 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13568                              SelectionDAG &DAG) {
13569   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13570   EVT VT = Op0.getValueType();
13571   SDLoc dl(Op);
13572
13573   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13574          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13575
13576   // Get the high parts.
13577   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13578   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13579   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13580
13581   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13582   // ints.
13583   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13584   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13585   unsigned Opcode =
13586       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13587   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13588                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13589   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13590                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13591
13592   // Shuffle it back into the right order.
13593   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13594   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13595   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13596   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13597
13598   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13599   // unsigned multiply.
13600   if (IsSigned && !Subtarget->hasSSE41()) {
13601     SDValue ShAmt =
13602         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13603     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13604                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13605     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13606                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13607
13608     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13609     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13610   }
13611
13612   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13613 }
13614
13615 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13616                                          const X86Subtarget *Subtarget) {
13617   MVT VT = Op.getSimpleValueType();
13618   SDLoc dl(Op);
13619   SDValue R = Op.getOperand(0);
13620   SDValue Amt = Op.getOperand(1);
13621
13622   // Optimize shl/srl/sra with constant shift amount.
13623   if (isSplatVector(Amt.getNode())) {
13624     SDValue SclrAmt = Amt->getOperand(0);
13625     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13626       uint64_t ShiftAmt = C->getZExtValue();
13627
13628       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13629           (Subtarget->hasInt256() &&
13630            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13631           (Subtarget->hasAVX512() &&
13632            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13633         if (Op.getOpcode() == ISD::SHL)
13634           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13635                                             DAG);
13636         if (Op.getOpcode() == ISD::SRL)
13637           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13638                                             DAG);
13639         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13640           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13641                                             DAG);
13642       }
13643
13644       if (VT == MVT::v16i8) {
13645         if (Op.getOpcode() == ISD::SHL) {
13646           // Make a large shift.
13647           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13648                                                    MVT::v8i16, R, ShiftAmt,
13649                                                    DAG);
13650           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13651           // Zero out the rightmost bits.
13652           SmallVector<SDValue, 16> V(16,
13653                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13654                                                      MVT::i8));
13655           return DAG.getNode(ISD::AND, dl, VT, SHL,
13656                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13657         }
13658         if (Op.getOpcode() == ISD::SRL) {
13659           // Make a large shift.
13660           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13661                                                    MVT::v8i16, R, ShiftAmt,
13662                                                    DAG);
13663           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13664           // Zero out the leftmost bits.
13665           SmallVector<SDValue, 16> V(16,
13666                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13667                                                      MVT::i8));
13668           return DAG.getNode(ISD::AND, dl, VT, SRL,
13669                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13670         }
13671         if (Op.getOpcode() == ISD::SRA) {
13672           if (ShiftAmt == 7) {
13673             // R s>> 7  ===  R s< 0
13674             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13675             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13676           }
13677
13678           // R s>> a === ((R u>> a) ^ m) - m
13679           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13680           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13681                                                          MVT::i8));
13682           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13683           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13684           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13685           return Res;
13686         }
13687         llvm_unreachable("Unknown shift opcode.");
13688       }
13689
13690       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13691         if (Op.getOpcode() == ISD::SHL) {
13692           // Make a large shift.
13693           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13694                                                    MVT::v16i16, R, ShiftAmt,
13695                                                    DAG);
13696           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13697           // Zero out the rightmost bits.
13698           SmallVector<SDValue, 32> V(32,
13699                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13700                                                      MVT::i8));
13701           return DAG.getNode(ISD::AND, dl, VT, SHL,
13702                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13703         }
13704         if (Op.getOpcode() == ISD::SRL) {
13705           // Make a large shift.
13706           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13707                                                    MVT::v16i16, R, ShiftAmt,
13708                                                    DAG);
13709           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13710           // Zero out the leftmost bits.
13711           SmallVector<SDValue, 32> V(32,
13712                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13713                                                      MVT::i8));
13714           return DAG.getNode(ISD::AND, dl, VT, SRL,
13715                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13716         }
13717         if (Op.getOpcode() == ISD::SRA) {
13718           if (ShiftAmt == 7) {
13719             // R s>> 7  ===  R s< 0
13720             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13721             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13722           }
13723
13724           // R s>> a === ((R u>> a) ^ m) - m
13725           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13726           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13727                                                          MVT::i8));
13728           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13729           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13730           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13731           return Res;
13732         }
13733         llvm_unreachable("Unknown shift opcode.");
13734       }
13735     }
13736   }
13737
13738   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13739   if (!Subtarget->is64Bit() &&
13740       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13741       Amt.getOpcode() == ISD::BITCAST &&
13742       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13743     Amt = Amt.getOperand(0);
13744     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13745                      VT.getVectorNumElements();
13746     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13747     uint64_t ShiftAmt = 0;
13748     for (unsigned i = 0; i != Ratio; ++i) {
13749       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13750       if (!C)
13751         return SDValue();
13752       // 6 == Log2(64)
13753       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13754     }
13755     // Check remaining shift amounts.
13756     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13757       uint64_t ShAmt = 0;
13758       for (unsigned j = 0; j != Ratio; ++j) {
13759         ConstantSDNode *C =
13760           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13761         if (!C)
13762           return SDValue();
13763         // 6 == Log2(64)
13764         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13765       }
13766       if (ShAmt != ShiftAmt)
13767         return SDValue();
13768     }
13769     switch (Op.getOpcode()) {
13770     default:
13771       llvm_unreachable("Unknown shift opcode!");
13772     case ISD::SHL:
13773       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13774                                         DAG);
13775     case ISD::SRL:
13776       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13777                                         DAG);
13778     case ISD::SRA:
13779       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13780                                         DAG);
13781     }
13782   }
13783
13784   return SDValue();
13785 }
13786
13787 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13788                                         const X86Subtarget* Subtarget) {
13789   MVT VT = Op.getSimpleValueType();
13790   SDLoc dl(Op);
13791   SDValue R = Op.getOperand(0);
13792   SDValue Amt = Op.getOperand(1);
13793
13794   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13795       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13796       (Subtarget->hasInt256() &&
13797        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13798         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13799        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13800     SDValue BaseShAmt;
13801     EVT EltVT = VT.getVectorElementType();
13802
13803     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13804       unsigned NumElts = VT.getVectorNumElements();
13805       unsigned i, j;
13806       for (i = 0; i != NumElts; ++i) {
13807         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13808           continue;
13809         break;
13810       }
13811       for (j = i; j != NumElts; ++j) {
13812         SDValue Arg = Amt.getOperand(j);
13813         if (Arg.getOpcode() == ISD::UNDEF) continue;
13814         if (Arg != Amt.getOperand(i))
13815           break;
13816       }
13817       if (i != NumElts && j == NumElts)
13818         BaseShAmt = Amt.getOperand(i);
13819     } else {
13820       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13821         Amt = Amt.getOperand(0);
13822       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13823                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13824         SDValue InVec = Amt.getOperand(0);
13825         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13826           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13827           unsigned i = 0;
13828           for (; i != NumElts; ++i) {
13829             SDValue Arg = InVec.getOperand(i);
13830             if (Arg.getOpcode() == ISD::UNDEF) continue;
13831             BaseShAmt = Arg;
13832             break;
13833           }
13834         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13835            if (ConstantSDNode *C =
13836                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13837              unsigned SplatIdx =
13838                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13839              if (C->getZExtValue() == SplatIdx)
13840                BaseShAmt = InVec.getOperand(1);
13841            }
13842         }
13843         if (!BaseShAmt.getNode())
13844           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13845                                   DAG.getIntPtrConstant(0));
13846       }
13847     }
13848
13849     if (BaseShAmt.getNode()) {
13850       if (EltVT.bitsGT(MVT::i32))
13851         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13852       else if (EltVT.bitsLT(MVT::i32))
13853         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13854
13855       switch (Op.getOpcode()) {
13856       default:
13857         llvm_unreachable("Unknown shift opcode!");
13858       case ISD::SHL:
13859         switch (VT.SimpleTy) {
13860         default: return SDValue();
13861         case MVT::v2i64:
13862         case MVT::v4i32:
13863         case MVT::v8i16:
13864         case MVT::v4i64:
13865         case MVT::v8i32:
13866         case MVT::v16i16:
13867         case MVT::v16i32:
13868         case MVT::v8i64:
13869           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13870         }
13871       case ISD::SRA:
13872         switch (VT.SimpleTy) {
13873         default: return SDValue();
13874         case MVT::v4i32:
13875         case MVT::v8i16:
13876         case MVT::v8i32:
13877         case MVT::v16i16:
13878         case MVT::v16i32:
13879         case MVT::v8i64:
13880           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13881         }
13882       case ISD::SRL:
13883         switch (VT.SimpleTy) {
13884         default: return SDValue();
13885         case MVT::v2i64:
13886         case MVT::v4i32:
13887         case MVT::v8i16:
13888         case MVT::v4i64:
13889         case MVT::v8i32:
13890         case MVT::v16i16:
13891         case MVT::v16i32:
13892         case MVT::v8i64:
13893           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13894         }
13895       }
13896     }
13897   }
13898
13899   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13900   if (!Subtarget->is64Bit() &&
13901       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13902       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13903       Amt.getOpcode() == ISD::BITCAST &&
13904       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13905     Amt = Amt.getOperand(0);
13906     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13907                      VT.getVectorNumElements();
13908     std::vector<SDValue> Vals(Ratio);
13909     for (unsigned i = 0; i != Ratio; ++i)
13910       Vals[i] = Amt.getOperand(i);
13911     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13912       for (unsigned j = 0; j != Ratio; ++j)
13913         if (Vals[j] != Amt.getOperand(i + j))
13914           return SDValue();
13915     }
13916     switch (Op.getOpcode()) {
13917     default:
13918       llvm_unreachable("Unknown shift opcode!");
13919     case ISD::SHL:
13920       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13921     case ISD::SRL:
13922       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13923     case ISD::SRA:
13924       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13925     }
13926   }
13927
13928   return SDValue();
13929 }
13930
13931 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13932                           SelectionDAG &DAG) {
13933
13934   MVT VT = Op.getSimpleValueType();
13935   SDLoc dl(Op);
13936   SDValue R = Op.getOperand(0);
13937   SDValue Amt = Op.getOperand(1);
13938   SDValue V;
13939
13940   if (!Subtarget->hasSSE2())
13941     return SDValue();
13942
13943   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13944   if (V.getNode())
13945     return V;
13946
13947   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13948   if (V.getNode())
13949       return V;
13950
13951   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13952     return Op;
13953   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13954   if (Subtarget->hasInt256()) {
13955     if (Op.getOpcode() == ISD::SRL &&
13956         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13957          VT == MVT::v4i64 || VT == MVT::v8i32))
13958       return Op;
13959     if (Op.getOpcode() == ISD::SHL &&
13960         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13961          VT == MVT::v4i64 || VT == MVT::v8i32))
13962       return Op;
13963     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13964       return Op;
13965   }
13966
13967   // If possible, lower this packed shift into a vector multiply instead of
13968   // expanding it into a sequence of scalar shifts.
13969   // Do this only if the vector shift count is a constant build_vector.
13970   if (Op.getOpcode() == ISD::SHL && 
13971       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13972        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13973       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13974     SmallVector<SDValue, 8> Elts;
13975     EVT SVT = VT.getScalarType();
13976     unsigned SVTBits = SVT.getSizeInBits();
13977     const APInt &One = APInt(SVTBits, 1);
13978     unsigned NumElems = VT.getVectorNumElements();
13979
13980     for (unsigned i=0; i !=NumElems; ++i) {
13981       SDValue Op = Amt->getOperand(i);
13982       if (Op->getOpcode() == ISD::UNDEF) {
13983         Elts.push_back(Op);
13984         continue;
13985       }
13986
13987       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13988       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13989       uint64_t ShAmt = C.getZExtValue();
13990       if (ShAmt >= SVTBits) {
13991         Elts.push_back(DAG.getUNDEF(SVT));
13992         continue;
13993       }
13994       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13995     }
13996     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13997     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13998   }
13999
14000   // Lower SHL with variable shift amount.
14001   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14002     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14003
14004     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14005     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14006     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14007     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14008   }
14009
14010   // If possible, lower this shift as a sequence of two shifts by
14011   // constant plus a MOVSS/MOVSD instead of scalarizing it.
14012   // Example:
14013   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14014   //
14015   // Could be rewritten as:
14016   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14017   //
14018   // The advantage is that the two shifts from the example would be
14019   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14020   // the vector shift into four scalar shifts plus four pairs of vector
14021   // insert/extract.
14022   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14023       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14024     unsigned TargetOpcode = X86ISD::MOVSS;
14025     bool CanBeSimplified;
14026     // The splat value for the first packed shift (the 'X' from the example).
14027     SDValue Amt1 = Amt->getOperand(0);
14028     // The splat value for the second packed shift (the 'Y' from the example).
14029     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14030                                         Amt->getOperand(2);
14031
14032     // See if it is possible to replace this node with a sequence of
14033     // two shifts followed by a MOVSS/MOVSD
14034     if (VT == MVT::v4i32) {
14035       // Check if it is legal to use a MOVSS.
14036       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14037                         Amt2 == Amt->getOperand(3);
14038       if (!CanBeSimplified) {
14039         // Otherwise, check if we can still simplify this node using a MOVSD.
14040         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14041                           Amt->getOperand(2) == Amt->getOperand(3);
14042         TargetOpcode = X86ISD::MOVSD;
14043         Amt2 = Amt->getOperand(2);
14044       }
14045     } else {
14046       // Do similar checks for the case where the machine value type
14047       // is MVT::v8i16.
14048       CanBeSimplified = Amt1 == Amt->getOperand(1);
14049       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14050         CanBeSimplified = Amt2 == Amt->getOperand(i);
14051
14052       if (!CanBeSimplified) {
14053         TargetOpcode = X86ISD::MOVSD;
14054         CanBeSimplified = true;
14055         Amt2 = Amt->getOperand(4);
14056         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14057           CanBeSimplified = Amt1 == Amt->getOperand(i);
14058         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14059           CanBeSimplified = Amt2 == Amt->getOperand(j);
14060       }
14061     }
14062     
14063     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14064         isa<ConstantSDNode>(Amt2)) {
14065       // Replace this node with two shifts followed by a MOVSS/MOVSD.
14066       EVT CastVT = MVT::v4i32;
14067       SDValue Splat1 = 
14068         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14069       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14070       SDValue Splat2 = 
14071         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14072       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14073       if (TargetOpcode == X86ISD::MOVSD)
14074         CastVT = MVT::v2i64;
14075       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14076       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14077       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14078                                             BitCast1, DAG);
14079       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14080     }
14081   }
14082
14083   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14084     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14085
14086     // a = a << 5;
14087     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14088     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14089
14090     // Turn 'a' into a mask suitable for VSELECT
14091     SDValue VSelM = DAG.getConstant(0x80, VT);
14092     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14093     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14094
14095     SDValue CM1 = DAG.getConstant(0x0f, VT);
14096     SDValue CM2 = DAG.getConstant(0x3f, VT);
14097
14098     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14099     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14100     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14101     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14102     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14103
14104     // a += a
14105     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14106     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14107     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14108
14109     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14110     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14111     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14112     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14113     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14114
14115     // a += a
14116     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14117     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14118     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14119
14120     // return VSELECT(r, r+r, a);
14121     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14122                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14123     return R;
14124   }
14125
14126   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14127   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14128   // solution better.
14129   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14130     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14131     unsigned ExtOpc =
14132         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14133     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14134     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14135     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14136                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14137     }
14138
14139   // Decompose 256-bit shifts into smaller 128-bit shifts.
14140   if (VT.is256BitVector()) {
14141     unsigned NumElems = VT.getVectorNumElements();
14142     MVT EltVT = VT.getVectorElementType();
14143     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14144
14145     // Extract the two vectors
14146     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14147     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14148
14149     // Recreate the shift amount vectors
14150     SDValue Amt1, Amt2;
14151     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14152       // Constant shift amount
14153       SmallVector<SDValue, 4> Amt1Csts;
14154       SmallVector<SDValue, 4> Amt2Csts;
14155       for (unsigned i = 0; i != NumElems/2; ++i)
14156         Amt1Csts.push_back(Amt->getOperand(i));
14157       for (unsigned i = NumElems/2; i != NumElems; ++i)
14158         Amt2Csts.push_back(Amt->getOperand(i));
14159
14160       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14161       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14162     } else {
14163       // Variable shift amount
14164       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14165       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14166     }
14167
14168     // Issue new vector shifts for the smaller types
14169     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14170     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14171
14172     // Concatenate the result back
14173     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14174   }
14175
14176   return SDValue();
14177 }
14178
14179 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14180   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14181   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14182   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14183   // has only one use.
14184   SDNode *N = Op.getNode();
14185   SDValue LHS = N->getOperand(0);
14186   SDValue RHS = N->getOperand(1);
14187   unsigned BaseOp = 0;
14188   unsigned Cond = 0;
14189   SDLoc DL(Op);
14190   switch (Op.getOpcode()) {
14191   default: llvm_unreachable("Unknown ovf instruction!");
14192   case ISD::SADDO:
14193     // A subtract of one will be selected as a INC. Note that INC doesn't
14194     // set CF, so we can't do this for UADDO.
14195     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14196       if (C->isOne()) {
14197         BaseOp = X86ISD::INC;
14198         Cond = X86::COND_O;
14199         break;
14200       }
14201     BaseOp = X86ISD::ADD;
14202     Cond = X86::COND_O;
14203     break;
14204   case ISD::UADDO:
14205     BaseOp = X86ISD::ADD;
14206     Cond = X86::COND_B;
14207     break;
14208   case ISD::SSUBO:
14209     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14210     // set CF, so we can't do this for USUBO.
14211     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14212       if (C->isOne()) {
14213         BaseOp = X86ISD::DEC;
14214         Cond = X86::COND_O;
14215         break;
14216       }
14217     BaseOp = X86ISD::SUB;
14218     Cond = X86::COND_O;
14219     break;
14220   case ISD::USUBO:
14221     BaseOp = X86ISD::SUB;
14222     Cond = X86::COND_B;
14223     break;
14224   case ISD::SMULO:
14225     BaseOp = X86ISD::SMUL;
14226     Cond = X86::COND_O;
14227     break;
14228   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14229     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14230                                  MVT::i32);
14231     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14232
14233     SDValue SetCC =
14234       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14235                   DAG.getConstant(X86::COND_O, MVT::i32),
14236                   SDValue(Sum.getNode(), 2));
14237
14238     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14239   }
14240   }
14241
14242   // Also sets EFLAGS.
14243   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14244   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14245
14246   SDValue SetCC =
14247     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14248                 DAG.getConstant(Cond, MVT::i32),
14249                 SDValue(Sum.getNode(), 1));
14250
14251   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14252 }
14253
14254 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14255                                                   SelectionDAG &DAG) const {
14256   SDLoc dl(Op);
14257   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14258   MVT VT = Op.getSimpleValueType();
14259
14260   if (!Subtarget->hasSSE2() || !VT.isVector())
14261     return SDValue();
14262
14263   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14264                       ExtraVT.getScalarType().getSizeInBits();
14265
14266   switch (VT.SimpleTy) {
14267     default: return SDValue();
14268     case MVT::v8i32:
14269     case MVT::v16i16:
14270       if (!Subtarget->hasFp256())
14271         return SDValue();
14272       if (!Subtarget->hasInt256()) {
14273         // needs to be split
14274         unsigned NumElems = VT.getVectorNumElements();
14275
14276         // Extract the LHS vectors
14277         SDValue LHS = Op.getOperand(0);
14278         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14279         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14280
14281         MVT EltVT = VT.getVectorElementType();
14282         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14283
14284         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14285         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14286         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14287                                    ExtraNumElems/2);
14288         SDValue Extra = DAG.getValueType(ExtraVT);
14289
14290         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14291         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14292
14293         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14294       }
14295       // fall through
14296     case MVT::v4i32:
14297     case MVT::v8i16: {
14298       SDValue Op0 = Op.getOperand(0);
14299       SDValue Op00 = Op0.getOperand(0);
14300       SDValue Tmp1;
14301       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14302       if (Op0.getOpcode() == ISD::BITCAST &&
14303           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14304         // (sext (vzext x)) -> (vsext x)
14305         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14306         if (Tmp1.getNode()) {
14307           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14308           // This folding is only valid when the in-reg type is a vector of i8,
14309           // i16, or i32.
14310           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14311               ExtraEltVT == MVT::i32) {
14312             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14313             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14314                    "This optimization is invalid without a VZEXT.");
14315             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14316           }
14317           Op0 = Tmp1;
14318         }
14319       }
14320
14321       // If the above didn't work, then just use Shift-Left + Shift-Right.
14322       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14323                                         DAG);
14324       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14325                                         DAG);
14326     }
14327   }
14328 }
14329
14330 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14331                                  SelectionDAG &DAG) {
14332   SDLoc dl(Op);
14333   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14334     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14335   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14336     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14337
14338   // The only fence that needs an instruction is a sequentially-consistent
14339   // cross-thread fence.
14340   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14341     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14342     // no-sse2). There isn't any reason to disable it if the target processor
14343     // supports it.
14344     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14345       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14346
14347     SDValue Chain = Op.getOperand(0);
14348     SDValue Zero = DAG.getConstant(0, MVT::i32);
14349     SDValue Ops[] = {
14350       DAG.getRegister(X86::ESP, MVT::i32), // Base
14351       DAG.getTargetConstant(1, MVT::i8),   // Scale
14352       DAG.getRegister(0, MVT::i32),        // Index
14353       DAG.getTargetConstant(0, MVT::i32),  // Disp
14354       DAG.getRegister(0, MVT::i32),        // Segment.
14355       Zero,
14356       Chain
14357     };
14358     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14359     return SDValue(Res, 0);
14360   }
14361
14362   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14363   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14364 }
14365
14366 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14367                              SelectionDAG &DAG) {
14368   MVT T = Op.getSimpleValueType();
14369   SDLoc DL(Op);
14370   unsigned Reg = 0;
14371   unsigned size = 0;
14372   switch(T.SimpleTy) {
14373   default: llvm_unreachable("Invalid value type!");
14374   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14375   case MVT::i16: Reg = X86::AX;  size = 2; break;
14376   case MVT::i32: Reg = X86::EAX; size = 4; break;
14377   case MVT::i64:
14378     assert(Subtarget->is64Bit() && "Node not type legal!");
14379     Reg = X86::RAX; size = 8;
14380     break;
14381   }
14382   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14383                                     Op.getOperand(2), SDValue());
14384   SDValue Ops[] = { cpIn.getValue(0),
14385                     Op.getOperand(1),
14386                     Op.getOperand(3),
14387                     DAG.getTargetConstant(size, MVT::i8),
14388                     cpIn.getValue(1) };
14389   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14390   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14391   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14392                                            Ops, T, MMO);
14393   SDValue cpOut =
14394     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14395   return cpOut;
14396 }
14397
14398 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14399                             SelectionDAG &DAG) {
14400   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14401   MVT DstVT = Op.getSimpleValueType();
14402
14403   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14404     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14405     if (DstVT != MVT::f64)
14406       // This conversion needs to be expanded.
14407       return SDValue();
14408
14409     SDValue InVec = Op->getOperand(0);
14410     SDLoc dl(Op);
14411     unsigned NumElts = SrcVT.getVectorNumElements();
14412     EVT SVT = SrcVT.getVectorElementType();
14413
14414     // Widen the vector in input in the case of MVT::v2i32.
14415     // Example: from MVT::v2i32 to MVT::v4i32.
14416     SmallVector<SDValue, 16> Elts;
14417     for (unsigned i = 0, e = NumElts; i != e; ++i)
14418       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14419                                  DAG.getIntPtrConstant(i)));
14420
14421     // Explicitly mark the extra elements as Undef.
14422     SDValue Undef = DAG.getUNDEF(SVT);
14423     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14424       Elts.push_back(Undef);
14425
14426     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14427     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14428     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14429     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14430                        DAG.getIntPtrConstant(0));
14431   }
14432
14433   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14434          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14435   assert((DstVT == MVT::i64 ||
14436           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14437          "Unexpected custom BITCAST");
14438   // i64 <=> MMX conversions are Legal.
14439   if (SrcVT==MVT::i64 && DstVT.isVector())
14440     return Op;
14441   if (DstVT==MVT::i64 && SrcVT.isVector())
14442     return Op;
14443   // MMX <=> MMX conversions are Legal.
14444   if (SrcVT.isVector() && DstVT.isVector())
14445     return Op;
14446   // All other conversions need to be expanded.
14447   return SDValue();
14448 }
14449
14450 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14451   SDNode *Node = Op.getNode();
14452   SDLoc dl(Node);
14453   EVT T = Node->getValueType(0);
14454   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14455                               DAG.getConstant(0, T), Node->getOperand(2));
14456   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14457                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14458                        Node->getOperand(0),
14459                        Node->getOperand(1), negOp,
14460                        cast<AtomicSDNode>(Node)->getMemOperand(),
14461                        cast<AtomicSDNode>(Node)->getOrdering(),
14462                        cast<AtomicSDNode>(Node)->getSynchScope());
14463 }
14464
14465 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14466   SDNode *Node = Op.getNode();
14467   SDLoc dl(Node);
14468   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14469
14470   // Convert seq_cst store -> xchg
14471   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14472   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14473   //        (The only way to get a 16-byte store is cmpxchg16b)
14474   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14475   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14476       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14477     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14478                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14479                                  Node->getOperand(0),
14480                                  Node->getOperand(1), Node->getOperand(2),
14481                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14482                                  cast<AtomicSDNode>(Node)->getOrdering(),
14483                                  cast<AtomicSDNode>(Node)->getSynchScope());
14484     return Swap.getValue(1);
14485   }
14486   // Other atomic stores have a simple pattern.
14487   return Op;
14488 }
14489
14490 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14491   EVT VT = Op.getNode()->getSimpleValueType(0);
14492
14493   // Let legalize expand this if it isn't a legal type yet.
14494   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14495     return SDValue();
14496
14497   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14498
14499   unsigned Opc;
14500   bool ExtraOp = false;
14501   switch (Op.getOpcode()) {
14502   default: llvm_unreachable("Invalid code");
14503   case ISD::ADDC: Opc = X86ISD::ADD; break;
14504   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14505   case ISD::SUBC: Opc = X86ISD::SUB; break;
14506   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14507   }
14508
14509   if (!ExtraOp)
14510     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14511                        Op.getOperand(1));
14512   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14513                      Op.getOperand(1), Op.getOperand(2));
14514 }
14515
14516 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14517                             SelectionDAG &DAG) {
14518   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14519
14520   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14521   // which returns the values as { float, float } (in XMM0) or
14522   // { double, double } (which is returned in XMM0, XMM1).
14523   SDLoc dl(Op);
14524   SDValue Arg = Op.getOperand(0);
14525   EVT ArgVT = Arg.getValueType();
14526   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14527
14528   TargetLowering::ArgListTy Args;
14529   TargetLowering::ArgListEntry Entry;
14530
14531   Entry.Node = Arg;
14532   Entry.Ty = ArgTy;
14533   Entry.isSExt = false;
14534   Entry.isZExt = false;
14535   Args.push_back(Entry);
14536
14537   bool isF64 = ArgVT == MVT::f64;
14538   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14539   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14540   // the results are returned via SRet in memory.
14541   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14542   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14543   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14544
14545   Type *RetTy = isF64
14546     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14547     : (Type*)VectorType::get(ArgTy, 4);
14548
14549   TargetLowering::CallLoweringInfo CLI(DAG);
14550   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14551     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14552
14553   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14554
14555   if (isF64)
14556     // Returned in xmm0 and xmm1.
14557     return CallResult.first;
14558
14559   // Returned in bits 0:31 and 32:64 xmm0.
14560   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14561                                CallResult.first, DAG.getIntPtrConstant(0));
14562   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14563                                CallResult.first, DAG.getIntPtrConstant(1));
14564   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14565   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14566 }
14567
14568 /// LowerOperation - Provide custom lowering hooks for some operations.
14569 ///
14570 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14571   switch (Op.getOpcode()) {
14572   default: llvm_unreachable("Should not custom lower this!");
14573   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14574   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14575   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14576   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14577   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14578   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14579   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14580   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14581   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14582   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14583   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14584   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14585   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14586   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14587   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14588   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14589   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14590   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14591   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14592   case ISD::SHL_PARTS:
14593   case ISD::SRA_PARTS:
14594   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14595   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14596   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14597   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14598   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14599   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14600   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14601   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14602   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14603   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14604   case ISD::FABS:               return LowerFABS(Op, DAG);
14605   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14606   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14607   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14608   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14609   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14610   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14611   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14612   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14613   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14614   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14615   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14616   case ISD::INTRINSIC_VOID:
14617   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14618   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14619   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14620   case ISD::FRAME_TO_ARGS_OFFSET:
14621                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14622   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14623   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14624   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14625   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14626   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14627   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14628   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14629   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14630   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14631   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14632   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14633   case ISD::UMUL_LOHI:
14634   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14635   case ISD::SRA:
14636   case ISD::SRL:
14637   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14638   case ISD::SADDO:
14639   case ISD::UADDO:
14640   case ISD::SSUBO:
14641   case ISD::USUBO:
14642   case ISD::SMULO:
14643   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14644   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14645   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14646   case ISD::ADDC:
14647   case ISD::ADDE:
14648   case ISD::SUBC:
14649   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14650   case ISD::ADD:                return LowerADD(Op, DAG);
14651   case ISD::SUB:                return LowerSUB(Op, DAG);
14652   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14653   }
14654 }
14655
14656 static void ReplaceATOMIC_LOAD(SDNode *Node,
14657                                   SmallVectorImpl<SDValue> &Results,
14658                                   SelectionDAG &DAG) {
14659   SDLoc dl(Node);
14660   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14661
14662   // Convert wide load -> cmpxchg8b/cmpxchg16b
14663   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14664   //        (The only way to get a 16-byte load is cmpxchg16b)
14665   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14666   SDValue Zero = DAG.getConstant(0, VT);
14667   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14668                                Node->getOperand(0),
14669                                Node->getOperand(1), Zero, Zero,
14670                                cast<AtomicSDNode>(Node)->getMemOperand(),
14671                                cast<AtomicSDNode>(Node)->getOrdering(),
14672                                cast<AtomicSDNode>(Node)->getOrdering(),
14673                                cast<AtomicSDNode>(Node)->getSynchScope());
14674   Results.push_back(Swap.getValue(0));
14675   Results.push_back(Swap.getValue(1));
14676 }
14677
14678 static void
14679 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14680                         SelectionDAG &DAG, unsigned NewOp) {
14681   SDLoc dl(Node);
14682   assert (Node->getValueType(0) == MVT::i64 &&
14683           "Only know how to expand i64 atomics");
14684
14685   SDValue Chain = Node->getOperand(0);
14686   SDValue In1 = Node->getOperand(1);
14687   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14688                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14689   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14690                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14691   SDValue Ops[] = { Chain, In1, In2L, In2H };
14692   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14693   SDValue Result =
14694     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14695                             cast<MemSDNode>(Node)->getMemOperand());
14696   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14697   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14698   Results.push_back(Result.getValue(2));
14699 }
14700
14701 /// ReplaceNodeResults - Replace a node with an illegal result type
14702 /// with a new node built out of custom code.
14703 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14704                                            SmallVectorImpl<SDValue>&Results,
14705                                            SelectionDAG &DAG) const {
14706   SDLoc dl(N);
14707   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14708   switch (N->getOpcode()) {
14709   default:
14710     llvm_unreachable("Do not know how to custom type legalize this operation!");
14711   case ISD::SIGN_EXTEND_INREG:
14712   case ISD::ADDC:
14713   case ISD::ADDE:
14714   case ISD::SUBC:
14715   case ISD::SUBE:
14716     // We don't want to expand or promote these.
14717     return;
14718   case ISD::SDIV:
14719   case ISD::UDIV:
14720   case ISD::SREM:
14721   case ISD::UREM:
14722   case ISD::SDIVREM:
14723   case ISD::UDIVREM: {
14724     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14725     Results.push_back(V);
14726     return;
14727   }
14728   case ISD::FP_TO_SINT:
14729   case ISD::FP_TO_UINT: {
14730     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14731
14732     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14733       return;
14734
14735     std::pair<SDValue,SDValue> Vals =
14736         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14737     SDValue FIST = Vals.first, StackSlot = Vals.second;
14738     if (FIST.getNode()) {
14739       EVT VT = N->getValueType(0);
14740       // Return a load from the stack slot.
14741       if (StackSlot.getNode())
14742         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14743                                       MachinePointerInfo(),
14744                                       false, false, false, 0));
14745       else
14746         Results.push_back(FIST);
14747     }
14748     return;
14749   }
14750   case ISD::UINT_TO_FP: {
14751     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14752     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14753         N->getValueType(0) != MVT::v2f32)
14754       return;
14755     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14756                                  N->getOperand(0));
14757     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14758                                      MVT::f64);
14759     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14760     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14761                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14762     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14763     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14764     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14765     return;
14766   }
14767   case ISD::FP_ROUND: {
14768     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14769         return;
14770     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14771     Results.push_back(V);
14772     return;
14773   }
14774   case ISD::INTRINSIC_W_CHAIN: {
14775     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14776     switch (IntNo) {
14777     default : llvm_unreachable("Do not know how to custom type "
14778                                "legalize this intrinsic operation!");
14779     case Intrinsic::x86_rdtsc:
14780       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14781                                      Results);
14782     case Intrinsic::x86_rdtscp:
14783       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14784                                      Results);
14785     }
14786   }
14787   case ISD::READCYCLECOUNTER: {
14788     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14789                                    Results);
14790   }
14791   case ISD::ATOMIC_CMP_SWAP: {
14792     EVT T = N->getValueType(0);
14793     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14794     bool Regs64bit = T == MVT::i128;
14795     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14796     SDValue cpInL, cpInH;
14797     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14798                         DAG.getConstant(0, HalfT));
14799     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14800                         DAG.getConstant(1, HalfT));
14801     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14802                              Regs64bit ? X86::RAX : X86::EAX,
14803                              cpInL, SDValue());
14804     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14805                              Regs64bit ? X86::RDX : X86::EDX,
14806                              cpInH, cpInL.getValue(1));
14807     SDValue swapInL, swapInH;
14808     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14809                           DAG.getConstant(0, HalfT));
14810     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14811                           DAG.getConstant(1, HalfT));
14812     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14813                                Regs64bit ? X86::RBX : X86::EBX,
14814                                swapInL, cpInH.getValue(1));
14815     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14816                                Regs64bit ? X86::RCX : X86::ECX,
14817                                swapInH, swapInL.getValue(1));
14818     SDValue Ops[] = { swapInH.getValue(0),
14819                       N->getOperand(1),
14820                       swapInH.getValue(1) };
14821     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14822     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14823     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14824                                   X86ISD::LCMPXCHG8_DAG;
14825     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14826     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14827                                         Regs64bit ? X86::RAX : X86::EAX,
14828                                         HalfT, Result.getValue(1));
14829     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14830                                         Regs64bit ? X86::RDX : X86::EDX,
14831                                         HalfT, cpOutL.getValue(2));
14832     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14833     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14834     Results.push_back(cpOutH.getValue(1));
14835     return;
14836   }
14837   case ISD::ATOMIC_LOAD_ADD:
14838   case ISD::ATOMIC_LOAD_AND:
14839   case ISD::ATOMIC_LOAD_NAND:
14840   case ISD::ATOMIC_LOAD_OR:
14841   case ISD::ATOMIC_LOAD_SUB:
14842   case ISD::ATOMIC_LOAD_XOR:
14843   case ISD::ATOMIC_LOAD_MAX:
14844   case ISD::ATOMIC_LOAD_MIN:
14845   case ISD::ATOMIC_LOAD_UMAX:
14846   case ISD::ATOMIC_LOAD_UMIN:
14847   case ISD::ATOMIC_SWAP: {
14848     unsigned Opc;
14849     switch (N->getOpcode()) {
14850     default: llvm_unreachable("Unexpected opcode");
14851     case ISD::ATOMIC_LOAD_ADD:
14852       Opc = X86ISD::ATOMADD64_DAG;
14853       break;
14854     case ISD::ATOMIC_LOAD_AND:
14855       Opc = X86ISD::ATOMAND64_DAG;
14856       break;
14857     case ISD::ATOMIC_LOAD_NAND:
14858       Opc = X86ISD::ATOMNAND64_DAG;
14859       break;
14860     case ISD::ATOMIC_LOAD_OR:
14861       Opc = X86ISD::ATOMOR64_DAG;
14862       break;
14863     case ISD::ATOMIC_LOAD_SUB:
14864       Opc = X86ISD::ATOMSUB64_DAG;
14865       break;
14866     case ISD::ATOMIC_LOAD_XOR:
14867       Opc = X86ISD::ATOMXOR64_DAG;
14868       break;
14869     case ISD::ATOMIC_LOAD_MAX:
14870       Opc = X86ISD::ATOMMAX64_DAG;
14871       break;
14872     case ISD::ATOMIC_LOAD_MIN:
14873       Opc = X86ISD::ATOMMIN64_DAG;
14874       break;
14875     case ISD::ATOMIC_LOAD_UMAX:
14876       Opc = X86ISD::ATOMUMAX64_DAG;
14877       break;
14878     case ISD::ATOMIC_LOAD_UMIN:
14879       Opc = X86ISD::ATOMUMIN64_DAG;
14880       break;
14881     case ISD::ATOMIC_SWAP:
14882       Opc = X86ISD::ATOMSWAP64_DAG;
14883       break;
14884     }
14885     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14886     return;
14887   }
14888   case ISD::ATOMIC_LOAD: {
14889     ReplaceATOMIC_LOAD(N, Results, DAG);
14890     return;
14891   }
14892   case ISD::BITCAST: {
14893     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14894     EVT DstVT = N->getValueType(0);
14895     EVT SrcVT = N->getOperand(0)->getValueType(0);
14896
14897     if (SrcVT != MVT::f64 ||
14898         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14899       return;
14900
14901     unsigned NumElts = DstVT.getVectorNumElements();
14902     EVT SVT = DstVT.getVectorElementType();
14903     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14904     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14905                                    MVT::v2f64, N->getOperand(0));
14906     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14907
14908     SmallVector<SDValue, 8> Elts;
14909     for (unsigned i = 0, e = NumElts; i != e; ++i)
14910       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14911                                    ToVecInt, DAG.getIntPtrConstant(i)));
14912
14913     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14914   }
14915   }
14916 }
14917
14918 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14919   switch (Opcode) {
14920   default: return nullptr;
14921   case X86ISD::BSF:                return "X86ISD::BSF";
14922   case X86ISD::BSR:                return "X86ISD::BSR";
14923   case X86ISD::SHLD:               return "X86ISD::SHLD";
14924   case X86ISD::SHRD:               return "X86ISD::SHRD";
14925   case X86ISD::FAND:               return "X86ISD::FAND";
14926   case X86ISD::FANDN:              return "X86ISD::FANDN";
14927   case X86ISD::FOR:                return "X86ISD::FOR";
14928   case X86ISD::FXOR:               return "X86ISD::FXOR";
14929   case X86ISD::FSRL:               return "X86ISD::FSRL";
14930   case X86ISD::FILD:               return "X86ISD::FILD";
14931   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14932   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14933   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14934   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14935   case X86ISD::FLD:                return "X86ISD::FLD";
14936   case X86ISD::FST:                return "X86ISD::FST";
14937   case X86ISD::CALL:               return "X86ISD::CALL";
14938   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14939   case X86ISD::BT:                 return "X86ISD::BT";
14940   case X86ISD::CMP:                return "X86ISD::CMP";
14941   case X86ISD::COMI:               return "X86ISD::COMI";
14942   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14943   case X86ISD::CMPM:               return "X86ISD::CMPM";
14944   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14945   case X86ISD::SETCC:              return "X86ISD::SETCC";
14946   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14947   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14948   case X86ISD::CMOV:               return "X86ISD::CMOV";
14949   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14950   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14951   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14952   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14953   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14954   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14955   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14956   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14957   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14958   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14959   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14960   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14961   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14962   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14963   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14964   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14965   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14966   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14967   case X86ISD::HADD:               return "X86ISD::HADD";
14968   case X86ISD::HSUB:               return "X86ISD::HSUB";
14969   case X86ISD::FHADD:              return "X86ISD::FHADD";
14970   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14971   case X86ISD::UMAX:               return "X86ISD::UMAX";
14972   case X86ISD::UMIN:               return "X86ISD::UMIN";
14973   case X86ISD::SMAX:               return "X86ISD::SMAX";
14974   case X86ISD::SMIN:               return "X86ISD::SMIN";
14975   case X86ISD::FMAX:               return "X86ISD::FMAX";
14976   case X86ISD::FMIN:               return "X86ISD::FMIN";
14977   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14978   case X86ISD::FMINC:              return "X86ISD::FMINC";
14979   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14980   case X86ISD::FRCP:               return "X86ISD::FRCP";
14981   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14982   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14983   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14984   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14985   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14986   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14987   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14988   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14989   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14990   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14991   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14992   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14993   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14994   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14995   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14996   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14997   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14998   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14999   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
15000   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
15001   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
15002   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
15003   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
15004   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
15005   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
15006   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
15007   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
15008   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
15009   case X86ISD::VSHL:               return "X86ISD::VSHL";
15010   case X86ISD::VSRL:               return "X86ISD::VSRL";
15011   case X86ISD::VSRA:               return "X86ISD::VSRA";
15012   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
15013   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
15014   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
15015   case X86ISD::CMPP:               return "X86ISD::CMPP";
15016   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
15017   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
15018   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
15019   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
15020   case X86ISD::ADD:                return "X86ISD::ADD";
15021   case X86ISD::SUB:                return "X86ISD::SUB";
15022   case X86ISD::ADC:                return "X86ISD::ADC";
15023   case X86ISD::SBB:                return "X86ISD::SBB";
15024   case X86ISD::SMUL:               return "X86ISD::SMUL";
15025   case X86ISD::UMUL:               return "X86ISD::UMUL";
15026   case X86ISD::INC:                return "X86ISD::INC";
15027   case X86ISD::DEC:                return "X86ISD::DEC";
15028   case X86ISD::OR:                 return "X86ISD::OR";
15029   case X86ISD::XOR:                return "X86ISD::XOR";
15030   case X86ISD::AND:                return "X86ISD::AND";
15031   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
15032   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
15033   case X86ISD::PTEST:              return "X86ISD::PTEST";
15034   case X86ISD::TESTP:              return "X86ISD::TESTP";
15035   case X86ISD::TESTM:              return "X86ISD::TESTM";
15036   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
15037   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
15038   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
15039   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
15040   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
15041   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
15042   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
15043   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
15044   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
15045   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
15046   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
15047   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
15048   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
15049   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
15050   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
15051   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
15052   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
15053   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
15054   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
15055   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
15056   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
15057   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
15058   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
15059   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
15060   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
15061   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
15062   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
15063   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
15064   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
15065   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
15066   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15067   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
15068   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
15069   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
15070   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
15071   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
15072   case X86ISD::SAHF:               return "X86ISD::SAHF";
15073   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
15074   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
15075   case X86ISD::FMADD:              return "X86ISD::FMADD";
15076   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
15077   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
15078   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
15079   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
15080   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
15081   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
15082   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
15083   case X86ISD::XTEST:              return "X86ISD::XTEST";
15084   }
15085 }
15086
15087 // isLegalAddressingMode - Return true if the addressing mode represented
15088 // by AM is legal for this target, for a load/store of the specified type.
15089 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15090                                               Type *Ty) const {
15091   // X86 supports extremely general addressing modes.
15092   CodeModel::Model M = getTargetMachine().getCodeModel();
15093   Reloc::Model R = getTargetMachine().getRelocationModel();
15094
15095   // X86 allows a sign-extended 32-bit immediate field as a displacement.
15096   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15097     return false;
15098
15099   if (AM.BaseGV) {
15100     unsigned GVFlags =
15101       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15102
15103     // If a reference to this global requires an extra load, we can't fold it.
15104     if (isGlobalStubReference(GVFlags))
15105       return false;
15106
15107     // If BaseGV requires a register for the PIC base, we cannot also have a
15108     // BaseReg specified.
15109     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15110       return false;
15111
15112     // If lower 4G is not available, then we must use rip-relative addressing.
15113     if ((M != CodeModel::Small || R != Reloc::Static) &&
15114         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15115       return false;
15116   }
15117
15118   switch (AM.Scale) {
15119   case 0:
15120   case 1:
15121   case 2:
15122   case 4:
15123   case 8:
15124     // These scales always work.
15125     break;
15126   case 3:
15127   case 5:
15128   case 9:
15129     // These scales are formed with basereg+scalereg.  Only accept if there is
15130     // no basereg yet.
15131     if (AM.HasBaseReg)
15132       return false;
15133     break;
15134   default:  // Other stuff never works.
15135     return false;
15136   }
15137
15138   return true;
15139 }
15140
15141 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15142   unsigned Bits = Ty->getScalarSizeInBits();
15143
15144   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15145   // particularly cheaper than those without.
15146   if (Bits == 8)
15147     return false;
15148
15149   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15150   // variable shifts just as cheap as scalar ones.
15151   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15152     return false;
15153
15154   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15155   // fully general vector.
15156   return true;
15157 }
15158
15159 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15160   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15161     return false;
15162   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15163   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15164   return NumBits1 > NumBits2;
15165 }
15166
15167 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15168   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15169     return false;
15170
15171   if (!isTypeLegal(EVT::getEVT(Ty1)))
15172     return false;
15173
15174   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15175
15176   // Assuming the caller doesn't have a zeroext or signext return parameter,
15177   // truncation all the way down to i1 is valid.
15178   return true;
15179 }
15180
15181 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15182   return isInt<32>(Imm);
15183 }
15184
15185 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15186   // Can also use sub to handle negated immediates.
15187   return isInt<32>(Imm);
15188 }
15189
15190 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15191   if (!VT1.isInteger() || !VT2.isInteger())
15192     return false;
15193   unsigned NumBits1 = VT1.getSizeInBits();
15194   unsigned NumBits2 = VT2.getSizeInBits();
15195   return NumBits1 > NumBits2;
15196 }
15197
15198 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15199   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15200   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15201 }
15202
15203 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15204   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15205   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15206 }
15207
15208 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15209   EVT VT1 = Val.getValueType();
15210   if (isZExtFree(VT1, VT2))
15211     return true;
15212
15213   if (Val.getOpcode() != ISD::LOAD)
15214     return false;
15215
15216   if (!VT1.isSimple() || !VT1.isInteger() ||
15217       !VT2.isSimple() || !VT2.isInteger())
15218     return false;
15219
15220   switch (VT1.getSimpleVT().SimpleTy) {
15221   default: break;
15222   case MVT::i8:
15223   case MVT::i16:
15224   case MVT::i32:
15225     // X86 has 8, 16, and 32-bit zero-extending loads.
15226     return true;
15227   }
15228
15229   return false;
15230 }
15231
15232 bool
15233 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15234   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15235     return false;
15236
15237   VT = VT.getScalarType();
15238
15239   if (!VT.isSimple())
15240     return false;
15241
15242   switch (VT.getSimpleVT().SimpleTy) {
15243   case MVT::f32:
15244   case MVT::f64:
15245     return true;
15246   default:
15247     break;
15248   }
15249
15250   return false;
15251 }
15252
15253 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15254   // i16 instructions are longer (0x66 prefix) and potentially slower.
15255   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15256 }
15257
15258 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15259 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15260 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15261 /// are assumed to be legal.
15262 bool
15263 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15264                                       EVT VT) const {
15265   if (!VT.isSimple())
15266     return false;
15267
15268   MVT SVT = VT.getSimpleVT();
15269
15270   // Very little shuffling can be done for 64-bit vectors right now.
15271   if (VT.getSizeInBits() == 64)
15272     return false;
15273
15274   // If this is a single-input shuffle with no 128 bit lane crossings we can
15275   // lower it into pshufb.
15276   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15277       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15278     bool isLegal = true;
15279     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15280       if (M[I] >= (int)SVT.getVectorNumElements() ||
15281           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15282         isLegal = false;
15283         break;
15284       }
15285     }
15286     if (isLegal)
15287       return true;
15288   }
15289
15290   // FIXME: blends, shifts.
15291   return (SVT.getVectorNumElements() == 2 ||
15292           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15293           isMOVLMask(M, SVT) ||
15294           isSHUFPMask(M, SVT) ||
15295           isPSHUFDMask(M, SVT) ||
15296           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15297           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15298           isPALIGNRMask(M, SVT, Subtarget) ||
15299           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15300           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15301           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15302           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15303           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15304 }
15305
15306 bool
15307 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15308                                           EVT VT) const {
15309   if (!VT.isSimple())
15310     return false;
15311
15312   MVT SVT = VT.getSimpleVT();
15313   unsigned NumElts = SVT.getVectorNumElements();
15314   // FIXME: This collection of masks seems suspect.
15315   if (NumElts == 2)
15316     return true;
15317   if (NumElts == 4 && SVT.is128BitVector()) {
15318     return (isMOVLMask(Mask, SVT)  ||
15319             isCommutedMOVLMask(Mask, SVT, true) ||
15320             isSHUFPMask(Mask, SVT) ||
15321             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15322   }
15323   return false;
15324 }
15325
15326 //===----------------------------------------------------------------------===//
15327 //                           X86 Scheduler Hooks
15328 //===----------------------------------------------------------------------===//
15329
15330 /// Utility function to emit xbegin specifying the start of an RTM region.
15331 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15332                                      const TargetInstrInfo *TII) {
15333   DebugLoc DL = MI->getDebugLoc();
15334
15335   const BasicBlock *BB = MBB->getBasicBlock();
15336   MachineFunction::iterator I = MBB;
15337   ++I;
15338
15339   // For the v = xbegin(), we generate
15340   //
15341   // thisMBB:
15342   //  xbegin sinkMBB
15343   //
15344   // mainMBB:
15345   //  eax = -1
15346   //
15347   // sinkMBB:
15348   //  v = eax
15349
15350   MachineBasicBlock *thisMBB = MBB;
15351   MachineFunction *MF = MBB->getParent();
15352   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15353   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15354   MF->insert(I, mainMBB);
15355   MF->insert(I, sinkMBB);
15356
15357   // Transfer the remainder of BB and its successor edges to sinkMBB.
15358   sinkMBB->splice(sinkMBB->begin(), MBB,
15359                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15360   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15361
15362   // thisMBB:
15363   //  xbegin sinkMBB
15364   //  # fallthrough to mainMBB
15365   //  # abortion to sinkMBB
15366   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15367   thisMBB->addSuccessor(mainMBB);
15368   thisMBB->addSuccessor(sinkMBB);
15369
15370   // mainMBB:
15371   //  EAX = -1
15372   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15373   mainMBB->addSuccessor(sinkMBB);
15374
15375   // sinkMBB:
15376   // EAX is live into the sinkMBB
15377   sinkMBB->addLiveIn(X86::EAX);
15378   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15379           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15380     .addReg(X86::EAX);
15381
15382   MI->eraseFromParent();
15383   return sinkMBB;
15384 }
15385
15386 // Get CMPXCHG opcode for the specified data type.
15387 static unsigned getCmpXChgOpcode(EVT VT) {
15388   switch (VT.getSimpleVT().SimpleTy) {
15389   case MVT::i8:  return X86::LCMPXCHG8;
15390   case MVT::i16: return X86::LCMPXCHG16;
15391   case MVT::i32: return X86::LCMPXCHG32;
15392   case MVT::i64: return X86::LCMPXCHG64;
15393   default:
15394     break;
15395   }
15396   llvm_unreachable("Invalid operand size!");
15397 }
15398
15399 // Get LOAD opcode for the specified data type.
15400 static unsigned getLoadOpcode(EVT VT) {
15401   switch (VT.getSimpleVT().SimpleTy) {
15402   case MVT::i8:  return X86::MOV8rm;
15403   case MVT::i16: return X86::MOV16rm;
15404   case MVT::i32: return X86::MOV32rm;
15405   case MVT::i64: return X86::MOV64rm;
15406   default:
15407     break;
15408   }
15409   llvm_unreachable("Invalid operand size!");
15410 }
15411
15412 // Get opcode of the non-atomic one from the specified atomic instruction.
15413 static unsigned getNonAtomicOpcode(unsigned Opc) {
15414   switch (Opc) {
15415   case X86::ATOMAND8:  return X86::AND8rr;
15416   case X86::ATOMAND16: return X86::AND16rr;
15417   case X86::ATOMAND32: return X86::AND32rr;
15418   case X86::ATOMAND64: return X86::AND64rr;
15419   case X86::ATOMOR8:   return X86::OR8rr;
15420   case X86::ATOMOR16:  return X86::OR16rr;
15421   case X86::ATOMOR32:  return X86::OR32rr;
15422   case X86::ATOMOR64:  return X86::OR64rr;
15423   case X86::ATOMXOR8:  return X86::XOR8rr;
15424   case X86::ATOMXOR16: return X86::XOR16rr;
15425   case X86::ATOMXOR32: return X86::XOR32rr;
15426   case X86::ATOMXOR64: return X86::XOR64rr;
15427   }
15428   llvm_unreachable("Unhandled atomic-load-op opcode!");
15429 }
15430
15431 // Get opcode of the non-atomic one from the specified atomic instruction with
15432 // extra opcode.
15433 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15434                                                unsigned &ExtraOpc) {
15435   switch (Opc) {
15436   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15437   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15438   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15439   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15440   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15441   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15442   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15443   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15444   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15445   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15446   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15447   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15448   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15449   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15450   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15451   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15452   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15453   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15454   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15455   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15456   }
15457   llvm_unreachable("Unhandled atomic-load-op opcode!");
15458 }
15459
15460 // Get opcode of the non-atomic one from the specified atomic instruction for
15461 // 64-bit data type on 32-bit target.
15462 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15463   switch (Opc) {
15464   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15465   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15466   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15467   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15468   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15469   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15470   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15471   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15472   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15473   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15474   }
15475   llvm_unreachable("Unhandled atomic-load-op opcode!");
15476 }
15477
15478 // Get opcode of the non-atomic one from the specified atomic instruction for
15479 // 64-bit data type on 32-bit target with extra opcode.
15480 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15481                                                    unsigned &HiOpc,
15482                                                    unsigned &ExtraOpc) {
15483   switch (Opc) {
15484   case X86::ATOMNAND6432:
15485     ExtraOpc = X86::NOT32r;
15486     HiOpc = X86::AND32rr;
15487     return X86::AND32rr;
15488   }
15489   llvm_unreachable("Unhandled atomic-load-op opcode!");
15490 }
15491
15492 // Get pseudo CMOV opcode from the specified data type.
15493 static unsigned getPseudoCMOVOpc(EVT VT) {
15494   switch (VT.getSimpleVT().SimpleTy) {
15495   case MVT::i8:  return X86::CMOV_GR8;
15496   case MVT::i16: return X86::CMOV_GR16;
15497   case MVT::i32: return X86::CMOV_GR32;
15498   default:
15499     break;
15500   }
15501   llvm_unreachable("Unknown CMOV opcode!");
15502 }
15503
15504 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15505 // They will be translated into a spin-loop or compare-exchange loop from
15506 //
15507 //    ...
15508 //    dst = atomic-fetch-op MI.addr, MI.val
15509 //    ...
15510 //
15511 // to
15512 //
15513 //    ...
15514 //    t1 = LOAD MI.addr
15515 // loop:
15516 //    t4 = phi(t1, t3 / loop)
15517 //    t2 = OP MI.val, t4
15518 //    EAX = t4
15519 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15520 //    t3 = EAX
15521 //    JNE loop
15522 // sink:
15523 //    dst = t3
15524 //    ...
15525 MachineBasicBlock *
15526 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15527                                        MachineBasicBlock *MBB) const {
15528   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15529   DebugLoc DL = MI->getDebugLoc();
15530
15531   MachineFunction *MF = MBB->getParent();
15532   MachineRegisterInfo &MRI = MF->getRegInfo();
15533
15534   const BasicBlock *BB = MBB->getBasicBlock();
15535   MachineFunction::iterator I = MBB;
15536   ++I;
15537
15538   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15539          "Unexpected number of operands");
15540
15541   assert(MI->hasOneMemOperand() &&
15542          "Expected atomic-load-op to have one memoperand");
15543
15544   // Memory Reference
15545   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15546   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15547
15548   unsigned DstReg, SrcReg;
15549   unsigned MemOpndSlot;
15550
15551   unsigned CurOp = 0;
15552
15553   DstReg = MI->getOperand(CurOp++).getReg();
15554   MemOpndSlot = CurOp;
15555   CurOp += X86::AddrNumOperands;
15556   SrcReg = MI->getOperand(CurOp++).getReg();
15557
15558   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15559   MVT::SimpleValueType VT = *RC->vt_begin();
15560   unsigned t1 = MRI.createVirtualRegister(RC);
15561   unsigned t2 = MRI.createVirtualRegister(RC);
15562   unsigned t3 = MRI.createVirtualRegister(RC);
15563   unsigned t4 = MRI.createVirtualRegister(RC);
15564   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15565
15566   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15567   unsigned LOADOpc = getLoadOpcode(VT);
15568
15569   // For the atomic load-arith operator, we generate
15570   //
15571   //  thisMBB:
15572   //    t1 = LOAD [MI.addr]
15573   //  mainMBB:
15574   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15575   //    t1 = OP MI.val, EAX
15576   //    EAX = t4
15577   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15578   //    t3 = EAX
15579   //    JNE mainMBB
15580   //  sinkMBB:
15581   //    dst = t3
15582
15583   MachineBasicBlock *thisMBB = MBB;
15584   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15585   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15586   MF->insert(I, mainMBB);
15587   MF->insert(I, sinkMBB);
15588
15589   MachineInstrBuilder MIB;
15590
15591   // Transfer the remainder of BB and its successor edges to sinkMBB.
15592   sinkMBB->splice(sinkMBB->begin(), MBB,
15593                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15594   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15595
15596   // thisMBB:
15597   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15598   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15599     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15600     if (NewMO.isReg())
15601       NewMO.setIsKill(false);
15602     MIB.addOperand(NewMO);
15603   }
15604   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15605     unsigned flags = (*MMOI)->getFlags();
15606     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15607     MachineMemOperand *MMO =
15608       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15609                                (*MMOI)->getSize(),
15610                                (*MMOI)->getBaseAlignment(),
15611                                (*MMOI)->getTBAAInfo(),
15612                                (*MMOI)->getRanges());
15613     MIB.addMemOperand(MMO);
15614   }
15615
15616   thisMBB->addSuccessor(mainMBB);
15617
15618   // mainMBB:
15619   MachineBasicBlock *origMainMBB = mainMBB;
15620
15621   // Add a PHI.
15622   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15623                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15624
15625   unsigned Opc = MI->getOpcode();
15626   switch (Opc) {
15627   default:
15628     llvm_unreachable("Unhandled atomic-load-op opcode!");
15629   case X86::ATOMAND8:
15630   case X86::ATOMAND16:
15631   case X86::ATOMAND32:
15632   case X86::ATOMAND64:
15633   case X86::ATOMOR8:
15634   case X86::ATOMOR16:
15635   case X86::ATOMOR32:
15636   case X86::ATOMOR64:
15637   case X86::ATOMXOR8:
15638   case X86::ATOMXOR16:
15639   case X86::ATOMXOR32:
15640   case X86::ATOMXOR64: {
15641     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15642     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15643       .addReg(t4);
15644     break;
15645   }
15646   case X86::ATOMNAND8:
15647   case X86::ATOMNAND16:
15648   case X86::ATOMNAND32:
15649   case X86::ATOMNAND64: {
15650     unsigned Tmp = MRI.createVirtualRegister(RC);
15651     unsigned NOTOpc;
15652     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15653     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15654       .addReg(t4);
15655     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15656     break;
15657   }
15658   case X86::ATOMMAX8:
15659   case X86::ATOMMAX16:
15660   case X86::ATOMMAX32:
15661   case X86::ATOMMAX64:
15662   case X86::ATOMMIN8:
15663   case X86::ATOMMIN16:
15664   case X86::ATOMMIN32:
15665   case X86::ATOMMIN64:
15666   case X86::ATOMUMAX8:
15667   case X86::ATOMUMAX16:
15668   case X86::ATOMUMAX32:
15669   case X86::ATOMUMAX64:
15670   case X86::ATOMUMIN8:
15671   case X86::ATOMUMIN16:
15672   case X86::ATOMUMIN32:
15673   case X86::ATOMUMIN64: {
15674     unsigned CMPOpc;
15675     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15676
15677     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15678       .addReg(SrcReg)
15679       .addReg(t4);
15680
15681     if (Subtarget->hasCMov()) {
15682       if (VT != MVT::i8) {
15683         // Native support
15684         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15685           .addReg(SrcReg)
15686           .addReg(t4);
15687       } else {
15688         // Promote i8 to i32 to use CMOV32
15689         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15690         const TargetRegisterClass *RC32 =
15691           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15692         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15693         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15694         unsigned Tmp = MRI.createVirtualRegister(RC32);
15695
15696         unsigned Undef = MRI.createVirtualRegister(RC32);
15697         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15698
15699         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15700           .addReg(Undef)
15701           .addReg(SrcReg)
15702           .addImm(X86::sub_8bit);
15703         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15704           .addReg(Undef)
15705           .addReg(t4)
15706           .addImm(X86::sub_8bit);
15707
15708         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15709           .addReg(SrcReg32)
15710           .addReg(AccReg32);
15711
15712         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15713           .addReg(Tmp, 0, X86::sub_8bit);
15714       }
15715     } else {
15716       // Use pseudo select and lower them.
15717       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15718              "Invalid atomic-load-op transformation!");
15719       unsigned SelOpc = getPseudoCMOVOpc(VT);
15720       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15721       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15722       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15723               .addReg(SrcReg).addReg(t4)
15724               .addImm(CC);
15725       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15726       // Replace the original PHI node as mainMBB is changed after CMOV
15727       // lowering.
15728       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15729         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15730       Phi->eraseFromParent();
15731     }
15732     break;
15733   }
15734   }
15735
15736   // Copy PhyReg back from virtual register.
15737   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15738     .addReg(t4);
15739
15740   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15741   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15742     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15743     if (NewMO.isReg())
15744       NewMO.setIsKill(false);
15745     MIB.addOperand(NewMO);
15746   }
15747   MIB.addReg(t2);
15748   MIB.setMemRefs(MMOBegin, MMOEnd);
15749
15750   // Copy PhyReg back to virtual register.
15751   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15752     .addReg(PhyReg);
15753
15754   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15755
15756   mainMBB->addSuccessor(origMainMBB);
15757   mainMBB->addSuccessor(sinkMBB);
15758
15759   // sinkMBB:
15760   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15761           TII->get(TargetOpcode::COPY), DstReg)
15762     .addReg(t3);
15763
15764   MI->eraseFromParent();
15765   return sinkMBB;
15766 }
15767
15768 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15769 // instructions. They will be translated into a spin-loop or compare-exchange
15770 // loop from
15771 //
15772 //    ...
15773 //    dst = atomic-fetch-op MI.addr, MI.val
15774 //    ...
15775 //
15776 // to
15777 //
15778 //    ...
15779 //    t1L = LOAD [MI.addr + 0]
15780 //    t1H = LOAD [MI.addr + 4]
15781 // loop:
15782 //    t4L = phi(t1L, t3L / loop)
15783 //    t4H = phi(t1H, t3H / loop)
15784 //    t2L = OP MI.val.lo, t4L
15785 //    t2H = OP MI.val.hi, t4H
15786 //    EAX = t4L
15787 //    EDX = t4H
15788 //    EBX = t2L
15789 //    ECX = t2H
15790 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15791 //    t3L = EAX
15792 //    t3H = EDX
15793 //    JNE loop
15794 // sink:
15795 //    dstL = t3L
15796 //    dstH = t3H
15797 //    ...
15798 MachineBasicBlock *
15799 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15800                                            MachineBasicBlock *MBB) const {
15801   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15802   DebugLoc DL = MI->getDebugLoc();
15803
15804   MachineFunction *MF = MBB->getParent();
15805   MachineRegisterInfo &MRI = MF->getRegInfo();
15806
15807   const BasicBlock *BB = MBB->getBasicBlock();
15808   MachineFunction::iterator I = MBB;
15809   ++I;
15810
15811   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15812          "Unexpected number of operands");
15813
15814   assert(MI->hasOneMemOperand() &&
15815          "Expected atomic-load-op32 to have one memoperand");
15816
15817   // Memory Reference
15818   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15819   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15820
15821   unsigned DstLoReg, DstHiReg;
15822   unsigned SrcLoReg, SrcHiReg;
15823   unsigned MemOpndSlot;
15824
15825   unsigned CurOp = 0;
15826
15827   DstLoReg = MI->getOperand(CurOp++).getReg();
15828   DstHiReg = MI->getOperand(CurOp++).getReg();
15829   MemOpndSlot = CurOp;
15830   CurOp += X86::AddrNumOperands;
15831   SrcLoReg = MI->getOperand(CurOp++).getReg();
15832   SrcHiReg = MI->getOperand(CurOp++).getReg();
15833
15834   const TargetRegisterClass *RC = &X86::GR32RegClass;
15835   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15836
15837   unsigned t1L = MRI.createVirtualRegister(RC);
15838   unsigned t1H = MRI.createVirtualRegister(RC);
15839   unsigned t2L = MRI.createVirtualRegister(RC);
15840   unsigned t2H = MRI.createVirtualRegister(RC);
15841   unsigned t3L = MRI.createVirtualRegister(RC);
15842   unsigned t3H = MRI.createVirtualRegister(RC);
15843   unsigned t4L = MRI.createVirtualRegister(RC);
15844   unsigned t4H = MRI.createVirtualRegister(RC);
15845
15846   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15847   unsigned LOADOpc = X86::MOV32rm;
15848
15849   // For the atomic load-arith operator, we generate
15850   //
15851   //  thisMBB:
15852   //    t1L = LOAD [MI.addr + 0]
15853   //    t1H = LOAD [MI.addr + 4]
15854   //  mainMBB:
15855   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15856   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15857   //    t2L = OP MI.val.lo, t4L
15858   //    t2H = OP MI.val.hi, t4H
15859   //    EBX = t2L
15860   //    ECX = t2H
15861   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15862   //    t3L = EAX
15863   //    t3H = EDX
15864   //    JNE loop
15865   //  sinkMBB:
15866   //    dstL = t3L
15867   //    dstH = t3H
15868
15869   MachineBasicBlock *thisMBB = MBB;
15870   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15871   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15872   MF->insert(I, mainMBB);
15873   MF->insert(I, sinkMBB);
15874
15875   MachineInstrBuilder MIB;
15876
15877   // Transfer the remainder of BB and its successor edges to sinkMBB.
15878   sinkMBB->splice(sinkMBB->begin(), MBB,
15879                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15880   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15881
15882   // thisMBB:
15883   // Lo
15884   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15885   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15886     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15887     if (NewMO.isReg())
15888       NewMO.setIsKill(false);
15889     MIB.addOperand(NewMO);
15890   }
15891   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15892     unsigned flags = (*MMOI)->getFlags();
15893     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15894     MachineMemOperand *MMO =
15895       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15896                                (*MMOI)->getSize(),
15897                                (*MMOI)->getBaseAlignment(),
15898                                (*MMOI)->getTBAAInfo(),
15899                                (*MMOI)->getRanges());
15900     MIB.addMemOperand(MMO);
15901   };
15902   MachineInstr *LowMI = MIB;
15903
15904   // Hi
15905   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15906   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15907     if (i == X86::AddrDisp) {
15908       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15909     } else {
15910       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15911       if (NewMO.isReg())
15912         NewMO.setIsKill(false);
15913       MIB.addOperand(NewMO);
15914     }
15915   }
15916   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15917
15918   thisMBB->addSuccessor(mainMBB);
15919
15920   // mainMBB:
15921   MachineBasicBlock *origMainMBB = mainMBB;
15922
15923   // Add PHIs.
15924   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15925                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15926   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15927                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15928
15929   unsigned Opc = MI->getOpcode();
15930   switch (Opc) {
15931   default:
15932     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15933   case X86::ATOMAND6432:
15934   case X86::ATOMOR6432:
15935   case X86::ATOMXOR6432:
15936   case X86::ATOMADD6432:
15937   case X86::ATOMSUB6432: {
15938     unsigned HiOpc;
15939     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15940     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15941       .addReg(SrcLoReg);
15942     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15943       .addReg(SrcHiReg);
15944     break;
15945   }
15946   case X86::ATOMNAND6432: {
15947     unsigned HiOpc, NOTOpc;
15948     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15949     unsigned TmpL = MRI.createVirtualRegister(RC);
15950     unsigned TmpH = MRI.createVirtualRegister(RC);
15951     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15952       .addReg(t4L);
15953     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15954       .addReg(t4H);
15955     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15956     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15957     break;
15958   }
15959   case X86::ATOMMAX6432:
15960   case X86::ATOMMIN6432:
15961   case X86::ATOMUMAX6432:
15962   case X86::ATOMUMIN6432: {
15963     unsigned HiOpc;
15964     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15965     unsigned cL = MRI.createVirtualRegister(RC8);
15966     unsigned cH = MRI.createVirtualRegister(RC8);
15967     unsigned cL32 = MRI.createVirtualRegister(RC);
15968     unsigned cH32 = MRI.createVirtualRegister(RC);
15969     unsigned cc = MRI.createVirtualRegister(RC);
15970     // cl := cmp src_lo, lo
15971     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15972       .addReg(SrcLoReg).addReg(t4L);
15973     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15974     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15975     // ch := cmp src_hi, hi
15976     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15977       .addReg(SrcHiReg).addReg(t4H);
15978     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15979     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15980     // cc := if (src_hi == hi) ? cl : ch;
15981     if (Subtarget->hasCMov()) {
15982       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15983         .addReg(cH32).addReg(cL32);
15984     } else {
15985       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15986               .addReg(cH32).addReg(cL32)
15987               .addImm(X86::COND_E);
15988       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15989     }
15990     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15991     if (Subtarget->hasCMov()) {
15992       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15993         .addReg(SrcLoReg).addReg(t4L);
15994       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15995         .addReg(SrcHiReg).addReg(t4H);
15996     } else {
15997       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15998               .addReg(SrcLoReg).addReg(t4L)
15999               .addImm(X86::COND_NE);
16000       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16001       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16002       // 2nd CMOV lowering.
16003       mainMBB->addLiveIn(X86::EFLAGS);
16004       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16005               .addReg(SrcHiReg).addReg(t4H)
16006               .addImm(X86::COND_NE);
16007       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16008       // Replace the original PHI node as mainMBB is changed after CMOV
16009       // lowering.
16010       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16011         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16012       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16013         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16014       PhiL->eraseFromParent();
16015       PhiH->eraseFromParent();
16016     }
16017     break;
16018   }
16019   case X86::ATOMSWAP6432: {
16020     unsigned HiOpc;
16021     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16022     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16023     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16024     break;
16025   }
16026   }
16027
16028   // Copy EDX:EAX back from HiReg:LoReg
16029   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16030   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16031   // Copy ECX:EBX from t1H:t1L
16032   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16033   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16034
16035   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16036   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16037     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16038     if (NewMO.isReg())
16039       NewMO.setIsKill(false);
16040     MIB.addOperand(NewMO);
16041   }
16042   MIB.setMemRefs(MMOBegin, MMOEnd);
16043
16044   // Copy EDX:EAX back to t3H:t3L
16045   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16046   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16047
16048   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16049
16050   mainMBB->addSuccessor(origMainMBB);
16051   mainMBB->addSuccessor(sinkMBB);
16052
16053   // sinkMBB:
16054   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16055           TII->get(TargetOpcode::COPY), DstLoReg)
16056     .addReg(t3L);
16057   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16058           TII->get(TargetOpcode::COPY), DstHiReg)
16059     .addReg(t3H);
16060
16061   MI->eraseFromParent();
16062   return sinkMBB;
16063 }
16064
16065 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16066 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16067 // in the .td file.
16068 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16069                                        const TargetInstrInfo *TII) {
16070   unsigned Opc;
16071   switch (MI->getOpcode()) {
16072   default: llvm_unreachable("illegal opcode!");
16073   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16074   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16075   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16076   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16077   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16078   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16079   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16080   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16081   }
16082
16083   DebugLoc dl = MI->getDebugLoc();
16084   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16085
16086   unsigned NumArgs = MI->getNumOperands();
16087   for (unsigned i = 1; i < NumArgs; ++i) {
16088     MachineOperand &Op = MI->getOperand(i);
16089     if (!(Op.isReg() && Op.isImplicit()))
16090       MIB.addOperand(Op);
16091   }
16092   if (MI->hasOneMemOperand())
16093     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16094
16095   BuildMI(*BB, MI, dl,
16096     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16097     .addReg(X86::XMM0);
16098
16099   MI->eraseFromParent();
16100   return BB;
16101 }
16102
16103 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16104 // defs in an instruction pattern
16105 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16106                                        const TargetInstrInfo *TII) {
16107   unsigned Opc;
16108   switch (MI->getOpcode()) {
16109   default: llvm_unreachable("illegal opcode!");
16110   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16111   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16112   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16113   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16114   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16115   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16116   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16117   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16118   }
16119
16120   DebugLoc dl = MI->getDebugLoc();
16121   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16122
16123   unsigned NumArgs = MI->getNumOperands(); // remove the results
16124   for (unsigned i = 1; i < NumArgs; ++i) {
16125     MachineOperand &Op = MI->getOperand(i);
16126     if (!(Op.isReg() && Op.isImplicit()))
16127       MIB.addOperand(Op);
16128   }
16129   if (MI->hasOneMemOperand())
16130     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16131
16132   BuildMI(*BB, MI, dl,
16133     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16134     .addReg(X86::ECX);
16135
16136   MI->eraseFromParent();
16137   return BB;
16138 }
16139
16140 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16141                                        const TargetInstrInfo *TII,
16142                                        const X86Subtarget* Subtarget) {
16143   DebugLoc dl = MI->getDebugLoc();
16144
16145   // Address into RAX/EAX, other two args into ECX, EDX.
16146   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16147   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16148   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16149   for (int i = 0; i < X86::AddrNumOperands; ++i)
16150     MIB.addOperand(MI->getOperand(i));
16151
16152   unsigned ValOps = X86::AddrNumOperands;
16153   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16154     .addReg(MI->getOperand(ValOps).getReg());
16155   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16156     .addReg(MI->getOperand(ValOps+1).getReg());
16157
16158   // The instruction doesn't actually take any operands though.
16159   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16160
16161   MI->eraseFromParent(); // The pseudo is gone now.
16162   return BB;
16163 }
16164
16165 MachineBasicBlock *
16166 X86TargetLowering::EmitVAARG64WithCustomInserter(
16167                    MachineInstr *MI,
16168                    MachineBasicBlock *MBB) const {
16169   // Emit va_arg instruction on X86-64.
16170
16171   // Operands to this pseudo-instruction:
16172   // 0  ) Output        : destination address (reg)
16173   // 1-5) Input         : va_list address (addr, i64mem)
16174   // 6  ) ArgSize       : Size (in bytes) of vararg type
16175   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16176   // 8  ) Align         : Alignment of type
16177   // 9  ) EFLAGS (implicit-def)
16178
16179   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16180   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16181
16182   unsigned DestReg = MI->getOperand(0).getReg();
16183   MachineOperand &Base = MI->getOperand(1);
16184   MachineOperand &Scale = MI->getOperand(2);
16185   MachineOperand &Index = MI->getOperand(3);
16186   MachineOperand &Disp = MI->getOperand(4);
16187   MachineOperand &Segment = MI->getOperand(5);
16188   unsigned ArgSize = MI->getOperand(6).getImm();
16189   unsigned ArgMode = MI->getOperand(7).getImm();
16190   unsigned Align = MI->getOperand(8).getImm();
16191
16192   // Memory Reference
16193   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16194   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16195   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16196
16197   // Machine Information
16198   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16199   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16200   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16201   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16202   DebugLoc DL = MI->getDebugLoc();
16203
16204   // struct va_list {
16205   //   i32   gp_offset
16206   //   i32   fp_offset
16207   //   i64   overflow_area (address)
16208   //   i64   reg_save_area (address)
16209   // }
16210   // sizeof(va_list) = 24
16211   // alignment(va_list) = 8
16212
16213   unsigned TotalNumIntRegs = 6;
16214   unsigned TotalNumXMMRegs = 8;
16215   bool UseGPOffset = (ArgMode == 1);
16216   bool UseFPOffset = (ArgMode == 2);
16217   unsigned MaxOffset = TotalNumIntRegs * 8 +
16218                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16219
16220   /* Align ArgSize to a multiple of 8 */
16221   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16222   bool NeedsAlign = (Align > 8);
16223
16224   MachineBasicBlock *thisMBB = MBB;
16225   MachineBasicBlock *overflowMBB;
16226   MachineBasicBlock *offsetMBB;
16227   MachineBasicBlock *endMBB;
16228
16229   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16230   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16231   unsigned OffsetReg = 0;
16232
16233   if (!UseGPOffset && !UseFPOffset) {
16234     // If we only pull from the overflow region, we don't create a branch.
16235     // We don't need to alter control flow.
16236     OffsetDestReg = 0; // unused
16237     OverflowDestReg = DestReg;
16238
16239     offsetMBB = nullptr;
16240     overflowMBB = thisMBB;
16241     endMBB = thisMBB;
16242   } else {
16243     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16244     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16245     // If not, pull from overflow_area. (branch to overflowMBB)
16246     //
16247     //       thisMBB
16248     //         |     .
16249     //         |        .
16250     //     offsetMBB   overflowMBB
16251     //         |        .
16252     //         |     .
16253     //        endMBB
16254
16255     // Registers for the PHI in endMBB
16256     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16257     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16258
16259     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16260     MachineFunction *MF = MBB->getParent();
16261     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16262     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16263     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16264
16265     MachineFunction::iterator MBBIter = MBB;
16266     ++MBBIter;
16267
16268     // Insert the new basic blocks
16269     MF->insert(MBBIter, offsetMBB);
16270     MF->insert(MBBIter, overflowMBB);
16271     MF->insert(MBBIter, endMBB);
16272
16273     // Transfer the remainder of MBB and its successor edges to endMBB.
16274     endMBB->splice(endMBB->begin(), thisMBB,
16275                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16276     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16277
16278     // Make offsetMBB and overflowMBB successors of thisMBB
16279     thisMBB->addSuccessor(offsetMBB);
16280     thisMBB->addSuccessor(overflowMBB);
16281
16282     // endMBB is a successor of both offsetMBB and overflowMBB
16283     offsetMBB->addSuccessor(endMBB);
16284     overflowMBB->addSuccessor(endMBB);
16285
16286     // Load the offset value into a register
16287     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16288     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16289       .addOperand(Base)
16290       .addOperand(Scale)
16291       .addOperand(Index)
16292       .addDisp(Disp, UseFPOffset ? 4 : 0)
16293       .addOperand(Segment)
16294       .setMemRefs(MMOBegin, MMOEnd);
16295
16296     // Check if there is enough room left to pull this argument.
16297     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16298       .addReg(OffsetReg)
16299       .addImm(MaxOffset + 8 - ArgSizeA8);
16300
16301     // Branch to "overflowMBB" if offset >= max
16302     // Fall through to "offsetMBB" otherwise
16303     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16304       .addMBB(overflowMBB);
16305   }
16306
16307   // In offsetMBB, emit code to use the reg_save_area.
16308   if (offsetMBB) {
16309     assert(OffsetReg != 0);
16310
16311     // Read the reg_save_area address.
16312     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16313     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16314       .addOperand(Base)
16315       .addOperand(Scale)
16316       .addOperand(Index)
16317       .addDisp(Disp, 16)
16318       .addOperand(Segment)
16319       .setMemRefs(MMOBegin, MMOEnd);
16320
16321     // Zero-extend the offset
16322     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16323       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16324         .addImm(0)
16325         .addReg(OffsetReg)
16326         .addImm(X86::sub_32bit);
16327
16328     // Add the offset to the reg_save_area to get the final address.
16329     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16330       .addReg(OffsetReg64)
16331       .addReg(RegSaveReg);
16332
16333     // Compute the offset for the next argument
16334     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16335     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16336       .addReg(OffsetReg)
16337       .addImm(UseFPOffset ? 16 : 8);
16338
16339     // Store it back into the va_list.
16340     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16341       .addOperand(Base)
16342       .addOperand(Scale)
16343       .addOperand(Index)
16344       .addDisp(Disp, UseFPOffset ? 4 : 0)
16345       .addOperand(Segment)
16346       .addReg(NextOffsetReg)
16347       .setMemRefs(MMOBegin, MMOEnd);
16348
16349     // Jump to endMBB
16350     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16351       .addMBB(endMBB);
16352   }
16353
16354   //
16355   // Emit code to use overflow area
16356   //
16357
16358   // Load the overflow_area address into a register.
16359   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16360   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16361     .addOperand(Base)
16362     .addOperand(Scale)
16363     .addOperand(Index)
16364     .addDisp(Disp, 8)
16365     .addOperand(Segment)
16366     .setMemRefs(MMOBegin, MMOEnd);
16367
16368   // If we need to align it, do so. Otherwise, just copy the address
16369   // to OverflowDestReg.
16370   if (NeedsAlign) {
16371     // Align the overflow address
16372     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16373     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16374
16375     // aligned_addr = (addr + (align-1)) & ~(align-1)
16376     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16377       .addReg(OverflowAddrReg)
16378       .addImm(Align-1);
16379
16380     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16381       .addReg(TmpReg)
16382       .addImm(~(uint64_t)(Align-1));
16383   } else {
16384     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16385       .addReg(OverflowAddrReg);
16386   }
16387
16388   // Compute the next overflow address after this argument.
16389   // (the overflow address should be kept 8-byte aligned)
16390   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16391   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16392     .addReg(OverflowDestReg)
16393     .addImm(ArgSizeA8);
16394
16395   // Store the new overflow address.
16396   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16397     .addOperand(Base)
16398     .addOperand(Scale)
16399     .addOperand(Index)
16400     .addDisp(Disp, 8)
16401     .addOperand(Segment)
16402     .addReg(NextAddrReg)
16403     .setMemRefs(MMOBegin, MMOEnd);
16404
16405   // If we branched, emit the PHI to the front of endMBB.
16406   if (offsetMBB) {
16407     BuildMI(*endMBB, endMBB->begin(), DL,
16408             TII->get(X86::PHI), DestReg)
16409       .addReg(OffsetDestReg).addMBB(offsetMBB)
16410       .addReg(OverflowDestReg).addMBB(overflowMBB);
16411   }
16412
16413   // Erase the pseudo instruction
16414   MI->eraseFromParent();
16415
16416   return endMBB;
16417 }
16418
16419 MachineBasicBlock *
16420 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16421                                                  MachineInstr *MI,
16422                                                  MachineBasicBlock *MBB) const {
16423   // Emit code to save XMM registers to the stack. The ABI says that the
16424   // number of registers to save is given in %al, so it's theoretically
16425   // possible to do an indirect jump trick to avoid saving all of them,
16426   // however this code takes a simpler approach and just executes all
16427   // of the stores if %al is non-zero. It's less code, and it's probably
16428   // easier on the hardware branch predictor, and stores aren't all that
16429   // expensive anyway.
16430
16431   // Create the new basic blocks. One block contains all the XMM stores,
16432   // and one block is the final destination regardless of whether any
16433   // stores were performed.
16434   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16435   MachineFunction *F = MBB->getParent();
16436   MachineFunction::iterator MBBIter = MBB;
16437   ++MBBIter;
16438   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16439   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16440   F->insert(MBBIter, XMMSaveMBB);
16441   F->insert(MBBIter, EndMBB);
16442
16443   // Transfer the remainder of MBB and its successor edges to EndMBB.
16444   EndMBB->splice(EndMBB->begin(), MBB,
16445                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16446   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16447
16448   // The original block will now fall through to the XMM save block.
16449   MBB->addSuccessor(XMMSaveMBB);
16450   // The XMMSaveMBB will fall through to the end block.
16451   XMMSaveMBB->addSuccessor(EndMBB);
16452
16453   // Now add the instructions.
16454   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16455   DebugLoc DL = MI->getDebugLoc();
16456
16457   unsigned CountReg = MI->getOperand(0).getReg();
16458   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16459   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16460
16461   if (!Subtarget->isTargetWin64()) {
16462     // If %al is 0, branch around the XMM save block.
16463     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16464     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16465     MBB->addSuccessor(EndMBB);
16466   }
16467
16468   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16469   // that was just emitted, but clearly shouldn't be "saved".
16470   assert((MI->getNumOperands() <= 3 ||
16471           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16472           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16473          && "Expected last argument to be EFLAGS");
16474   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16475   // In the XMM save block, save all the XMM argument registers.
16476   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16477     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16478     MachineMemOperand *MMO =
16479       F->getMachineMemOperand(
16480           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16481         MachineMemOperand::MOStore,
16482         /*Size=*/16, /*Align=*/16);
16483     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16484       .addFrameIndex(RegSaveFrameIndex)
16485       .addImm(/*Scale=*/1)
16486       .addReg(/*IndexReg=*/0)
16487       .addImm(/*Disp=*/Offset)
16488       .addReg(/*Segment=*/0)
16489       .addReg(MI->getOperand(i).getReg())
16490       .addMemOperand(MMO);
16491   }
16492
16493   MI->eraseFromParent();   // The pseudo instruction is gone now.
16494
16495   return EndMBB;
16496 }
16497
16498 // The EFLAGS operand of SelectItr might be missing a kill marker
16499 // because there were multiple uses of EFLAGS, and ISel didn't know
16500 // which to mark. Figure out whether SelectItr should have had a
16501 // kill marker, and set it if it should. Returns the correct kill
16502 // marker value.
16503 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16504                                      MachineBasicBlock* BB,
16505                                      const TargetRegisterInfo* TRI) {
16506   // Scan forward through BB for a use/def of EFLAGS.
16507   MachineBasicBlock::iterator miI(std::next(SelectItr));
16508   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16509     const MachineInstr& mi = *miI;
16510     if (mi.readsRegister(X86::EFLAGS))
16511       return false;
16512     if (mi.definesRegister(X86::EFLAGS))
16513       break; // Should have kill-flag - update below.
16514   }
16515
16516   // If we hit the end of the block, check whether EFLAGS is live into a
16517   // successor.
16518   if (miI == BB->end()) {
16519     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16520                                           sEnd = BB->succ_end();
16521          sItr != sEnd; ++sItr) {
16522       MachineBasicBlock* succ = *sItr;
16523       if (succ->isLiveIn(X86::EFLAGS))
16524         return false;
16525     }
16526   }
16527
16528   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16529   // out. SelectMI should have a kill flag on EFLAGS.
16530   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16531   return true;
16532 }
16533
16534 MachineBasicBlock *
16535 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16536                                      MachineBasicBlock *BB) const {
16537   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16538   DebugLoc DL = MI->getDebugLoc();
16539
16540   // To "insert" a SELECT_CC instruction, we actually have to insert the
16541   // diamond control-flow pattern.  The incoming instruction knows the
16542   // destination vreg to set, the condition code register to branch on, the
16543   // true/false values to select between, and a branch opcode to use.
16544   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16545   MachineFunction::iterator It = BB;
16546   ++It;
16547
16548   //  thisMBB:
16549   //  ...
16550   //   TrueVal = ...
16551   //   cmpTY ccX, r1, r2
16552   //   bCC copy1MBB
16553   //   fallthrough --> copy0MBB
16554   MachineBasicBlock *thisMBB = BB;
16555   MachineFunction *F = BB->getParent();
16556   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16557   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16558   F->insert(It, copy0MBB);
16559   F->insert(It, sinkMBB);
16560
16561   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16562   // live into the sink and copy blocks.
16563   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16564   if (!MI->killsRegister(X86::EFLAGS) &&
16565       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16566     copy0MBB->addLiveIn(X86::EFLAGS);
16567     sinkMBB->addLiveIn(X86::EFLAGS);
16568   }
16569
16570   // Transfer the remainder of BB and its successor edges to sinkMBB.
16571   sinkMBB->splice(sinkMBB->begin(), BB,
16572                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16573   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16574
16575   // Add the true and fallthrough blocks as its successors.
16576   BB->addSuccessor(copy0MBB);
16577   BB->addSuccessor(sinkMBB);
16578
16579   // Create the conditional branch instruction.
16580   unsigned Opc =
16581     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16582   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16583
16584   //  copy0MBB:
16585   //   %FalseValue = ...
16586   //   # fallthrough to sinkMBB
16587   copy0MBB->addSuccessor(sinkMBB);
16588
16589   //  sinkMBB:
16590   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16591   //  ...
16592   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16593           TII->get(X86::PHI), MI->getOperand(0).getReg())
16594     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16595     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16596
16597   MI->eraseFromParent();   // The pseudo instruction is gone now.
16598   return sinkMBB;
16599 }
16600
16601 MachineBasicBlock *
16602 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16603                                         bool Is64Bit) const {
16604   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16605   DebugLoc DL = MI->getDebugLoc();
16606   MachineFunction *MF = BB->getParent();
16607   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16608
16609   assert(MF->shouldSplitStack());
16610
16611   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16612   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16613
16614   // BB:
16615   //  ... [Till the alloca]
16616   // If stacklet is not large enough, jump to mallocMBB
16617   //
16618   // bumpMBB:
16619   //  Allocate by subtracting from RSP
16620   //  Jump to continueMBB
16621   //
16622   // mallocMBB:
16623   //  Allocate by call to runtime
16624   //
16625   // continueMBB:
16626   //  ...
16627   //  [rest of original BB]
16628   //
16629
16630   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16631   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16632   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16633
16634   MachineRegisterInfo &MRI = MF->getRegInfo();
16635   const TargetRegisterClass *AddrRegClass =
16636     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16637
16638   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16639     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16640     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16641     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16642     sizeVReg = MI->getOperand(1).getReg(),
16643     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16644
16645   MachineFunction::iterator MBBIter = BB;
16646   ++MBBIter;
16647
16648   MF->insert(MBBIter, bumpMBB);
16649   MF->insert(MBBIter, mallocMBB);
16650   MF->insert(MBBIter, continueMBB);
16651
16652   continueMBB->splice(continueMBB->begin(), BB,
16653                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16654   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16655
16656   // Add code to the main basic block to check if the stack limit has been hit,
16657   // and if so, jump to mallocMBB otherwise to bumpMBB.
16658   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16659   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16660     .addReg(tmpSPVReg).addReg(sizeVReg);
16661   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16662     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16663     .addReg(SPLimitVReg);
16664   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16665
16666   // bumpMBB simply decreases the stack pointer, since we know the current
16667   // stacklet has enough space.
16668   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16669     .addReg(SPLimitVReg);
16670   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16671     .addReg(SPLimitVReg);
16672   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16673
16674   // Calls into a routine in libgcc to allocate more space from the heap.
16675   const uint32_t *RegMask =
16676     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16677   if (Is64Bit) {
16678     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16679       .addReg(sizeVReg);
16680     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16681       .addExternalSymbol("__morestack_allocate_stack_space")
16682       .addRegMask(RegMask)
16683       .addReg(X86::RDI, RegState::Implicit)
16684       .addReg(X86::RAX, RegState::ImplicitDefine);
16685   } else {
16686     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16687       .addImm(12);
16688     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16689     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16690       .addExternalSymbol("__morestack_allocate_stack_space")
16691       .addRegMask(RegMask)
16692       .addReg(X86::EAX, RegState::ImplicitDefine);
16693   }
16694
16695   if (!Is64Bit)
16696     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16697       .addImm(16);
16698
16699   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16700     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16701   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16702
16703   // Set up the CFG correctly.
16704   BB->addSuccessor(bumpMBB);
16705   BB->addSuccessor(mallocMBB);
16706   mallocMBB->addSuccessor(continueMBB);
16707   bumpMBB->addSuccessor(continueMBB);
16708
16709   // Take care of the PHI nodes.
16710   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16711           MI->getOperand(0).getReg())
16712     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16713     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16714
16715   // Delete the original pseudo instruction.
16716   MI->eraseFromParent();
16717
16718   // And we're done.
16719   return continueMBB;
16720 }
16721
16722 MachineBasicBlock *
16723 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16724                                           MachineBasicBlock *BB) const {
16725   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16726   DebugLoc DL = MI->getDebugLoc();
16727
16728   assert(!Subtarget->isTargetMacho());
16729
16730   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16731   // non-trivial part is impdef of ESP.
16732
16733   if (Subtarget->isTargetWin64()) {
16734     if (Subtarget->isTargetCygMing()) {
16735       // ___chkstk(Mingw64):
16736       // Clobbers R10, R11, RAX and EFLAGS.
16737       // Updates RSP.
16738       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16739         .addExternalSymbol("___chkstk")
16740         .addReg(X86::RAX, RegState::Implicit)
16741         .addReg(X86::RSP, RegState::Implicit)
16742         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16743         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16744         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16745     } else {
16746       // __chkstk(MSVCRT): does not update stack pointer.
16747       // Clobbers R10, R11 and EFLAGS.
16748       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16749         .addExternalSymbol("__chkstk")
16750         .addReg(X86::RAX, RegState::Implicit)
16751         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16752       // RAX has the offset to be subtracted from RSP.
16753       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16754         .addReg(X86::RSP)
16755         .addReg(X86::RAX);
16756     }
16757   } else {
16758     const char *StackProbeSymbol =
16759       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16760
16761     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16762       .addExternalSymbol(StackProbeSymbol)
16763       .addReg(X86::EAX, RegState::Implicit)
16764       .addReg(X86::ESP, RegState::Implicit)
16765       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16766       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16767       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16768   }
16769
16770   MI->eraseFromParent();   // The pseudo instruction is gone now.
16771   return BB;
16772 }
16773
16774 MachineBasicBlock *
16775 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16776                                       MachineBasicBlock *BB) const {
16777   // This is pretty easy.  We're taking the value that we received from
16778   // our load from the relocation, sticking it in either RDI (x86-64)
16779   // or EAX and doing an indirect call.  The return value will then
16780   // be in the normal return register.
16781   const X86InstrInfo *TII
16782     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16783   DebugLoc DL = MI->getDebugLoc();
16784   MachineFunction *F = BB->getParent();
16785
16786   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16787   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16788
16789   // Get a register mask for the lowered call.
16790   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16791   // proper register mask.
16792   const uint32_t *RegMask =
16793     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16794   if (Subtarget->is64Bit()) {
16795     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16796                                       TII->get(X86::MOV64rm), X86::RDI)
16797     .addReg(X86::RIP)
16798     .addImm(0).addReg(0)
16799     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16800                       MI->getOperand(3).getTargetFlags())
16801     .addReg(0);
16802     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16803     addDirectMem(MIB, X86::RDI);
16804     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16805   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16806     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16807                                       TII->get(X86::MOV32rm), X86::EAX)
16808     .addReg(0)
16809     .addImm(0).addReg(0)
16810     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16811                       MI->getOperand(3).getTargetFlags())
16812     .addReg(0);
16813     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16814     addDirectMem(MIB, X86::EAX);
16815     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16816   } else {
16817     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16818                                       TII->get(X86::MOV32rm), X86::EAX)
16819     .addReg(TII->getGlobalBaseReg(F))
16820     .addImm(0).addReg(0)
16821     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16822                       MI->getOperand(3).getTargetFlags())
16823     .addReg(0);
16824     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16825     addDirectMem(MIB, X86::EAX);
16826     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16827   }
16828
16829   MI->eraseFromParent(); // The pseudo instruction is gone now.
16830   return BB;
16831 }
16832
16833 MachineBasicBlock *
16834 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16835                                     MachineBasicBlock *MBB) const {
16836   DebugLoc DL = MI->getDebugLoc();
16837   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16838
16839   MachineFunction *MF = MBB->getParent();
16840   MachineRegisterInfo &MRI = MF->getRegInfo();
16841
16842   const BasicBlock *BB = MBB->getBasicBlock();
16843   MachineFunction::iterator I = MBB;
16844   ++I;
16845
16846   // Memory Reference
16847   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16848   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16849
16850   unsigned DstReg;
16851   unsigned MemOpndSlot = 0;
16852
16853   unsigned CurOp = 0;
16854
16855   DstReg = MI->getOperand(CurOp++).getReg();
16856   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16857   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16858   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16859   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16860
16861   MemOpndSlot = CurOp;
16862
16863   MVT PVT = getPointerTy();
16864   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16865          "Invalid Pointer Size!");
16866
16867   // For v = setjmp(buf), we generate
16868   //
16869   // thisMBB:
16870   //  buf[LabelOffset] = restoreMBB
16871   //  SjLjSetup restoreMBB
16872   //
16873   // mainMBB:
16874   //  v_main = 0
16875   //
16876   // sinkMBB:
16877   //  v = phi(main, restore)
16878   //
16879   // restoreMBB:
16880   //  v_restore = 1
16881
16882   MachineBasicBlock *thisMBB = MBB;
16883   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16884   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16885   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16886   MF->insert(I, mainMBB);
16887   MF->insert(I, sinkMBB);
16888   MF->push_back(restoreMBB);
16889
16890   MachineInstrBuilder MIB;
16891
16892   // Transfer the remainder of BB and its successor edges to sinkMBB.
16893   sinkMBB->splice(sinkMBB->begin(), MBB,
16894                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16895   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16896
16897   // thisMBB:
16898   unsigned PtrStoreOpc = 0;
16899   unsigned LabelReg = 0;
16900   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16901   Reloc::Model RM = getTargetMachine().getRelocationModel();
16902   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16903                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16904
16905   // Prepare IP either in reg or imm.
16906   if (!UseImmLabel) {
16907     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16908     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16909     LabelReg = MRI.createVirtualRegister(PtrRC);
16910     if (Subtarget->is64Bit()) {
16911       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16912               .addReg(X86::RIP)
16913               .addImm(0)
16914               .addReg(0)
16915               .addMBB(restoreMBB)
16916               .addReg(0);
16917     } else {
16918       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16919       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16920               .addReg(XII->getGlobalBaseReg(MF))
16921               .addImm(0)
16922               .addReg(0)
16923               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16924               .addReg(0);
16925     }
16926   } else
16927     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16928   // Store IP
16929   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16930   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16931     if (i == X86::AddrDisp)
16932       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16933     else
16934       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16935   }
16936   if (!UseImmLabel)
16937     MIB.addReg(LabelReg);
16938   else
16939     MIB.addMBB(restoreMBB);
16940   MIB.setMemRefs(MMOBegin, MMOEnd);
16941   // Setup
16942   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16943           .addMBB(restoreMBB);
16944
16945   const X86RegisterInfo *RegInfo =
16946     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16947   MIB.addRegMask(RegInfo->getNoPreservedMask());
16948   thisMBB->addSuccessor(mainMBB);
16949   thisMBB->addSuccessor(restoreMBB);
16950
16951   // mainMBB:
16952   //  EAX = 0
16953   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16954   mainMBB->addSuccessor(sinkMBB);
16955
16956   // sinkMBB:
16957   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16958           TII->get(X86::PHI), DstReg)
16959     .addReg(mainDstReg).addMBB(mainMBB)
16960     .addReg(restoreDstReg).addMBB(restoreMBB);
16961
16962   // restoreMBB:
16963   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16964   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16965   restoreMBB->addSuccessor(sinkMBB);
16966
16967   MI->eraseFromParent();
16968   return sinkMBB;
16969 }
16970
16971 MachineBasicBlock *
16972 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16973                                      MachineBasicBlock *MBB) const {
16974   DebugLoc DL = MI->getDebugLoc();
16975   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16976
16977   MachineFunction *MF = MBB->getParent();
16978   MachineRegisterInfo &MRI = MF->getRegInfo();
16979
16980   // Memory Reference
16981   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16982   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16983
16984   MVT PVT = getPointerTy();
16985   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16986          "Invalid Pointer Size!");
16987
16988   const TargetRegisterClass *RC =
16989     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16990   unsigned Tmp = MRI.createVirtualRegister(RC);
16991   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16992   const X86RegisterInfo *RegInfo =
16993     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16994   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16995   unsigned SP = RegInfo->getStackRegister();
16996
16997   MachineInstrBuilder MIB;
16998
16999   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17000   const int64_t SPOffset = 2 * PVT.getStoreSize();
17001
17002   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17003   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17004
17005   // Reload FP
17006   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17007   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17008     MIB.addOperand(MI->getOperand(i));
17009   MIB.setMemRefs(MMOBegin, MMOEnd);
17010   // Reload IP
17011   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17012   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17013     if (i == X86::AddrDisp)
17014       MIB.addDisp(MI->getOperand(i), LabelOffset);
17015     else
17016       MIB.addOperand(MI->getOperand(i));
17017   }
17018   MIB.setMemRefs(MMOBegin, MMOEnd);
17019   // Reload SP
17020   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17021   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17022     if (i == X86::AddrDisp)
17023       MIB.addDisp(MI->getOperand(i), SPOffset);
17024     else
17025       MIB.addOperand(MI->getOperand(i));
17026   }
17027   MIB.setMemRefs(MMOBegin, MMOEnd);
17028   // Jump
17029   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17030
17031   MI->eraseFromParent();
17032   return MBB;
17033 }
17034
17035 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17036 // accumulator loops. Writing back to the accumulator allows the coalescer
17037 // to remove extra copies in the loop.   
17038 MachineBasicBlock *
17039 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17040                                  MachineBasicBlock *MBB) const {
17041   MachineOperand &AddendOp = MI->getOperand(3);
17042
17043   // Bail out early if the addend isn't a register - we can't switch these.
17044   if (!AddendOp.isReg())
17045     return MBB;
17046
17047   MachineFunction &MF = *MBB->getParent();
17048   MachineRegisterInfo &MRI = MF.getRegInfo();
17049
17050   // Check whether the addend is defined by a PHI:
17051   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17052   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17053   if (!AddendDef.isPHI())
17054     return MBB;
17055
17056   // Look for the following pattern:
17057   // loop:
17058   //   %addend = phi [%entry, 0], [%loop, %result]
17059   //   ...
17060   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17061
17062   // Replace with:
17063   //   loop:
17064   //   %addend = phi [%entry, 0], [%loop, %result]
17065   //   ...
17066   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17067
17068   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17069     assert(AddendDef.getOperand(i).isReg());
17070     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17071     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17072     if (&PHISrcInst == MI) {
17073       // Found a matching instruction.
17074       unsigned NewFMAOpc = 0;
17075       switch (MI->getOpcode()) {
17076         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17077         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17078         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17079         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17080         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17081         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17082         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17083         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17084         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17085         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17086         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17087         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17088         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17089         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17090         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17091         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17092         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17093         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17094         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17095         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17096         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17097         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17098         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17099         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17100         default: llvm_unreachable("Unrecognized FMA variant.");
17101       }
17102
17103       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17104       MachineInstrBuilder MIB =
17105         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17106         .addOperand(MI->getOperand(0))
17107         .addOperand(MI->getOperand(3))
17108         .addOperand(MI->getOperand(2))
17109         .addOperand(MI->getOperand(1));
17110       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17111       MI->eraseFromParent();
17112     }
17113   }
17114
17115   return MBB;
17116 }
17117
17118 MachineBasicBlock *
17119 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17120                                                MachineBasicBlock *BB) const {
17121   switch (MI->getOpcode()) {
17122   default: llvm_unreachable("Unexpected instr type to insert");
17123   case X86::TAILJMPd64:
17124   case X86::TAILJMPr64:
17125   case X86::TAILJMPm64:
17126     llvm_unreachable("TAILJMP64 would not be touched here.");
17127   case X86::TCRETURNdi64:
17128   case X86::TCRETURNri64:
17129   case X86::TCRETURNmi64:
17130     return BB;
17131   case X86::WIN_ALLOCA:
17132     return EmitLoweredWinAlloca(MI, BB);
17133   case X86::SEG_ALLOCA_32:
17134     return EmitLoweredSegAlloca(MI, BB, false);
17135   case X86::SEG_ALLOCA_64:
17136     return EmitLoweredSegAlloca(MI, BB, true);
17137   case X86::TLSCall_32:
17138   case X86::TLSCall_64:
17139     return EmitLoweredTLSCall(MI, BB);
17140   case X86::CMOV_GR8:
17141   case X86::CMOV_FR32:
17142   case X86::CMOV_FR64:
17143   case X86::CMOV_V4F32:
17144   case X86::CMOV_V2F64:
17145   case X86::CMOV_V2I64:
17146   case X86::CMOV_V8F32:
17147   case X86::CMOV_V4F64:
17148   case X86::CMOV_V4I64:
17149   case X86::CMOV_V16F32:
17150   case X86::CMOV_V8F64:
17151   case X86::CMOV_V8I64:
17152   case X86::CMOV_GR16:
17153   case X86::CMOV_GR32:
17154   case X86::CMOV_RFP32:
17155   case X86::CMOV_RFP64:
17156   case X86::CMOV_RFP80:
17157     return EmitLoweredSelect(MI, BB);
17158
17159   case X86::FP32_TO_INT16_IN_MEM:
17160   case X86::FP32_TO_INT32_IN_MEM:
17161   case X86::FP32_TO_INT64_IN_MEM:
17162   case X86::FP64_TO_INT16_IN_MEM:
17163   case X86::FP64_TO_INT32_IN_MEM:
17164   case X86::FP64_TO_INT64_IN_MEM:
17165   case X86::FP80_TO_INT16_IN_MEM:
17166   case X86::FP80_TO_INT32_IN_MEM:
17167   case X86::FP80_TO_INT64_IN_MEM: {
17168     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17169     DebugLoc DL = MI->getDebugLoc();
17170
17171     // Change the floating point control register to use "round towards zero"
17172     // mode when truncating to an integer value.
17173     MachineFunction *F = BB->getParent();
17174     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17175     addFrameReference(BuildMI(*BB, MI, DL,
17176                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17177
17178     // Load the old value of the high byte of the control word...
17179     unsigned OldCW =
17180       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17181     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17182                       CWFrameIdx);
17183
17184     // Set the high part to be round to zero...
17185     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17186       .addImm(0xC7F);
17187
17188     // Reload the modified control word now...
17189     addFrameReference(BuildMI(*BB, MI, DL,
17190                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17191
17192     // Restore the memory image of control word to original value
17193     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17194       .addReg(OldCW);
17195
17196     // Get the X86 opcode to use.
17197     unsigned Opc;
17198     switch (MI->getOpcode()) {
17199     default: llvm_unreachable("illegal opcode!");
17200     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17201     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17202     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17203     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17204     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17205     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17206     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17207     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17208     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17209     }
17210
17211     X86AddressMode AM;
17212     MachineOperand &Op = MI->getOperand(0);
17213     if (Op.isReg()) {
17214       AM.BaseType = X86AddressMode::RegBase;
17215       AM.Base.Reg = Op.getReg();
17216     } else {
17217       AM.BaseType = X86AddressMode::FrameIndexBase;
17218       AM.Base.FrameIndex = Op.getIndex();
17219     }
17220     Op = MI->getOperand(1);
17221     if (Op.isImm())
17222       AM.Scale = Op.getImm();
17223     Op = MI->getOperand(2);
17224     if (Op.isImm())
17225       AM.IndexReg = Op.getImm();
17226     Op = MI->getOperand(3);
17227     if (Op.isGlobal()) {
17228       AM.GV = Op.getGlobal();
17229     } else {
17230       AM.Disp = Op.getImm();
17231     }
17232     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17233                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17234
17235     // Reload the original control word now.
17236     addFrameReference(BuildMI(*BB, MI, DL,
17237                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17238
17239     MI->eraseFromParent();   // The pseudo instruction is gone now.
17240     return BB;
17241   }
17242     // String/text processing lowering.
17243   case X86::PCMPISTRM128REG:
17244   case X86::VPCMPISTRM128REG:
17245   case X86::PCMPISTRM128MEM:
17246   case X86::VPCMPISTRM128MEM:
17247   case X86::PCMPESTRM128REG:
17248   case X86::VPCMPESTRM128REG:
17249   case X86::PCMPESTRM128MEM:
17250   case X86::VPCMPESTRM128MEM:
17251     assert(Subtarget->hasSSE42() &&
17252            "Target must have SSE4.2 or AVX features enabled");
17253     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17254
17255   // String/text processing lowering.
17256   case X86::PCMPISTRIREG:
17257   case X86::VPCMPISTRIREG:
17258   case X86::PCMPISTRIMEM:
17259   case X86::VPCMPISTRIMEM:
17260   case X86::PCMPESTRIREG:
17261   case X86::VPCMPESTRIREG:
17262   case X86::PCMPESTRIMEM:
17263   case X86::VPCMPESTRIMEM:
17264     assert(Subtarget->hasSSE42() &&
17265            "Target must have SSE4.2 or AVX features enabled");
17266     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17267
17268   // Thread synchronization.
17269   case X86::MONITOR:
17270     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17271
17272   // xbegin
17273   case X86::XBEGIN:
17274     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17275
17276   // Atomic Lowering.
17277   case X86::ATOMAND8:
17278   case X86::ATOMAND16:
17279   case X86::ATOMAND32:
17280   case X86::ATOMAND64:
17281     // Fall through
17282   case X86::ATOMOR8:
17283   case X86::ATOMOR16:
17284   case X86::ATOMOR32:
17285   case X86::ATOMOR64:
17286     // Fall through
17287   case X86::ATOMXOR16:
17288   case X86::ATOMXOR8:
17289   case X86::ATOMXOR32:
17290   case X86::ATOMXOR64:
17291     // Fall through
17292   case X86::ATOMNAND8:
17293   case X86::ATOMNAND16:
17294   case X86::ATOMNAND32:
17295   case X86::ATOMNAND64:
17296     // Fall through
17297   case X86::ATOMMAX8:
17298   case X86::ATOMMAX16:
17299   case X86::ATOMMAX32:
17300   case X86::ATOMMAX64:
17301     // Fall through
17302   case X86::ATOMMIN8:
17303   case X86::ATOMMIN16:
17304   case X86::ATOMMIN32:
17305   case X86::ATOMMIN64:
17306     // Fall through
17307   case X86::ATOMUMAX8:
17308   case X86::ATOMUMAX16:
17309   case X86::ATOMUMAX32:
17310   case X86::ATOMUMAX64:
17311     // Fall through
17312   case X86::ATOMUMIN8:
17313   case X86::ATOMUMIN16:
17314   case X86::ATOMUMIN32:
17315   case X86::ATOMUMIN64:
17316     return EmitAtomicLoadArith(MI, BB);
17317
17318   // This group does 64-bit operations on a 32-bit host.
17319   case X86::ATOMAND6432:
17320   case X86::ATOMOR6432:
17321   case X86::ATOMXOR6432:
17322   case X86::ATOMNAND6432:
17323   case X86::ATOMADD6432:
17324   case X86::ATOMSUB6432:
17325   case X86::ATOMMAX6432:
17326   case X86::ATOMMIN6432:
17327   case X86::ATOMUMAX6432:
17328   case X86::ATOMUMIN6432:
17329   case X86::ATOMSWAP6432:
17330     return EmitAtomicLoadArith6432(MI, BB);
17331
17332   case X86::VASTART_SAVE_XMM_REGS:
17333     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17334
17335   case X86::VAARG_64:
17336     return EmitVAARG64WithCustomInserter(MI, BB);
17337
17338   case X86::EH_SjLj_SetJmp32:
17339   case X86::EH_SjLj_SetJmp64:
17340     return emitEHSjLjSetJmp(MI, BB);
17341
17342   case X86::EH_SjLj_LongJmp32:
17343   case X86::EH_SjLj_LongJmp64:
17344     return emitEHSjLjLongJmp(MI, BB);
17345
17346   case TargetOpcode::STACKMAP:
17347   case TargetOpcode::PATCHPOINT:
17348     return emitPatchPoint(MI, BB);
17349
17350   case X86::VFMADDPDr213r:
17351   case X86::VFMADDPSr213r:
17352   case X86::VFMADDSDr213r:
17353   case X86::VFMADDSSr213r:
17354   case X86::VFMSUBPDr213r:
17355   case X86::VFMSUBPSr213r:
17356   case X86::VFMSUBSDr213r:
17357   case X86::VFMSUBSSr213r:
17358   case X86::VFNMADDPDr213r:
17359   case X86::VFNMADDPSr213r:
17360   case X86::VFNMADDSDr213r:
17361   case X86::VFNMADDSSr213r:
17362   case X86::VFNMSUBPDr213r:
17363   case X86::VFNMSUBPSr213r:
17364   case X86::VFNMSUBSDr213r:
17365   case X86::VFNMSUBSSr213r:
17366   case X86::VFMADDPDr213rY:
17367   case X86::VFMADDPSr213rY:
17368   case X86::VFMSUBPDr213rY:
17369   case X86::VFMSUBPSr213rY:
17370   case X86::VFNMADDPDr213rY:
17371   case X86::VFNMADDPSr213rY:
17372   case X86::VFNMSUBPDr213rY:
17373   case X86::VFNMSUBPSr213rY:
17374     return emitFMA3Instr(MI, BB);
17375   }
17376 }
17377
17378 //===----------------------------------------------------------------------===//
17379 //                           X86 Optimization Hooks
17380 //===----------------------------------------------------------------------===//
17381
17382 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17383                                                       APInt &KnownZero,
17384                                                       APInt &KnownOne,
17385                                                       const SelectionDAG &DAG,
17386                                                       unsigned Depth) const {
17387   unsigned BitWidth = KnownZero.getBitWidth();
17388   unsigned Opc = Op.getOpcode();
17389   assert((Opc >= ISD::BUILTIN_OP_END ||
17390           Opc == ISD::INTRINSIC_WO_CHAIN ||
17391           Opc == ISD::INTRINSIC_W_CHAIN ||
17392           Opc == ISD::INTRINSIC_VOID) &&
17393          "Should use MaskedValueIsZero if you don't know whether Op"
17394          " is a target node!");
17395
17396   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17397   switch (Opc) {
17398   default: break;
17399   case X86ISD::ADD:
17400   case X86ISD::SUB:
17401   case X86ISD::ADC:
17402   case X86ISD::SBB:
17403   case X86ISD::SMUL:
17404   case X86ISD::UMUL:
17405   case X86ISD::INC:
17406   case X86ISD::DEC:
17407   case X86ISD::OR:
17408   case X86ISD::XOR:
17409   case X86ISD::AND:
17410     // These nodes' second result is a boolean.
17411     if (Op.getResNo() == 0)
17412       break;
17413     // Fallthrough
17414   case X86ISD::SETCC:
17415     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17416     break;
17417   case ISD::INTRINSIC_WO_CHAIN: {
17418     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17419     unsigned NumLoBits = 0;
17420     switch (IntId) {
17421     default: break;
17422     case Intrinsic::x86_sse_movmsk_ps:
17423     case Intrinsic::x86_avx_movmsk_ps_256:
17424     case Intrinsic::x86_sse2_movmsk_pd:
17425     case Intrinsic::x86_avx_movmsk_pd_256:
17426     case Intrinsic::x86_mmx_pmovmskb:
17427     case Intrinsic::x86_sse2_pmovmskb_128:
17428     case Intrinsic::x86_avx2_pmovmskb: {
17429       // High bits of movmskp{s|d}, pmovmskb are known zero.
17430       switch (IntId) {
17431         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17432         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17433         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17434         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17435         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17436         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17437         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17438         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17439       }
17440       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17441       break;
17442     }
17443     }
17444     break;
17445   }
17446   }
17447 }
17448
17449 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17450   SDValue Op,
17451   const SelectionDAG &,
17452   unsigned Depth) const {
17453   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17454   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17455     return Op.getValueType().getScalarType().getSizeInBits();
17456
17457   // Fallback case.
17458   return 1;
17459 }
17460
17461 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17462 /// node is a GlobalAddress + offset.
17463 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17464                                        const GlobalValue* &GA,
17465                                        int64_t &Offset) const {
17466   if (N->getOpcode() == X86ISD::Wrapper) {
17467     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17468       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17469       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17470       return true;
17471     }
17472   }
17473   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17474 }
17475
17476 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17477 /// same as extracting the high 128-bit part of 256-bit vector and then
17478 /// inserting the result into the low part of a new 256-bit vector
17479 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17480   EVT VT = SVOp->getValueType(0);
17481   unsigned NumElems = VT.getVectorNumElements();
17482
17483   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17484   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17485     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17486         SVOp->getMaskElt(j) >= 0)
17487       return false;
17488
17489   return true;
17490 }
17491
17492 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17493 /// same as extracting the low 128-bit part of 256-bit vector and then
17494 /// inserting the result into the high part of a new 256-bit vector
17495 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17496   EVT VT = SVOp->getValueType(0);
17497   unsigned NumElems = VT.getVectorNumElements();
17498
17499   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17500   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17501     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17502         SVOp->getMaskElt(j) >= 0)
17503       return false;
17504
17505   return true;
17506 }
17507
17508 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17509 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17510                                         TargetLowering::DAGCombinerInfo &DCI,
17511                                         const X86Subtarget* Subtarget) {
17512   SDLoc dl(N);
17513   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17514   SDValue V1 = SVOp->getOperand(0);
17515   SDValue V2 = SVOp->getOperand(1);
17516   EVT VT = SVOp->getValueType(0);
17517   unsigned NumElems = VT.getVectorNumElements();
17518
17519   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17520       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17521     //
17522     //                   0,0,0,...
17523     //                      |
17524     //    V      UNDEF    BUILD_VECTOR    UNDEF
17525     //     \      /           \           /
17526     //  CONCAT_VECTOR         CONCAT_VECTOR
17527     //         \                  /
17528     //          \                /
17529     //          RESULT: V + zero extended
17530     //
17531     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17532         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17533         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17534       return SDValue();
17535
17536     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17537       return SDValue();
17538
17539     // To match the shuffle mask, the first half of the mask should
17540     // be exactly the first vector, and all the rest a splat with the
17541     // first element of the second one.
17542     for (unsigned i = 0; i != NumElems/2; ++i)
17543       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17544           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17545         return SDValue();
17546
17547     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17548     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17549       if (Ld->hasNUsesOfValue(1, 0)) {
17550         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17551         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17552         SDValue ResNode =
17553           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17554                                   Ld->getMemoryVT(),
17555                                   Ld->getPointerInfo(),
17556                                   Ld->getAlignment(),
17557                                   false/*isVolatile*/, true/*ReadMem*/,
17558                                   false/*WriteMem*/);
17559
17560         // Make sure the newly-created LOAD is in the same position as Ld in
17561         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17562         // and update uses of Ld's output chain to use the TokenFactor.
17563         if (Ld->hasAnyUseOfValue(1)) {
17564           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17565                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17566           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17567           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17568                                  SDValue(ResNode.getNode(), 1));
17569         }
17570
17571         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17572       }
17573     }
17574
17575     // Emit a zeroed vector and insert the desired subvector on its
17576     // first half.
17577     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17578     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17579     return DCI.CombineTo(N, InsV);
17580   }
17581
17582   //===--------------------------------------------------------------------===//
17583   // Combine some shuffles into subvector extracts and inserts:
17584   //
17585
17586   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17587   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17588     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17589     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17590     return DCI.CombineTo(N, InsV);
17591   }
17592
17593   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17594   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17595     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17596     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17597     return DCI.CombineTo(N, InsV);
17598   }
17599
17600   return SDValue();
17601 }
17602
17603 /// PerformShuffleCombine - Performs several different shuffle combines.
17604 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17605                                      TargetLowering::DAGCombinerInfo &DCI,
17606                                      const X86Subtarget *Subtarget) {
17607   SDLoc dl(N);
17608   SDValue N0 = N->getOperand(0);
17609   SDValue N1 = N->getOperand(1);
17610   EVT VT = N->getValueType(0);
17611
17612   // Don't create instructions with illegal types after legalize types has run.
17613   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17614   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17615     return SDValue();
17616
17617   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17618   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17619       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17620     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17621
17622   // During Type Legalization, when promoting illegal vector types,
17623   // the backend might introduce new shuffle dag nodes and bitcasts.
17624   //
17625   // This code performs the following transformation:
17626   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17627   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17628   //
17629   // We do this only if both the bitcast and the BINOP dag nodes have
17630   // one use. Also, perform this transformation only if the new binary
17631   // operation is legal. This is to avoid introducing dag nodes that
17632   // potentially need to be further expanded (or custom lowered) into a
17633   // less optimal sequence of dag nodes.
17634   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17635       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17636       N0.getOpcode() == ISD::BITCAST) {
17637     SDValue BC0 = N0.getOperand(0);
17638     EVT SVT = BC0.getValueType();
17639     unsigned Opcode = BC0.getOpcode();
17640     unsigned NumElts = VT.getVectorNumElements();
17641     
17642     if (BC0.hasOneUse() && SVT.isVector() &&
17643         SVT.getVectorNumElements() * 2 == NumElts &&
17644         TLI.isOperationLegal(Opcode, VT)) {
17645       bool CanFold = false;
17646       switch (Opcode) {
17647       default : break;
17648       case ISD::ADD :
17649       case ISD::FADD :
17650       case ISD::SUB :
17651       case ISD::FSUB :
17652       case ISD::MUL :
17653       case ISD::FMUL :
17654         CanFold = true;
17655       }
17656
17657       unsigned SVTNumElts = SVT.getVectorNumElements();
17658       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17659       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17660         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17661       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17662         CanFold = SVOp->getMaskElt(i) < 0;
17663
17664       if (CanFold) {
17665         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17666         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17667         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17668         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17669       }
17670     }
17671   }
17672
17673   // Only handle 128 wide vector from here on.
17674   if (!VT.is128BitVector())
17675     return SDValue();
17676
17677   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17678   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17679   // consecutive, non-overlapping, and in the right order.
17680   SmallVector<SDValue, 16> Elts;
17681   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17682     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17683
17684   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17685 }
17686
17687 /// PerformTruncateCombine - Converts truncate operation to
17688 /// a sequence of vector shuffle operations.
17689 /// It is possible when we truncate 256-bit vector to 128-bit vector
17690 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17691                                       TargetLowering::DAGCombinerInfo &DCI,
17692                                       const X86Subtarget *Subtarget)  {
17693   return SDValue();
17694 }
17695
17696 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17697 /// specific shuffle of a load can be folded into a single element load.
17698 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17699 /// shuffles have been customed lowered so we need to handle those here.
17700 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17701                                          TargetLowering::DAGCombinerInfo &DCI) {
17702   if (DCI.isBeforeLegalizeOps())
17703     return SDValue();
17704
17705   SDValue InVec = N->getOperand(0);
17706   SDValue EltNo = N->getOperand(1);
17707
17708   if (!isa<ConstantSDNode>(EltNo))
17709     return SDValue();
17710
17711   EVT VT = InVec.getValueType();
17712
17713   bool HasShuffleIntoBitcast = false;
17714   if (InVec.getOpcode() == ISD::BITCAST) {
17715     // Don't duplicate a load with other uses.
17716     if (!InVec.hasOneUse())
17717       return SDValue();
17718     EVT BCVT = InVec.getOperand(0).getValueType();
17719     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17720       return SDValue();
17721     InVec = InVec.getOperand(0);
17722     HasShuffleIntoBitcast = true;
17723   }
17724
17725   if (!isTargetShuffle(InVec.getOpcode()))
17726     return SDValue();
17727
17728   // Don't duplicate a load with other uses.
17729   if (!InVec.hasOneUse())
17730     return SDValue();
17731
17732   SmallVector<int, 16> ShuffleMask;
17733   bool UnaryShuffle;
17734   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17735                             UnaryShuffle))
17736     return SDValue();
17737
17738   // Select the input vector, guarding against out of range extract vector.
17739   unsigned NumElems = VT.getVectorNumElements();
17740   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17741   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17742   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17743                                          : InVec.getOperand(1);
17744
17745   // If inputs to shuffle are the same for both ops, then allow 2 uses
17746   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17747
17748   if (LdNode.getOpcode() == ISD::BITCAST) {
17749     // Don't duplicate a load with other uses.
17750     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17751       return SDValue();
17752
17753     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17754     LdNode = LdNode.getOperand(0);
17755   }
17756
17757   if (!ISD::isNormalLoad(LdNode.getNode()))
17758     return SDValue();
17759
17760   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17761
17762   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17763     return SDValue();
17764
17765   if (HasShuffleIntoBitcast) {
17766     // If there's a bitcast before the shuffle, check if the load type and
17767     // alignment is valid.
17768     unsigned Align = LN0->getAlignment();
17769     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17770     unsigned NewAlign = TLI.getDataLayout()->
17771       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17772
17773     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17774       return SDValue();
17775   }
17776
17777   // All checks match so transform back to vector_shuffle so that DAG combiner
17778   // can finish the job
17779   SDLoc dl(N);
17780
17781   // Create shuffle node taking into account the case that its a unary shuffle
17782   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17783   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17784                                  InVec.getOperand(0), Shuffle,
17785                                  &ShuffleMask[0]);
17786   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17787   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17788                      EltNo);
17789 }
17790
17791 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17792 /// generation and convert it from being a bunch of shuffles and extracts
17793 /// to a simple store and scalar loads to extract the elements.
17794 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17795                                          TargetLowering::DAGCombinerInfo &DCI) {
17796   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17797   if (NewOp.getNode())
17798     return NewOp;
17799
17800   SDValue InputVector = N->getOperand(0);
17801
17802   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17803   // from mmx to v2i32 has a single usage.
17804   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17805       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17806       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17807     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17808                        N->getValueType(0),
17809                        InputVector.getNode()->getOperand(0));
17810
17811   // Only operate on vectors of 4 elements, where the alternative shuffling
17812   // gets to be more expensive.
17813   if (InputVector.getValueType() != MVT::v4i32)
17814     return SDValue();
17815
17816   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17817   // single use which is a sign-extend or zero-extend, and all elements are
17818   // used.
17819   SmallVector<SDNode *, 4> Uses;
17820   unsigned ExtractedElements = 0;
17821   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17822        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17823     if (UI.getUse().getResNo() != InputVector.getResNo())
17824       return SDValue();
17825
17826     SDNode *Extract = *UI;
17827     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17828       return SDValue();
17829
17830     if (Extract->getValueType(0) != MVT::i32)
17831       return SDValue();
17832     if (!Extract->hasOneUse())
17833       return SDValue();
17834     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17835         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17836       return SDValue();
17837     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17838       return SDValue();
17839
17840     // Record which element was extracted.
17841     ExtractedElements |=
17842       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17843
17844     Uses.push_back(Extract);
17845   }
17846
17847   // If not all the elements were used, this may not be worthwhile.
17848   if (ExtractedElements != 15)
17849     return SDValue();
17850
17851   // Ok, we've now decided to do the transformation.
17852   SDLoc dl(InputVector);
17853
17854   // Store the value to a temporary stack slot.
17855   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17856   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17857                             MachinePointerInfo(), false, false, 0);
17858
17859   // Replace each use (extract) with a load of the appropriate element.
17860   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17861        UE = Uses.end(); UI != UE; ++UI) {
17862     SDNode *Extract = *UI;
17863
17864     // cOMpute the element's address.
17865     SDValue Idx = Extract->getOperand(1);
17866     unsigned EltSize =
17867         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17868     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17869     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17870     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17871
17872     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17873                                      StackPtr, OffsetVal);
17874
17875     // Load the scalar.
17876     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17877                                      ScalarAddr, MachinePointerInfo(),
17878                                      false, false, false, 0);
17879
17880     // Replace the exact with the load.
17881     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17882   }
17883
17884   // The replacement was made in place; don't return anything.
17885   return SDValue();
17886 }
17887
17888 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17889 static std::pair<unsigned, bool>
17890 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17891                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17892   if (!VT.isVector())
17893     return std::make_pair(0, false);
17894
17895   bool NeedSplit = false;
17896   switch (VT.getSimpleVT().SimpleTy) {
17897   default: return std::make_pair(0, false);
17898   case MVT::v32i8:
17899   case MVT::v16i16:
17900   case MVT::v8i32:
17901     if (!Subtarget->hasAVX2())
17902       NeedSplit = true;
17903     if (!Subtarget->hasAVX())
17904       return std::make_pair(0, false);
17905     break;
17906   case MVT::v16i8:
17907   case MVT::v8i16:
17908   case MVT::v4i32:
17909     if (!Subtarget->hasSSE2())
17910       return std::make_pair(0, false);
17911   }
17912
17913   // SSE2 has only a small subset of the operations.
17914   bool hasUnsigned = Subtarget->hasSSE41() ||
17915                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17916   bool hasSigned = Subtarget->hasSSE41() ||
17917                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17918
17919   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17920
17921   unsigned Opc = 0;
17922   // Check for x CC y ? x : y.
17923   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17924       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17925     switch (CC) {
17926     default: break;
17927     case ISD::SETULT:
17928     case ISD::SETULE:
17929       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17930     case ISD::SETUGT:
17931     case ISD::SETUGE:
17932       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17933     case ISD::SETLT:
17934     case ISD::SETLE:
17935       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17936     case ISD::SETGT:
17937     case ISD::SETGE:
17938       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17939     }
17940   // Check for x CC y ? y : x -- a min/max with reversed arms.
17941   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17942              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17943     switch (CC) {
17944     default: break;
17945     case ISD::SETULT:
17946     case ISD::SETULE:
17947       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17948     case ISD::SETUGT:
17949     case ISD::SETUGE:
17950       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17951     case ISD::SETLT:
17952     case ISD::SETLE:
17953       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17954     case ISD::SETGT:
17955     case ISD::SETGE:
17956       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17957     }
17958   }
17959
17960   return std::make_pair(Opc, NeedSplit);
17961 }
17962
17963 static SDValue
17964 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17965                                       const X86Subtarget *Subtarget) {
17966   SDLoc dl(N);
17967   SDValue Cond = N->getOperand(0);
17968   SDValue LHS = N->getOperand(1);
17969   SDValue RHS = N->getOperand(2);
17970
17971   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17972     SDValue CondSrc = Cond->getOperand(0);
17973     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17974       Cond = CondSrc->getOperand(0);
17975   }
17976
17977   MVT VT = N->getSimpleValueType(0);
17978   MVT EltVT = VT.getVectorElementType();
17979   unsigned NumElems = VT.getVectorNumElements();
17980   // There is no blend with immediate in AVX-512.
17981   if (VT.is512BitVector())
17982     return SDValue();
17983
17984   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17985     return SDValue();
17986   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17987     return SDValue();
17988
17989   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17990     return SDValue();
17991
17992   unsigned MaskValue = 0;
17993   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
17994     return SDValue();
17995
17996   SmallVector<int, 8> ShuffleMask(NumElems, -1);
17997   for (unsigned i = 0; i < NumElems; ++i) {
17998     // Be sure we emit undef where we can.
17999     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18000       ShuffleMask[i] = -1;
18001     else
18002       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18003   }
18004
18005   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18006 }
18007
18008 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18009 /// nodes.
18010 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18011                                     TargetLowering::DAGCombinerInfo &DCI,
18012                                     const X86Subtarget *Subtarget) {
18013   SDLoc DL(N);
18014   SDValue Cond = N->getOperand(0);
18015   // Get the LHS/RHS of the select.
18016   SDValue LHS = N->getOperand(1);
18017   SDValue RHS = N->getOperand(2);
18018   EVT VT = LHS.getValueType();
18019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18020
18021   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18022   // instructions match the semantics of the common C idiom x<y?x:y but not
18023   // x<=y?x:y, because of how they handle negative zero (which can be
18024   // ignored in unsafe-math mode).
18025   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18026       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18027       (Subtarget->hasSSE2() ||
18028        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18029     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18030
18031     unsigned Opcode = 0;
18032     // Check for x CC y ? x : y.
18033     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18034         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18035       switch (CC) {
18036       default: break;
18037       case ISD::SETULT:
18038         // Converting this to a min would handle NaNs incorrectly, and swapping
18039         // the operands would cause it to handle comparisons between positive
18040         // and negative zero incorrectly.
18041         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18042           if (!DAG.getTarget().Options.UnsafeFPMath &&
18043               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18044             break;
18045           std::swap(LHS, RHS);
18046         }
18047         Opcode = X86ISD::FMIN;
18048         break;
18049       case ISD::SETOLE:
18050         // Converting this to a min would handle comparisons between positive
18051         // and negative zero incorrectly.
18052         if (!DAG.getTarget().Options.UnsafeFPMath &&
18053             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18054           break;
18055         Opcode = X86ISD::FMIN;
18056         break;
18057       case ISD::SETULE:
18058         // Converting this to a min would handle both negative zeros and NaNs
18059         // incorrectly, but we can swap the operands to fix both.
18060         std::swap(LHS, RHS);
18061       case ISD::SETOLT:
18062       case ISD::SETLT:
18063       case ISD::SETLE:
18064         Opcode = X86ISD::FMIN;
18065         break;
18066
18067       case ISD::SETOGE:
18068         // Converting this to a max would handle comparisons between positive
18069         // and negative zero incorrectly.
18070         if (!DAG.getTarget().Options.UnsafeFPMath &&
18071             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18072           break;
18073         Opcode = X86ISD::FMAX;
18074         break;
18075       case ISD::SETUGT:
18076         // Converting this to a max would handle NaNs incorrectly, and swapping
18077         // the operands would cause it to handle comparisons between positive
18078         // and negative zero incorrectly.
18079         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18080           if (!DAG.getTarget().Options.UnsafeFPMath &&
18081               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18082             break;
18083           std::swap(LHS, RHS);
18084         }
18085         Opcode = X86ISD::FMAX;
18086         break;
18087       case ISD::SETUGE:
18088         // Converting this to a max would handle both negative zeros and NaNs
18089         // incorrectly, but we can swap the operands to fix both.
18090         std::swap(LHS, RHS);
18091       case ISD::SETOGT:
18092       case ISD::SETGT:
18093       case ISD::SETGE:
18094         Opcode = X86ISD::FMAX;
18095         break;
18096       }
18097     // Check for x CC y ? y : x -- a min/max with reversed arms.
18098     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18099                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18100       switch (CC) {
18101       default: break;
18102       case ISD::SETOGE:
18103         // Converting this to a min would handle comparisons between positive
18104         // and negative zero incorrectly, and swapping the operands would
18105         // cause it to handle NaNs incorrectly.
18106         if (!DAG.getTarget().Options.UnsafeFPMath &&
18107             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18108           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18109             break;
18110           std::swap(LHS, RHS);
18111         }
18112         Opcode = X86ISD::FMIN;
18113         break;
18114       case ISD::SETUGT:
18115         // Converting this to a min would handle NaNs incorrectly.
18116         if (!DAG.getTarget().Options.UnsafeFPMath &&
18117             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18118           break;
18119         Opcode = X86ISD::FMIN;
18120         break;
18121       case ISD::SETUGE:
18122         // Converting this to a min would handle both negative zeros and NaNs
18123         // incorrectly, but we can swap the operands to fix both.
18124         std::swap(LHS, RHS);
18125       case ISD::SETOGT:
18126       case ISD::SETGT:
18127       case ISD::SETGE:
18128         Opcode = X86ISD::FMIN;
18129         break;
18130
18131       case ISD::SETULT:
18132         // Converting this to a max would handle NaNs incorrectly.
18133         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18134           break;
18135         Opcode = X86ISD::FMAX;
18136         break;
18137       case ISD::SETOLE:
18138         // Converting this to a max would handle comparisons between positive
18139         // and negative zero incorrectly, and swapping the operands would
18140         // cause it to handle NaNs incorrectly.
18141         if (!DAG.getTarget().Options.UnsafeFPMath &&
18142             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18143           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18144             break;
18145           std::swap(LHS, RHS);
18146         }
18147         Opcode = X86ISD::FMAX;
18148         break;
18149       case ISD::SETULE:
18150         // Converting this to a max would handle both negative zeros and NaNs
18151         // incorrectly, but we can swap the operands to fix both.
18152         std::swap(LHS, RHS);
18153       case ISD::SETOLT:
18154       case ISD::SETLT:
18155       case ISD::SETLE:
18156         Opcode = X86ISD::FMAX;
18157         break;
18158       }
18159     }
18160
18161     if (Opcode)
18162       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18163   }
18164
18165   EVT CondVT = Cond.getValueType();
18166   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18167       CondVT.getVectorElementType() == MVT::i1) {
18168     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18169     // lowering on AVX-512. In this case we convert it to
18170     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18171     // The same situation for all 128 and 256-bit vectors of i8 and i16
18172     EVT OpVT = LHS.getValueType();
18173     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18174         (OpVT.getVectorElementType() == MVT::i8 ||
18175          OpVT.getVectorElementType() == MVT::i16)) {
18176       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18177       DCI.AddToWorklist(Cond.getNode());
18178       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18179     }
18180   }
18181   // If this is a select between two integer constants, try to do some
18182   // optimizations.
18183   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18184     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18185       // Don't do this for crazy integer types.
18186       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18187         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18188         // so that TrueC (the true value) is larger than FalseC.
18189         bool NeedsCondInvert = false;
18190
18191         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18192             // Efficiently invertible.
18193             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
18194              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
18195               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18196           NeedsCondInvert = true;
18197           std::swap(TrueC, FalseC);
18198         }
18199
18200         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18201         if (FalseC->getAPIntValue() == 0 &&
18202             TrueC->getAPIntValue().isPowerOf2()) {
18203           if (NeedsCondInvert) // Invert the condition if needed.
18204             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18205                                DAG.getConstant(1, Cond.getValueType()));
18206
18207           // Zero extend the condition if needed.
18208           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18209
18210           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18211           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18212                              DAG.getConstant(ShAmt, MVT::i8));
18213         }
18214
18215         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18216         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18217           if (NeedsCondInvert) // Invert the condition if needed.
18218             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18219                                DAG.getConstant(1, Cond.getValueType()));
18220
18221           // Zero extend the condition if needed.
18222           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18223                              FalseC->getValueType(0), Cond);
18224           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18225                              SDValue(FalseC, 0));
18226         }
18227
18228         // Optimize cases that will turn into an LEA instruction.  This requires
18229         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18230         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18231           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18232           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18233
18234           bool isFastMultiplier = false;
18235           if (Diff < 10) {
18236             switch ((unsigned char)Diff) {
18237               default: break;
18238               case 1:  // result = add base, cond
18239               case 2:  // result = lea base(    , cond*2)
18240               case 3:  // result = lea base(cond, cond*2)
18241               case 4:  // result = lea base(    , cond*4)
18242               case 5:  // result = lea base(cond, cond*4)
18243               case 8:  // result = lea base(    , cond*8)
18244               case 9:  // result = lea base(cond, cond*8)
18245                 isFastMultiplier = true;
18246                 break;
18247             }
18248           }
18249
18250           if (isFastMultiplier) {
18251             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18252             if (NeedsCondInvert) // Invert the condition if needed.
18253               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18254                                  DAG.getConstant(1, Cond.getValueType()));
18255
18256             // Zero extend the condition if needed.
18257             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18258                                Cond);
18259             // Scale the condition by the difference.
18260             if (Diff != 1)
18261               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18262                                  DAG.getConstant(Diff, Cond.getValueType()));
18263
18264             // Add the base if non-zero.
18265             if (FalseC->getAPIntValue() != 0)
18266               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18267                                  SDValue(FalseC, 0));
18268             return Cond;
18269           }
18270         }
18271       }
18272   }
18273
18274   // Canonicalize max and min:
18275   // (x > y) ? x : y -> (x >= y) ? x : y
18276   // (x < y) ? x : y -> (x <= y) ? x : y
18277   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18278   // the need for an extra compare
18279   // against zero. e.g.
18280   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18281   // subl   %esi, %edi
18282   // testl  %edi, %edi
18283   // movl   $0, %eax
18284   // cmovgl %edi, %eax
18285   // =>
18286   // xorl   %eax, %eax
18287   // subl   %esi, $edi
18288   // cmovsl %eax, %edi
18289   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18290       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18291       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18292     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18293     switch (CC) {
18294     default: break;
18295     case ISD::SETLT:
18296     case ISD::SETGT: {
18297       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18298       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18299                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18300       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18301     }
18302     }
18303   }
18304
18305   // Early exit check
18306   if (!TLI.isTypeLegal(VT))
18307     return SDValue();
18308
18309   // Match VSELECTs into subs with unsigned saturation.
18310   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18311       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18312       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18313        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18314     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18315
18316     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18317     // left side invert the predicate to simplify logic below.
18318     SDValue Other;
18319     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18320       Other = RHS;
18321       CC = ISD::getSetCCInverse(CC, true);
18322     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18323       Other = LHS;
18324     }
18325
18326     if (Other.getNode() && Other->getNumOperands() == 2 &&
18327         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18328       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18329       SDValue CondRHS = Cond->getOperand(1);
18330
18331       // Look for a general sub with unsigned saturation first.
18332       // x >= y ? x-y : 0 --> subus x, y
18333       // x >  y ? x-y : 0 --> subus x, y
18334       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18335           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18336         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18337
18338       // If the RHS is a constant we have to reverse the const canonicalization.
18339       // x > C-1 ? x+-C : 0 --> subus x, C
18340       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18341           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18342         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18343         if (CondRHS.getConstantOperandVal(0) == -A-1)
18344           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18345                              DAG.getConstant(-A, VT));
18346       }
18347
18348       // Another special case: If C was a sign bit, the sub has been
18349       // canonicalized into a xor.
18350       // FIXME: Would it be better to use computeKnownBits to determine whether
18351       //        it's safe to decanonicalize the xor?
18352       // x s< 0 ? x^C : 0 --> subus x, C
18353       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18354           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18355           isSplatVector(OpRHS.getNode())) {
18356         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18357         if (A.isSignBit())
18358           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18359       }
18360     }
18361   }
18362
18363   // Try to match a min/max vector operation.
18364   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18365     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18366     unsigned Opc = ret.first;
18367     bool NeedSplit = ret.second;
18368
18369     if (Opc && NeedSplit) {
18370       unsigned NumElems = VT.getVectorNumElements();
18371       // Extract the LHS vectors
18372       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18373       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18374
18375       // Extract the RHS vectors
18376       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18377       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18378
18379       // Create min/max for each subvector
18380       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18381       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18382
18383       // Merge the result
18384       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18385     } else if (Opc)
18386       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18387   }
18388
18389   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18390   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18391       // Check if SETCC has already been promoted
18392       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18393       // Check that condition value type matches vselect operand type
18394       CondVT == VT) { 
18395
18396     assert(Cond.getValueType().isVector() &&
18397            "vector select expects a vector selector!");
18398
18399     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18400     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18401
18402     if (!TValIsAllOnes && !FValIsAllZeros) {
18403       // Try invert the condition if true value is not all 1s and false value
18404       // is not all 0s.
18405       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18406       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18407
18408       if (TValIsAllZeros || FValIsAllOnes) {
18409         SDValue CC = Cond.getOperand(2);
18410         ISD::CondCode NewCC =
18411           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18412                                Cond.getOperand(0).getValueType().isInteger());
18413         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18414         std::swap(LHS, RHS);
18415         TValIsAllOnes = FValIsAllOnes;
18416         FValIsAllZeros = TValIsAllZeros;
18417       }
18418     }
18419
18420     if (TValIsAllOnes || FValIsAllZeros) {
18421       SDValue Ret;
18422
18423       if (TValIsAllOnes && FValIsAllZeros)
18424         Ret = Cond;
18425       else if (TValIsAllOnes)
18426         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18427                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18428       else if (FValIsAllZeros)
18429         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18430                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18431
18432       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18433     }
18434   }
18435
18436   // Try to fold this VSELECT into a MOVSS/MOVSD
18437   if (N->getOpcode() == ISD::VSELECT &&
18438       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18439     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18440         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18441       bool CanFold = false;
18442       unsigned NumElems = Cond.getNumOperands();
18443       SDValue A = LHS;
18444       SDValue B = RHS;
18445       
18446       if (isZero(Cond.getOperand(0))) {
18447         CanFold = true;
18448
18449         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18450         // fold (vselect <0,-1> -> (movsd A, B)
18451         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18452           CanFold = isAllOnes(Cond.getOperand(i));
18453       } else if (isAllOnes(Cond.getOperand(0))) {
18454         CanFold = true;
18455         std::swap(A, B);
18456
18457         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18458         // fold (vselect <-1,0> -> (movsd B, A)
18459         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18460           CanFold = isZero(Cond.getOperand(i));
18461       }
18462
18463       if (CanFold) {
18464         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18465           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18466         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18467       }
18468
18469       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18470         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18471         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18472         //                             (v2i64 (bitcast B)))))
18473         //
18474         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18475         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18476         //                             (v2f64 (bitcast B)))))
18477         //
18478         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18479         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18480         //                             (v2i64 (bitcast A)))))
18481         //
18482         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18483         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18484         //                             (v2f64 (bitcast A)))))
18485
18486         CanFold = (isZero(Cond.getOperand(0)) &&
18487                    isZero(Cond.getOperand(1)) &&
18488                    isAllOnes(Cond.getOperand(2)) &&
18489                    isAllOnes(Cond.getOperand(3)));
18490
18491         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18492             isAllOnes(Cond.getOperand(1)) &&
18493             isZero(Cond.getOperand(2)) &&
18494             isZero(Cond.getOperand(3))) {
18495           CanFold = true;
18496           std::swap(LHS, RHS);
18497         }
18498
18499         if (CanFold) {
18500           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18501           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18502           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18503           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18504                                                 NewB, DAG);
18505           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18506         }
18507       }
18508     }
18509   }
18510
18511   // If we know that this node is legal then we know that it is going to be
18512   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18513   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18514   // to simplify previous instructions.
18515   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18516       !DCI.isBeforeLegalize() &&
18517       // We explicitly check against v8i16 and v16i16 because, although
18518       // they're marked as Custom, they might only be legal when Cond is a
18519       // build_vector of constants. This will be taken care in a later
18520       // condition.
18521       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18522        VT != MVT::v8i16)) {
18523     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18524
18525     // Don't optimize vector selects that map to mask-registers.
18526     if (BitWidth == 1)
18527       return SDValue();
18528
18529     // Check all uses of that condition operand to check whether it will be
18530     // consumed by non-BLEND instructions, which may depend on all bits are set
18531     // properly.
18532     for (SDNode::use_iterator I = Cond->use_begin(),
18533                               E = Cond->use_end(); I != E; ++I)
18534       if (I->getOpcode() != ISD::VSELECT)
18535         // TODO: Add other opcodes eventually lowered into BLEND.
18536         return SDValue();
18537
18538     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18539     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18540
18541     APInt KnownZero, KnownOne;
18542     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18543                                           DCI.isBeforeLegalizeOps());
18544     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18545         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18546       DCI.CommitTargetLoweringOpt(TLO);
18547   }
18548
18549   // We should generate an X86ISD::BLENDI from a vselect if its argument
18550   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18551   // constants. This specific pattern gets generated when we split a
18552   // selector for a 512 bit vector in a machine without AVX512 (but with
18553   // 256-bit vectors), during legalization:
18554   //
18555   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18556   //
18557   // Iff we find this pattern and the build_vectors are built from
18558   // constants, we translate the vselect into a shuffle_vector that we
18559   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18560   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18561     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18562     if (Shuffle.getNode())
18563       return Shuffle;
18564   }
18565
18566   return SDValue();
18567 }
18568
18569 // Check whether a boolean test is testing a boolean value generated by
18570 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18571 // code.
18572 //
18573 // Simplify the following patterns:
18574 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18575 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18576 // to (Op EFLAGS Cond)
18577 //
18578 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18579 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18580 // to (Op EFLAGS !Cond)
18581 //
18582 // where Op could be BRCOND or CMOV.
18583 //
18584 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18585   // Quit if not CMP and SUB with its value result used.
18586   if (Cmp.getOpcode() != X86ISD::CMP &&
18587       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18588       return SDValue();
18589
18590   // Quit if not used as a boolean value.
18591   if (CC != X86::COND_E && CC != X86::COND_NE)
18592     return SDValue();
18593
18594   // Check CMP operands. One of them should be 0 or 1 and the other should be
18595   // an SetCC or extended from it.
18596   SDValue Op1 = Cmp.getOperand(0);
18597   SDValue Op2 = Cmp.getOperand(1);
18598
18599   SDValue SetCC;
18600   const ConstantSDNode* C = nullptr;
18601   bool needOppositeCond = (CC == X86::COND_E);
18602   bool checkAgainstTrue = false; // Is it a comparison against 1?
18603
18604   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18605     SetCC = Op2;
18606   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18607     SetCC = Op1;
18608   else // Quit if all operands are not constants.
18609     return SDValue();
18610
18611   if (C->getZExtValue() == 1) {
18612     needOppositeCond = !needOppositeCond;
18613     checkAgainstTrue = true;
18614   } else if (C->getZExtValue() != 0)
18615     // Quit if the constant is neither 0 or 1.
18616     return SDValue();
18617
18618   bool truncatedToBoolWithAnd = false;
18619   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18620   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18621          SetCC.getOpcode() == ISD::TRUNCATE ||
18622          SetCC.getOpcode() == ISD::AND) {
18623     if (SetCC.getOpcode() == ISD::AND) {
18624       int OpIdx = -1;
18625       ConstantSDNode *CS;
18626       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18627           CS->getZExtValue() == 1)
18628         OpIdx = 1;
18629       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18630           CS->getZExtValue() == 1)
18631         OpIdx = 0;
18632       if (OpIdx == -1)
18633         break;
18634       SetCC = SetCC.getOperand(OpIdx);
18635       truncatedToBoolWithAnd = true;
18636     } else
18637       SetCC = SetCC.getOperand(0);
18638   }
18639
18640   switch (SetCC.getOpcode()) {
18641   case X86ISD::SETCC_CARRY:
18642     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18643     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18644     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18645     // truncated to i1 using 'and'.
18646     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18647       break;
18648     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18649            "Invalid use of SETCC_CARRY!");
18650     // FALL THROUGH
18651   case X86ISD::SETCC:
18652     // Set the condition code or opposite one if necessary.
18653     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18654     if (needOppositeCond)
18655       CC = X86::GetOppositeBranchCondition(CC);
18656     return SetCC.getOperand(1);
18657   case X86ISD::CMOV: {
18658     // Check whether false/true value has canonical one, i.e. 0 or 1.
18659     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18660     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18661     // Quit if true value is not a constant.
18662     if (!TVal)
18663       return SDValue();
18664     // Quit if false value is not a constant.
18665     if (!FVal) {
18666       SDValue Op = SetCC.getOperand(0);
18667       // Skip 'zext' or 'trunc' node.
18668       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18669           Op.getOpcode() == ISD::TRUNCATE)
18670         Op = Op.getOperand(0);
18671       // A special case for rdrand/rdseed, where 0 is set if false cond is
18672       // found.
18673       if ((Op.getOpcode() != X86ISD::RDRAND &&
18674            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18675         return SDValue();
18676     }
18677     // Quit if false value is not the constant 0 or 1.
18678     bool FValIsFalse = true;
18679     if (FVal && FVal->getZExtValue() != 0) {
18680       if (FVal->getZExtValue() != 1)
18681         return SDValue();
18682       // If FVal is 1, opposite cond is needed.
18683       needOppositeCond = !needOppositeCond;
18684       FValIsFalse = false;
18685     }
18686     // Quit if TVal is not the constant opposite of FVal.
18687     if (FValIsFalse && TVal->getZExtValue() != 1)
18688       return SDValue();
18689     if (!FValIsFalse && TVal->getZExtValue() != 0)
18690       return SDValue();
18691     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18692     if (needOppositeCond)
18693       CC = X86::GetOppositeBranchCondition(CC);
18694     return SetCC.getOperand(3);
18695   }
18696   }
18697
18698   return SDValue();
18699 }
18700
18701 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18702 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18703                                   TargetLowering::DAGCombinerInfo &DCI,
18704                                   const X86Subtarget *Subtarget) {
18705   SDLoc DL(N);
18706
18707   // If the flag operand isn't dead, don't touch this CMOV.
18708   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18709     return SDValue();
18710
18711   SDValue FalseOp = N->getOperand(0);
18712   SDValue TrueOp = N->getOperand(1);
18713   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18714   SDValue Cond = N->getOperand(3);
18715
18716   if (CC == X86::COND_E || CC == X86::COND_NE) {
18717     switch (Cond.getOpcode()) {
18718     default: break;
18719     case X86ISD::BSR:
18720     case X86ISD::BSF:
18721       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18722       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18723         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18724     }
18725   }
18726
18727   SDValue Flags;
18728
18729   Flags = checkBoolTestSetCCCombine(Cond, CC);
18730   if (Flags.getNode() &&
18731       // Extra check as FCMOV only supports a subset of X86 cond.
18732       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18733     SDValue Ops[] = { FalseOp, TrueOp,
18734                       DAG.getConstant(CC, MVT::i8), Flags };
18735     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18736   }
18737
18738   // If this is a select between two integer constants, try to do some
18739   // optimizations.  Note that the operands are ordered the opposite of SELECT
18740   // operands.
18741   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18742     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18743       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18744       // larger than FalseC (the false value).
18745       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18746         CC = X86::GetOppositeBranchCondition(CC);
18747         std::swap(TrueC, FalseC);
18748         std::swap(TrueOp, FalseOp);
18749       }
18750
18751       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18752       // This is efficient for any integer data type (including i8/i16) and
18753       // shift amount.
18754       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18755         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18756                            DAG.getConstant(CC, MVT::i8), Cond);
18757
18758         // Zero extend the condition if needed.
18759         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18760
18761         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18762         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18763                            DAG.getConstant(ShAmt, MVT::i8));
18764         if (N->getNumValues() == 2)  // Dead flag value?
18765           return DCI.CombineTo(N, Cond, SDValue());
18766         return Cond;
18767       }
18768
18769       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18770       // for any integer data type, including i8/i16.
18771       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18772         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18773                            DAG.getConstant(CC, MVT::i8), Cond);
18774
18775         // Zero extend the condition if needed.
18776         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18777                            FalseC->getValueType(0), Cond);
18778         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18779                            SDValue(FalseC, 0));
18780
18781         if (N->getNumValues() == 2)  // Dead flag value?
18782           return DCI.CombineTo(N, Cond, SDValue());
18783         return Cond;
18784       }
18785
18786       // Optimize cases that will turn into an LEA instruction.  This requires
18787       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18788       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18789         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18790         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18791
18792         bool isFastMultiplier = false;
18793         if (Diff < 10) {
18794           switch ((unsigned char)Diff) {
18795           default: break;
18796           case 1:  // result = add base, cond
18797           case 2:  // result = lea base(    , cond*2)
18798           case 3:  // result = lea base(cond, cond*2)
18799           case 4:  // result = lea base(    , cond*4)
18800           case 5:  // result = lea base(cond, cond*4)
18801           case 8:  // result = lea base(    , cond*8)
18802           case 9:  // result = lea base(cond, cond*8)
18803             isFastMultiplier = true;
18804             break;
18805           }
18806         }
18807
18808         if (isFastMultiplier) {
18809           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18810           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18811                              DAG.getConstant(CC, MVT::i8), Cond);
18812           // Zero extend the condition if needed.
18813           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18814                              Cond);
18815           // Scale the condition by the difference.
18816           if (Diff != 1)
18817             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18818                                DAG.getConstant(Diff, Cond.getValueType()));
18819
18820           // Add the base if non-zero.
18821           if (FalseC->getAPIntValue() != 0)
18822             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18823                                SDValue(FalseC, 0));
18824           if (N->getNumValues() == 2)  // Dead flag value?
18825             return DCI.CombineTo(N, Cond, SDValue());
18826           return Cond;
18827         }
18828       }
18829     }
18830   }
18831
18832   // Handle these cases:
18833   //   (select (x != c), e, c) -> select (x != c), e, x),
18834   //   (select (x == c), c, e) -> select (x == c), x, e)
18835   // where the c is an integer constant, and the "select" is the combination
18836   // of CMOV and CMP.
18837   //
18838   // The rationale for this change is that the conditional-move from a constant
18839   // needs two instructions, however, conditional-move from a register needs
18840   // only one instruction.
18841   //
18842   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18843   //  some instruction-combining opportunities. This opt needs to be
18844   //  postponed as late as possible.
18845   //
18846   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18847     // the DCI.xxxx conditions are provided to postpone the optimization as
18848     // late as possible.
18849
18850     ConstantSDNode *CmpAgainst = nullptr;
18851     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18852         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18853         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18854
18855       if (CC == X86::COND_NE &&
18856           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18857         CC = X86::GetOppositeBranchCondition(CC);
18858         std::swap(TrueOp, FalseOp);
18859       }
18860
18861       if (CC == X86::COND_E &&
18862           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18863         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18864                           DAG.getConstant(CC, MVT::i8), Cond };
18865         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18866       }
18867     }
18868   }
18869
18870   return SDValue();
18871 }
18872
18873 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18874                                                 const X86Subtarget *Subtarget) {
18875   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18876   switch (IntNo) {
18877   default: return SDValue();
18878   // SSE/AVX/AVX2 blend intrinsics.
18879   case Intrinsic::x86_avx2_pblendvb:
18880   case Intrinsic::x86_avx2_pblendw:
18881   case Intrinsic::x86_avx2_pblendd_128:
18882   case Intrinsic::x86_avx2_pblendd_256:
18883     // Don't try to simplify this intrinsic if we don't have AVX2.
18884     if (!Subtarget->hasAVX2())
18885       return SDValue();
18886     // FALL-THROUGH
18887   case Intrinsic::x86_avx_blend_pd_256:
18888   case Intrinsic::x86_avx_blend_ps_256:
18889   case Intrinsic::x86_avx_blendv_pd_256:
18890   case Intrinsic::x86_avx_blendv_ps_256:
18891     // Don't try to simplify this intrinsic if we don't have AVX.
18892     if (!Subtarget->hasAVX())
18893       return SDValue();
18894     // FALL-THROUGH
18895   case Intrinsic::x86_sse41_pblendw:
18896   case Intrinsic::x86_sse41_blendpd:
18897   case Intrinsic::x86_sse41_blendps:
18898   case Intrinsic::x86_sse41_blendvps:
18899   case Intrinsic::x86_sse41_blendvpd:
18900   case Intrinsic::x86_sse41_pblendvb: {
18901     SDValue Op0 = N->getOperand(1);
18902     SDValue Op1 = N->getOperand(2);
18903     SDValue Mask = N->getOperand(3);
18904
18905     // Don't try to simplify this intrinsic if we don't have SSE4.1.
18906     if (!Subtarget->hasSSE41())
18907       return SDValue();
18908
18909     // fold (blend A, A, Mask) -> A
18910     if (Op0 == Op1)
18911       return Op0;
18912     // fold (blend A, B, allZeros) -> A
18913     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18914       return Op0;
18915     // fold (blend A, B, allOnes) -> B
18916     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18917       return Op1;
18918     
18919     // Simplify the case where the mask is a constant i32 value.
18920     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18921       if (C->isNullValue())
18922         return Op0;
18923       if (C->isAllOnesValue())
18924         return Op1;
18925     }
18926   }
18927
18928   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18929   case Intrinsic::x86_sse2_psrai_w:
18930   case Intrinsic::x86_sse2_psrai_d:
18931   case Intrinsic::x86_avx2_psrai_w:
18932   case Intrinsic::x86_avx2_psrai_d:
18933   case Intrinsic::x86_sse2_psra_w:
18934   case Intrinsic::x86_sse2_psra_d:
18935   case Intrinsic::x86_avx2_psra_w:
18936   case Intrinsic::x86_avx2_psra_d: {
18937     SDValue Op0 = N->getOperand(1);
18938     SDValue Op1 = N->getOperand(2);
18939     EVT VT = Op0.getValueType();
18940     assert(VT.isVector() && "Expected a vector type!");
18941
18942     if (isa<BuildVectorSDNode>(Op1))
18943       Op1 = Op1.getOperand(0);
18944
18945     if (!isa<ConstantSDNode>(Op1))
18946       return SDValue();
18947
18948     EVT SVT = VT.getVectorElementType();
18949     unsigned SVTBits = SVT.getSizeInBits();
18950
18951     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18952     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18953     uint64_t ShAmt = C.getZExtValue();
18954
18955     // Don't try to convert this shift into a ISD::SRA if the shift
18956     // count is bigger than or equal to the element size.
18957     if (ShAmt >= SVTBits)
18958       return SDValue();
18959
18960     // Trivial case: if the shift count is zero, then fold this
18961     // into the first operand.
18962     if (ShAmt == 0)
18963       return Op0;
18964
18965     // Replace this packed shift intrinsic with a target independent
18966     // shift dag node.
18967     SDValue Splat = DAG.getConstant(C, VT);
18968     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18969   }
18970   }
18971 }
18972
18973 /// PerformMulCombine - Optimize a single multiply with constant into two
18974 /// in order to implement it with two cheaper instructions, e.g.
18975 /// LEA + SHL, LEA + LEA.
18976 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18977                                  TargetLowering::DAGCombinerInfo &DCI) {
18978   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18979     return SDValue();
18980
18981   EVT VT = N->getValueType(0);
18982   if (VT != MVT::i64)
18983     return SDValue();
18984
18985   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18986   if (!C)
18987     return SDValue();
18988   uint64_t MulAmt = C->getZExtValue();
18989   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18990     return SDValue();
18991
18992   uint64_t MulAmt1 = 0;
18993   uint64_t MulAmt2 = 0;
18994   if ((MulAmt % 9) == 0) {
18995     MulAmt1 = 9;
18996     MulAmt2 = MulAmt / 9;
18997   } else if ((MulAmt % 5) == 0) {
18998     MulAmt1 = 5;
18999     MulAmt2 = MulAmt / 5;
19000   } else if ((MulAmt % 3) == 0) {
19001     MulAmt1 = 3;
19002     MulAmt2 = MulAmt / 3;
19003   }
19004   if (MulAmt2 &&
19005       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19006     SDLoc DL(N);
19007
19008     if (isPowerOf2_64(MulAmt2) &&
19009         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19010       // If second multiplifer is pow2, issue it first. We want the multiply by
19011       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19012       // is an add.
19013       std::swap(MulAmt1, MulAmt2);
19014
19015     SDValue NewMul;
19016     if (isPowerOf2_64(MulAmt1))
19017       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19018                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19019     else
19020       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19021                            DAG.getConstant(MulAmt1, VT));
19022
19023     if (isPowerOf2_64(MulAmt2))
19024       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19025                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19026     else
19027       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19028                            DAG.getConstant(MulAmt2, VT));
19029
19030     // Do not add new nodes to DAG combiner worklist.
19031     DCI.CombineTo(N, NewMul, false);
19032   }
19033   return SDValue();
19034 }
19035
19036 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19037   SDValue N0 = N->getOperand(0);
19038   SDValue N1 = N->getOperand(1);
19039   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19040   EVT VT = N0.getValueType();
19041
19042   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19043   // since the result of setcc_c is all zero's or all ones.
19044   if (VT.isInteger() && !VT.isVector() &&
19045       N1C && N0.getOpcode() == ISD::AND &&
19046       N0.getOperand(1).getOpcode() == ISD::Constant) {
19047     SDValue N00 = N0.getOperand(0);
19048     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19049         ((N00.getOpcode() == ISD::ANY_EXTEND ||
19050           N00.getOpcode() == ISD::ZERO_EXTEND) &&
19051          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19052       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19053       APInt ShAmt = N1C->getAPIntValue();
19054       Mask = Mask.shl(ShAmt);
19055       if (Mask != 0)
19056         return DAG.getNode(ISD::AND, SDLoc(N), VT,
19057                            N00, DAG.getConstant(Mask, VT));
19058     }
19059   }
19060
19061   // Hardware support for vector shifts is sparse which makes us scalarize the
19062   // vector operations in many cases. Also, on sandybridge ADD is faster than
19063   // shl.
19064   // (shl V, 1) -> add V,V
19065   if (isSplatVector(N1.getNode())) {
19066     assert(N0.getValueType().isVector() && "Invalid vector shift type");
19067     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19068     // We shift all of the values by one. In many cases we do not have
19069     // hardware support for this operation. This is better expressed as an ADD
19070     // of two values.
19071     if (N1C && (1 == N1C->getZExtValue())) {
19072       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19073     }
19074   }
19075
19076   return SDValue();
19077 }
19078
19079 /// \brief Returns a vector of 0s if the node in input is a vector logical
19080 /// shift by a constant amount which is known to be bigger than or equal
19081 /// to the vector element size in bits.
19082 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19083                                       const X86Subtarget *Subtarget) {
19084   EVT VT = N->getValueType(0);
19085
19086   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19087       (!Subtarget->hasInt256() ||
19088        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19089     return SDValue();
19090
19091   SDValue Amt = N->getOperand(1);
19092   SDLoc DL(N);
19093   if (isSplatVector(Amt.getNode())) {
19094     SDValue SclrAmt = Amt->getOperand(0);
19095     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19096       APInt ShiftAmt = C->getAPIntValue();
19097       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19098
19099       // SSE2/AVX2 logical shifts always return a vector of 0s
19100       // if the shift amount is bigger than or equal to
19101       // the element size. The constant shift amount will be
19102       // encoded as a 8-bit immediate.
19103       if (ShiftAmt.trunc(8).uge(MaxAmount))
19104         return getZeroVector(VT, Subtarget, DAG, DL);
19105     }
19106   }
19107
19108   return SDValue();
19109 }
19110
19111 /// PerformShiftCombine - Combine shifts.
19112 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19113                                    TargetLowering::DAGCombinerInfo &DCI,
19114                                    const X86Subtarget *Subtarget) {
19115   if (N->getOpcode() == ISD::SHL) {
19116     SDValue V = PerformSHLCombine(N, DAG);
19117     if (V.getNode()) return V;
19118   }
19119
19120   if (N->getOpcode() != ISD::SRA) {
19121     // Try to fold this logical shift into a zero vector.
19122     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19123     if (V.getNode()) return V;
19124   }
19125
19126   return SDValue();
19127 }
19128
19129 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
19130 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19131 // and friends.  Likewise for OR -> CMPNEQSS.
19132 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19133                             TargetLowering::DAGCombinerInfo &DCI,
19134                             const X86Subtarget *Subtarget) {
19135   unsigned opcode;
19136
19137   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19138   // we're requiring SSE2 for both.
19139   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19140     SDValue N0 = N->getOperand(0);
19141     SDValue N1 = N->getOperand(1);
19142     SDValue CMP0 = N0->getOperand(1);
19143     SDValue CMP1 = N1->getOperand(1);
19144     SDLoc DL(N);
19145
19146     // The SETCCs should both refer to the same CMP.
19147     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19148       return SDValue();
19149
19150     SDValue CMP00 = CMP0->getOperand(0);
19151     SDValue CMP01 = CMP0->getOperand(1);
19152     EVT     VT    = CMP00.getValueType();
19153
19154     if (VT == MVT::f32 || VT == MVT::f64) {
19155       bool ExpectingFlags = false;
19156       // Check for any users that want flags:
19157       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19158            !ExpectingFlags && UI != UE; ++UI)
19159         switch (UI->getOpcode()) {
19160         default:
19161         case ISD::BR_CC:
19162         case ISD::BRCOND:
19163         case ISD::SELECT:
19164           ExpectingFlags = true;
19165           break;
19166         case ISD::CopyToReg:
19167         case ISD::SIGN_EXTEND:
19168         case ISD::ZERO_EXTEND:
19169         case ISD::ANY_EXTEND:
19170           break;
19171         }
19172
19173       if (!ExpectingFlags) {
19174         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19175         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19176
19177         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19178           X86::CondCode tmp = cc0;
19179           cc0 = cc1;
19180           cc1 = tmp;
19181         }
19182
19183         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
19184             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19185           // FIXME: need symbolic constants for these magic numbers.
19186           // See X86ATTInstPrinter.cpp:printSSECC().
19187           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19188           if (Subtarget->hasAVX512()) {
19189             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19190                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
19191             if (N->getValueType(0) != MVT::i1)
19192               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19193                                  FSetCC);
19194             return FSetCC;
19195           }
19196           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19197                                               CMP00.getValueType(), CMP00, CMP01,
19198                                               DAG.getConstant(x86cc, MVT::i8));
19199
19200           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19201           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19202
19203           if (is64BitFP && !Subtarget->is64Bit()) {
19204             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19205             // 64-bit integer, since that's not a legal type. Since
19206             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19207             // bits, but can do this little dance to extract the lowest 32 bits
19208             // and work with those going forward.
19209             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19210                                            OnesOrZeroesF);
19211             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19212                                            Vector64);
19213             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19214                                         Vector32, DAG.getIntPtrConstant(0));
19215             IntVT = MVT::i32;
19216           }
19217
19218           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19219           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19220                                       DAG.getConstant(1, IntVT));
19221           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19222           return OneBitOfTruth;
19223         }
19224       }
19225     }
19226   }
19227   return SDValue();
19228 }
19229
19230 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19231 /// so it can be folded inside ANDNP.
19232 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19233   EVT VT = N->getValueType(0);
19234
19235   // Match direct AllOnes for 128 and 256-bit vectors
19236   if (ISD::isBuildVectorAllOnes(N))
19237     return true;
19238
19239   // Look through a bit convert.
19240   if (N->getOpcode() == ISD::BITCAST)
19241     N = N->getOperand(0).getNode();
19242
19243   // Sometimes the operand may come from a insert_subvector building a 256-bit
19244   // allones vector
19245   if (VT.is256BitVector() &&
19246       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19247     SDValue V1 = N->getOperand(0);
19248     SDValue V2 = N->getOperand(1);
19249
19250     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19251         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19252         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19253         ISD::isBuildVectorAllOnes(V2.getNode()))
19254       return true;
19255   }
19256
19257   return false;
19258 }
19259
19260 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19261 // register. In most cases we actually compare or select YMM-sized registers
19262 // and mixing the two types creates horrible code. This method optimizes
19263 // some of the transition sequences.
19264 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19265                                  TargetLowering::DAGCombinerInfo &DCI,
19266                                  const X86Subtarget *Subtarget) {
19267   EVT VT = N->getValueType(0);
19268   if (!VT.is256BitVector())
19269     return SDValue();
19270
19271   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19272           N->getOpcode() == ISD::ZERO_EXTEND ||
19273           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19274
19275   SDValue Narrow = N->getOperand(0);
19276   EVT NarrowVT = Narrow->getValueType(0);
19277   if (!NarrowVT.is128BitVector())
19278     return SDValue();
19279
19280   if (Narrow->getOpcode() != ISD::XOR &&
19281       Narrow->getOpcode() != ISD::AND &&
19282       Narrow->getOpcode() != ISD::OR)
19283     return SDValue();
19284
19285   SDValue N0  = Narrow->getOperand(0);
19286   SDValue N1  = Narrow->getOperand(1);
19287   SDLoc DL(Narrow);
19288
19289   // The Left side has to be a trunc.
19290   if (N0.getOpcode() != ISD::TRUNCATE)
19291     return SDValue();
19292
19293   // The type of the truncated inputs.
19294   EVT WideVT = N0->getOperand(0)->getValueType(0);
19295   if (WideVT != VT)
19296     return SDValue();
19297
19298   // The right side has to be a 'trunc' or a constant vector.
19299   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19300   bool RHSConst = (isSplatVector(N1.getNode()) &&
19301                    isa<ConstantSDNode>(N1->getOperand(0)));
19302   if (!RHSTrunc && !RHSConst)
19303     return SDValue();
19304
19305   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19306
19307   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19308     return SDValue();
19309
19310   // Set N0 and N1 to hold the inputs to the new wide operation.
19311   N0 = N0->getOperand(0);
19312   if (RHSConst) {
19313     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19314                      N1->getOperand(0));
19315     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19316     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19317   } else if (RHSTrunc) {
19318     N1 = N1->getOperand(0);
19319   }
19320
19321   // Generate the wide operation.
19322   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19323   unsigned Opcode = N->getOpcode();
19324   switch (Opcode) {
19325   case ISD::ANY_EXTEND:
19326     return Op;
19327   case ISD::ZERO_EXTEND: {
19328     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19329     APInt Mask = APInt::getAllOnesValue(InBits);
19330     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19331     return DAG.getNode(ISD::AND, DL, VT,
19332                        Op, DAG.getConstant(Mask, VT));
19333   }
19334   case ISD::SIGN_EXTEND:
19335     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19336                        Op, DAG.getValueType(NarrowVT));
19337   default:
19338     llvm_unreachable("Unexpected opcode");
19339   }
19340 }
19341
19342 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19343                                  TargetLowering::DAGCombinerInfo &DCI,
19344                                  const X86Subtarget *Subtarget) {
19345   EVT VT = N->getValueType(0);
19346   if (DCI.isBeforeLegalizeOps())
19347     return SDValue();
19348
19349   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19350   if (R.getNode())
19351     return R;
19352
19353   // Create BEXTR instructions
19354   // BEXTR is ((X >> imm) & (2**size-1))
19355   if (VT == MVT::i32 || VT == MVT::i64) {
19356     SDValue N0 = N->getOperand(0);
19357     SDValue N1 = N->getOperand(1);
19358     SDLoc DL(N);
19359
19360     // Check for BEXTR.
19361     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19362         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19363       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19364       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19365       if (MaskNode && ShiftNode) {
19366         uint64_t Mask = MaskNode->getZExtValue();
19367         uint64_t Shift = ShiftNode->getZExtValue();
19368         if (isMask_64(Mask)) {
19369           uint64_t MaskSize = CountPopulation_64(Mask);
19370           if (Shift + MaskSize <= VT.getSizeInBits())
19371             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19372                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19373         }
19374       }
19375     } // BEXTR
19376
19377     return SDValue();
19378   }
19379
19380   // Want to form ANDNP nodes:
19381   // 1) In the hopes of then easily combining them with OR and AND nodes
19382   //    to form PBLEND/PSIGN.
19383   // 2) To match ANDN packed intrinsics
19384   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19385     return SDValue();
19386
19387   SDValue N0 = N->getOperand(0);
19388   SDValue N1 = N->getOperand(1);
19389   SDLoc DL(N);
19390
19391   // Check LHS for vnot
19392   if (N0.getOpcode() == ISD::XOR &&
19393       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19394       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19395     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19396
19397   // Check RHS for vnot
19398   if (N1.getOpcode() == ISD::XOR &&
19399       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19400       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19401     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19402
19403   return SDValue();
19404 }
19405
19406 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19407                                 TargetLowering::DAGCombinerInfo &DCI,
19408                                 const X86Subtarget *Subtarget) {
19409   if (DCI.isBeforeLegalizeOps())
19410     return SDValue();
19411
19412   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19413   if (R.getNode())
19414     return R;
19415
19416   SDValue N0 = N->getOperand(0);
19417   SDValue N1 = N->getOperand(1);
19418   EVT VT = N->getValueType(0);
19419
19420   // look for psign/blend
19421   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19422     if (!Subtarget->hasSSSE3() ||
19423         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19424       return SDValue();
19425
19426     // Canonicalize pandn to RHS
19427     if (N0.getOpcode() == X86ISD::ANDNP)
19428       std::swap(N0, N1);
19429     // or (and (m, y), (pandn m, x))
19430     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19431       SDValue Mask = N1.getOperand(0);
19432       SDValue X    = N1.getOperand(1);
19433       SDValue Y;
19434       if (N0.getOperand(0) == Mask)
19435         Y = N0.getOperand(1);
19436       if (N0.getOperand(1) == Mask)
19437         Y = N0.getOperand(0);
19438
19439       // Check to see if the mask appeared in both the AND and ANDNP and
19440       if (!Y.getNode())
19441         return SDValue();
19442
19443       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19444       // Look through mask bitcast.
19445       if (Mask.getOpcode() == ISD::BITCAST)
19446         Mask = Mask.getOperand(0);
19447       if (X.getOpcode() == ISD::BITCAST)
19448         X = X.getOperand(0);
19449       if (Y.getOpcode() == ISD::BITCAST)
19450         Y = Y.getOperand(0);
19451
19452       EVT MaskVT = Mask.getValueType();
19453
19454       // Validate that the Mask operand is a vector sra node.
19455       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19456       // there is no psrai.b
19457       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19458       unsigned SraAmt = ~0;
19459       if (Mask.getOpcode() == ISD::SRA) {
19460         SDValue Amt = Mask.getOperand(1);
19461         if (isSplatVector(Amt.getNode())) {
19462           SDValue SclrAmt = Amt->getOperand(0);
19463           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19464             SraAmt = C->getZExtValue();
19465         }
19466       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19467         SDValue SraC = Mask.getOperand(1);
19468         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19469       }
19470       if ((SraAmt + 1) != EltBits)
19471         return SDValue();
19472
19473       SDLoc DL(N);
19474
19475       // Now we know we at least have a plendvb with the mask val.  See if
19476       // we can form a psignb/w/d.
19477       // psign = x.type == y.type == mask.type && y = sub(0, x);
19478       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19479           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19480           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19481         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19482                "Unsupported VT for PSIGN");
19483         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19484         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19485       }
19486       // PBLENDVB only available on SSE 4.1
19487       if (!Subtarget->hasSSE41())
19488         return SDValue();
19489
19490       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19491
19492       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19493       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19494       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19495       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19496       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19497     }
19498   }
19499
19500   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19501     return SDValue();
19502
19503   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19504   MachineFunction &MF = DAG.getMachineFunction();
19505   bool OptForSize = MF.getFunction()->getAttributes().
19506     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19507
19508   // SHLD/SHRD instructions have lower register pressure, but on some
19509   // platforms they have higher latency than the equivalent
19510   // series of shifts/or that would otherwise be generated.
19511   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19512   // have higher latencies and we are not optimizing for size.
19513   if (!OptForSize && Subtarget->isSHLDSlow())
19514     return SDValue();
19515
19516   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19517     std::swap(N0, N1);
19518   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19519     return SDValue();
19520   if (!N0.hasOneUse() || !N1.hasOneUse())
19521     return SDValue();
19522
19523   SDValue ShAmt0 = N0.getOperand(1);
19524   if (ShAmt0.getValueType() != MVT::i8)
19525     return SDValue();
19526   SDValue ShAmt1 = N1.getOperand(1);
19527   if (ShAmt1.getValueType() != MVT::i8)
19528     return SDValue();
19529   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19530     ShAmt0 = ShAmt0.getOperand(0);
19531   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19532     ShAmt1 = ShAmt1.getOperand(0);
19533
19534   SDLoc DL(N);
19535   unsigned Opc = X86ISD::SHLD;
19536   SDValue Op0 = N0.getOperand(0);
19537   SDValue Op1 = N1.getOperand(0);
19538   if (ShAmt0.getOpcode() == ISD::SUB) {
19539     Opc = X86ISD::SHRD;
19540     std::swap(Op0, Op1);
19541     std::swap(ShAmt0, ShAmt1);
19542   }
19543
19544   unsigned Bits = VT.getSizeInBits();
19545   if (ShAmt1.getOpcode() == ISD::SUB) {
19546     SDValue Sum = ShAmt1.getOperand(0);
19547     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19548       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19549       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19550         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19551       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19552         return DAG.getNode(Opc, DL, VT,
19553                            Op0, Op1,
19554                            DAG.getNode(ISD::TRUNCATE, DL,
19555                                        MVT::i8, ShAmt0));
19556     }
19557   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19558     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19559     if (ShAmt0C &&
19560         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19561       return DAG.getNode(Opc, DL, VT,
19562                          N0.getOperand(0), N1.getOperand(0),
19563                          DAG.getNode(ISD::TRUNCATE, DL,
19564                                        MVT::i8, ShAmt0));
19565   }
19566
19567   return SDValue();
19568 }
19569
19570 // Generate NEG and CMOV for integer abs.
19571 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19572   EVT VT = N->getValueType(0);
19573
19574   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19575   // 8-bit integer abs to NEG and CMOV.
19576   if (VT.isInteger() && VT.getSizeInBits() == 8)
19577     return SDValue();
19578
19579   SDValue N0 = N->getOperand(0);
19580   SDValue N1 = N->getOperand(1);
19581   SDLoc DL(N);
19582
19583   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19584   // and change it to SUB and CMOV.
19585   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19586       N0.getOpcode() == ISD::ADD &&
19587       N0.getOperand(1) == N1 &&
19588       N1.getOpcode() == ISD::SRA &&
19589       N1.getOperand(0) == N0.getOperand(0))
19590     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19591       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19592         // Generate SUB & CMOV.
19593         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19594                                   DAG.getConstant(0, VT), N0.getOperand(0));
19595
19596         SDValue Ops[] = { N0.getOperand(0), Neg,
19597                           DAG.getConstant(X86::COND_GE, MVT::i8),
19598                           SDValue(Neg.getNode(), 1) };
19599         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19600       }
19601   return SDValue();
19602 }
19603
19604 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19605 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19606                                  TargetLowering::DAGCombinerInfo &DCI,
19607                                  const X86Subtarget *Subtarget) {
19608   if (DCI.isBeforeLegalizeOps())
19609     return SDValue();
19610
19611   if (Subtarget->hasCMov()) {
19612     SDValue RV = performIntegerAbsCombine(N, DAG);
19613     if (RV.getNode())
19614       return RV;
19615   }
19616
19617   return SDValue();
19618 }
19619
19620 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19621 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19622                                   TargetLowering::DAGCombinerInfo &DCI,
19623                                   const X86Subtarget *Subtarget) {
19624   LoadSDNode *Ld = cast<LoadSDNode>(N);
19625   EVT RegVT = Ld->getValueType(0);
19626   EVT MemVT = Ld->getMemoryVT();
19627   SDLoc dl(Ld);
19628   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19629   unsigned RegSz = RegVT.getSizeInBits();
19630
19631   // On Sandybridge unaligned 256bit loads are inefficient.
19632   ISD::LoadExtType Ext = Ld->getExtensionType();
19633   unsigned Alignment = Ld->getAlignment();
19634   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19635   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19636       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19637     unsigned NumElems = RegVT.getVectorNumElements();
19638     if (NumElems < 2)
19639       return SDValue();
19640
19641     SDValue Ptr = Ld->getBasePtr();
19642     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19643
19644     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19645                                   NumElems/2);
19646     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19647                                 Ld->getPointerInfo(), Ld->isVolatile(),
19648                                 Ld->isNonTemporal(), Ld->isInvariant(),
19649                                 Alignment);
19650     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19651     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19652                                 Ld->getPointerInfo(), Ld->isVolatile(),
19653                                 Ld->isNonTemporal(), Ld->isInvariant(),
19654                                 std::min(16U, Alignment));
19655     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19656                              Load1.getValue(1),
19657                              Load2.getValue(1));
19658
19659     SDValue NewVec = DAG.getUNDEF(RegVT);
19660     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19661     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19662     return DCI.CombineTo(N, NewVec, TF, true);
19663   }
19664
19665   // If this is a vector EXT Load then attempt to optimize it using a
19666   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19667   // expansion is still better than scalar code.
19668   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19669   // emit a shuffle and a arithmetic shift.
19670   // TODO: It is possible to support ZExt by zeroing the undef values
19671   // during the shuffle phase or after the shuffle.
19672   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19673       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19674     assert(MemVT != RegVT && "Cannot extend to the same type");
19675     assert(MemVT.isVector() && "Must load a vector from memory");
19676
19677     unsigned NumElems = RegVT.getVectorNumElements();
19678     unsigned MemSz = MemVT.getSizeInBits();
19679     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19680
19681     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19682       return SDValue();
19683
19684     // All sizes must be a power of two.
19685     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19686       return SDValue();
19687
19688     // Attempt to load the original value using scalar loads.
19689     // Find the largest scalar type that divides the total loaded size.
19690     MVT SclrLoadTy = MVT::i8;
19691     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19692          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19693       MVT Tp = (MVT::SimpleValueType)tp;
19694       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19695         SclrLoadTy = Tp;
19696       }
19697     }
19698
19699     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19700     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19701         (64 <= MemSz))
19702       SclrLoadTy = MVT::f64;
19703
19704     // Calculate the number of scalar loads that we need to perform
19705     // in order to load our vector from memory.
19706     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19707     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19708       return SDValue();
19709
19710     unsigned loadRegZize = RegSz;
19711     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19712       loadRegZize /= 2;
19713
19714     // Represent our vector as a sequence of elements which are the
19715     // largest scalar that we can load.
19716     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19717       loadRegZize/SclrLoadTy.getSizeInBits());
19718
19719     // Represent the data using the same element type that is stored in
19720     // memory. In practice, we ''widen'' MemVT.
19721     EVT WideVecVT =
19722           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19723                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19724
19725     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19726       "Invalid vector type");
19727
19728     // We can't shuffle using an illegal type.
19729     if (!TLI.isTypeLegal(WideVecVT))
19730       return SDValue();
19731
19732     SmallVector<SDValue, 8> Chains;
19733     SDValue Ptr = Ld->getBasePtr();
19734     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19735                                         TLI.getPointerTy());
19736     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19737
19738     for (unsigned i = 0; i < NumLoads; ++i) {
19739       // Perform a single load.
19740       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19741                                        Ptr, Ld->getPointerInfo(),
19742                                        Ld->isVolatile(), Ld->isNonTemporal(),
19743                                        Ld->isInvariant(), Ld->getAlignment());
19744       Chains.push_back(ScalarLoad.getValue(1));
19745       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19746       // another round of DAGCombining.
19747       if (i == 0)
19748         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19749       else
19750         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19751                           ScalarLoad, DAG.getIntPtrConstant(i));
19752
19753       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19754     }
19755
19756     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19757
19758     // Bitcast the loaded value to a vector of the original element type, in
19759     // the size of the target vector type.
19760     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19761     unsigned SizeRatio = RegSz/MemSz;
19762
19763     if (Ext == ISD::SEXTLOAD) {
19764       // If we have SSE4.1 we can directly emit a VSEXT node.
19765       if (Subtarget->hasSSE41()) {
19766         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19767         return DCI.CombineTo(N, Sext, TF, true);
19768       }
19769
19770       // Otherwise we'll shuffle the small elements in the high bits of the
19771       // larger type and perform an arithmetic shift. If the shift is not legal
19772       // it's better to scalarize.
19773       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19774         return SDValue();
19775
19776       // Redistribute the loaded elements into the different locations.
19777       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19778       for (unsigned i = 0; i != NumElems; ++i)
19779         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19780
19781       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19782                                            DAG.getUNDEF(WideVecVT),
19783                                            &ShuffleVec[0]);
19784
19785       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19786
19787       // Build the arithmetic shift.
19788       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19789                      MemVT.getVectorElementType().getSizeInBits();
19790       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19791                           DAG.getConstant(Amt, RegVT));
19792
19793       return DCI.CombineTo(N, Shuff, TF, true);
19794     }
19795
19796     // Redistribute the loaded elements into the different locations.
19797     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19798     for (unsigned i = 0; i != NumElems; ++i)
19799       ShuffleVec[i*SizeRatio] = i;
19800
19801     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19802                                          DAG.getUNDEF(WideVecVT),
19803                                          &ShuffleVec[0]);
19804
19805     // Bitcast to the requested type.
19806     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19807     // Replace the original load with the new sequence
19808     // and return the new chain.
19809     return DCI.CombineTo(N, Shuff, TF, true);
19810   }
19811
19812   return SDValue();
19813 }
19814
19815 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19816 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19817                                    const X86Subtarget *Subtarget) {
19818   StoreSDNode *St = cast<StoreSDNode>(N);
19819   EVT VT = St->getValue().getValueType();
19820   EVT StVT = St->getMemoryVT();
19821   SDLoc dl(St);
19822   SDValue StoredVal = St->getOperand(1);
19823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19824
19825   // If we are saving a concatenation of two XMM registers, perform two stores.
19826   // On Sandy Bridge, 256-bit memory operations are executed by two
19827   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19828   // memory  operation.
19829   unsigned Alignment = St->getAlignment();
19830   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19831   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19832       StVT == VT && !IsAligned) {
19833     unsigned NumElems = VT.getVectorNumElements();
19834     if (NumElems < 2)
19835       return SDValue();
19836
19837     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19838     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19839
19840     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19841     SDValue Ptr0 = St->getBasePtr();
19842     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19843
19844     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19845                                 St->getPointerInfo(), St->isVolatile(),
19846                                 St->isNonTemporal(), Alignment);
19847     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19848                                 St->getPointerInfo(), St->isVolatile(),
19849                                 St->isNonTemporal(),
19850                                 std::min(16U, Alignment));
19851     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19852   }
19853
19854   // Optimize trunc store (of multiple scalars) to shuffle and store.
19855   // First, pack all of the elements in one place. Next, store to memory
19856   // in fewer chunks.
19857   if (St->isTruncatingStore() && VT.isVector()) {
19858     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19859     unsigned NumElems = VT.getVectorNumElements();
19860     assert(StVT != VT && "Cannot truncate to the same type");
19861     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19862     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19863
19864     // From, To sizes and ElemCount must be pow of two
19865     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19866     // We are going to use the original vector elt for storing.
19867     // Accumulated smaller vector elements must be a multiple of the store size.
19868     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19869
19870     unsigned SizeRatio  = FromSz / ToSz;
19871
19872     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19873
19874     // Create a type on which we perform the shuffle
19875     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19876             StVT.getScalarType(), NumElems*SizeRatio);
19877
19878     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19879
19880     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19881     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19882     for (unsigned i = 0; i != NumElems; ++i)
19883       ShuffleVec[i] = i * SizeRatio;
19884
19885     // Can't shuffle using an illegal type.
19886     if (!TLI.isTypeLegal(WideVecVT))
19887       return SDValue();
19888
19889     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19890                                          DAG.getUNDEF(WideVecVT),
19891                                          &ShuffleVec[0]);
19892     // At this point all of the data is stored at the bottom of the
19893     // register. We now need to save it to mem.
19894
19895     // Find the largest store unit
19896     MVT StoreType = MVT::i8;
19897     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19898          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19899       MVT Tp = (MVT::SimpleValueType)tp;
19900       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19901         StoreType = Tp;
19902     }
19903
19904     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19905     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19906         (64 <= NumElems * ToSz))
19907       StoreType = MVT::f64;
19908
19909     // Bitcast the original vector into a vector of store-size units
19910     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19911             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19912     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19913     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19914     SmallVector<SDValue, 8> Chains;
19915     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19916                                         TLI.getPointerTy());
19917     SDValue Ptr = St->getBasePtr();
19918
19919     // Perform one or more big stores into memory.
19920     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19921       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19922                                    StoreType, ShuffWide,
19923                                    DAG.getIntPtrConstant(i));
19924       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19925                                 St->getPointerInfo(), St->isVolatile(),
19926                                 St->isNonTemporal(), St->getAlignment());
19927       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19928       Chains.push_back(Ch);
19929     }
19930
19931     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19932   }
19933
19934   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19935   // the FP state in cases where an emms may be missing.
19936   // A preferable solution to the general problem is to figure out the right
19937   // places to insert EMMS.  This qualifies as a quick hack.
19938
19939   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19940   if (VT.getSizeInBits() != 64)
19941     return SDValue();
19942
19943   const Function *F = DAG.getMachineFunction().getFunction();
19944   bool NoImplicitFloatOps = F->getAttributes().
19945     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19946   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19947                      && Subtarget->hasSSE2();
19948   if ((VT.isVector() ||
19949        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19950       isa<LoadSDNode>(St->getValue()) &&
19951       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19952       St->getChain().hasOneUse() && !St->isVolatile()) {
19953     SDNode* LdVal = St->getValue().getNode();
19954     LoadSDNode *Ld = nullptr;
19955     int TokenFactorIndex = -1;
19956     SmallVector<SDValue, 8> Ops;
19957     SDNode* ChainVal = St->getChain().getNode();
19958     // Must be a store of a load.  We currently handle two cases:  the load
19959     // is a direct child, and it's under an intervening TokenFactor.  It is
19960     // possible to dig deeper under nested TokenFactors.
19961     if (ChainVal == LdVal)
19962       Ld = cast<LoadSDNode>(St->getChain());
19963     else if (St->getValue().hasOneUse() &&
19964              ChainVal->getOpcode() == ISD::TokenFactor) {
19965       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19966         if (ChainVal->getOperand(i).getNode() == LdVal) {
19967           TokenFactorIndex = i;
19968           Ld = cast<LoadSDNode>(St->getValue());
19969         } else
19970           Ops.push_back(ChainVal->getOperand(i));
19971       }
19972     }
19973
19974     if (!Ld || !ISD::isNormalLoad(Ld))
19975       return SDValue();
19976
19977     // If this is not the MMX case, i.e. we are just turning i64 load/store
19978     // into f64 load/store, avoid the transformation if there are multiple
19979     // uses of the loaded value.
19980     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19981       return SDValue();
19982
19983     SDLoc LdDL(Ld);
19984     SDLoc StDL(N);
19985     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19986     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19987     // pair instead.
19988     if (Subtarget->is64Bit() || F64IsLegal) {
19989       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19990       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19991                                   Ld->getPointerInfo(), Ld->isVolatile(),
19992                                   Ld->isNonTemporal(), Ld->isInvariant(),
19993                                   Ld->getAlignment());
19994       SDValue NewChain = NewLd.getValue(1);
19995       if (TokenFactorIndex != -1) {
19996         Ops.push_back(NewChain);
19997         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19998       }
19999       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20000                           St->getPointerInfo(),
20001                           St->isVolatile(), St->isNonTemporal(),
20002                           St->getAlignment());
20003     }
20004
20005     // Otherwise, lower to two pairs of 32-bit loads / stores.
20006     SDValue LoAddr = Ld->getBasePtr();
20007     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20008                                  DAG.getConstant(4, MVT::i32));
20009
20010     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20011                                Ld->getPointerInfo(),
20012                                Ld->isVolatile(), Ld->isNonTemporal(),
20013                                Ld->isInvariant(), Ld->getAlignment());
20014     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20015                                Ld->getPointerInfo().getWithOffset(4),
20016                                Ld->isVolatile(), Ld->isNonTemporal(),
20017                                Ld->isInvariant(),
20018                                MinAlign(Ld->getAlignment(), 4));
20019
20020     SDValue NewChain = LoLd.getValue(1);
20021     if (TokenFactorIndex != -1) {
20022       Ops.push_back(LoLd);
20023       Ops.push_back(HiLd);
20024       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20025     }
20026
20027     LoAddr = St->getBasePtr();
20028     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20029                          DAG.getConstant(4, MVT::i32));
20030
20031     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20032                                 St->getPointerInfo(),
20033                                 St->isVolatile(), St->isNonTemporal(),
20034                                 St->getAlignment());
20035     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20036                                 St->getPointerInfo().getWithOffset(4),
20037                                 St->isVolatile(),
20038                                 St->isNonTemporal(),
20039                                 MinAlign(St->getAlignment(), 4));
20040     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20041   }
20042   return SDValue();
20043 }
20044
20045 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20046 /// and return the operands for the horizontal operation in LHS and RHS.  A
20047 /// horizontal operation performs the binary operation on successive elements
20048 /// of its first operand, then on successive elements of its second operand,
20049 /// returning the resulting values in a vector.  For example, if
20050 ///   A = < float a0, float a1, float a2, float a3 >
20051 /// and
20052 ///   B = < float b0, float b1, float b2, float b3 >
20053 /// then the result of doing a horizontal operation on A and B is
20054 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20055 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20056 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20057 /// set to A, RHS to B, and the routine returns 'true'.
20058 /// Note that the binary operation should have the property that if one of the
20059 /// operands is UNDEF then the result is UNDEF.
20060 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20061   // Look for the following pattern: if
20062   //   A = < float a0, float a1, float a2, float a3 >
20063   //   B = < float b0, float b1, float b2, float b3 >
20064   // and
20065   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20066   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20067   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20068   // which is A horizontal-op B.
20069
20070   // At least one of the operands should be a vector shuffle.
20071   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20072       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20073     return false;
20074
20075   MVT VT = LHS.getSimpleValueType();
20076
20077   assert((VT.is128BitVector() || VT.is256BitVector()) &&
20078          "Unsupported vector type for horizontal add/sub");
20079
20080   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20081   // operate independently on 128-bit lanes.
20082   unsigned NumElts = VT.getVectorNumElements();
20083   unsigned NumLanes = VT.getSizeInBits()/128;
20084   unsigned NumLaneElts = NumElts / NumLanes;
20085   assert((NumLaneElts % 2 == 0) &&
20086          "Vector type should have an even number of elements in each lane");
20087   unsigned HalfLaneElts = NumLaneElts/2;
20088
20089   // View LHS in the form
20090   //   LHS = VECTOR_SHUFFLE A, B, LMask
20091   // If LHS is not a shuffle then pretend it is the shuffle
20092   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20093   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20094   // type VT.
20095   SDValue A, B;
20096   SmallVector<int, 16> LMask(NumElts);
20097   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20098     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20099       A = LHS.getOperand(0);
20100     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20101       B = LHS.getOperand(1);
20102     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20103     std::copy(Mask.begin(), Mask.end(), LMask.begin());
20104   } else {
20105     if (LHS.getOpcode() != ISD::UNDEF)
20106       A = LHS;
20107     for (unsigned i = 0; i != NumElts; ++i)
20108       LMask[i] = i;
20109   }
20110
20111   // Likewise, view RHS in the form
20112   //   RHS = VECTOR_SHUFFLE C, D, RMask
20113   SDValue C, D;
20114   SmallVector<int, 16> RMask(NumElts);
20115   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20116     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20117       C = RHS.getOperand(0);
20118     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20119       D = RHS.getOperand(1);
20120     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20121     std::copy(Mask.begin(), Mask.end(), RMask.begin());
20122   } else {
20123     if (RHS.getOpcode() != ISD::UNDEF)
20124       C = RHS;
20125     for (unsigned i = 0; i != NumElts; ++i)
20126       RMask[i] = i;
20127   }
20128
20129   // Check that the shuffles are both shuffling the same vectors.
20130   if (!(A == C && B == D) && !(A == D && B == C))
20131     return false;
20132
20133   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20134   if (!A.getNode() && !B.getNode())
20135     return false;
20136
20137   // If A and B occur in reverse order in RHS, then "swap" them (which means
20138   // rewriting the mask).
20139   if (A != C)
20140     CommuteVectorShuffleMask(RMask, NumElts);
20141
20142   // At this point LHS and RHS are equivalent to
20143   //   LHS = VECTOR_SHUFFLE A, B, LMask
20144   //   RHS = VECTOR_SHUFFLE A, B, RMask
20145   // Check that the masks correspond to performing a horizontal operation.
20146   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20147     for (unsigned i = 0; i != NumLaneElts; ++i) {
20148       int LIdx = LMask[i+l], RIdx = RMask[i+l];
20149
20150       // Ignore any UNDEF components.
20151       if (LIdx < 0 || RIdx < 0 ||
20152           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20153           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20154         continue;
20155
20156       // Check that successive elements are being operated on.  If not, this is
20157       // not a horizontal operation.
20158       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20159       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20160       if (!(LIdx == Index && RIdx == Index + 1) &&
20161           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20162         return false;
20163     }
20164   }
20165
20166   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20167   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20168   return true;
20169 }
20170
20171 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20172 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20173                                   const X86Subtarget *Subtarget) {
20174   EVT VT = N->getValueType(0);
20175   SDValue LHS = N->getOperand(0);
20176   SDValue RHS = N->getOperand(1);
20177
20178   // Try to synthesize horizontal adds from adds of shuffles.
20179   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20180        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20181       isHorizontalBinOp(LHS, RHS, true))
20182     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20183   return SDValue();
20184 }
20185
20186 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20187 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20188                                   const X86Subtarget *Subtarget) {
20189   EVT VT = N->getValueType(0);
20190   SDValue LHS = N->getOperand(0);
20191   SDValue RHS = N->getOperand(1);
20192
20193   // Try to synthesize horizontal subs from subs of shuffles.
20194   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20195        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20196       isHorizontalBinOp(LHS, RHS, false))
20197     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20198   return SDValue();
20199 }
20200
20201 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20202 /// X86ISD::FXOR nodes.
20203 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20204   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20205   // F[X]OR(0.0, x) -> x
20206   // F[X]OR(x, 0.0) -> x
20207   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20208     if (C->getValueAPF().isPosZero())
20209       return N->getOperand(1);
20210   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20211     if (C->getValueAPF().isPosZero())
20212       return N->getOperand(0);
20213   return SDValue();
20214 }
20215
20216 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20217 /// X86ISD::FMAX nodes.
20218 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20219   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20220
20221   // Only perform optimizations if UnsafeMath is used.
20222   if (!DAG.getTarget().Options.UnsafeFPMath)
20223     return SDValue();
20224
20225   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20226   // into FMINC and FMAXC, which are Commutative operations.
20227   unsigned NewOp = 0;
20228   switch (N->getOpcode()) {
20229     default: llvm_unreachable("unknown opcode");
20230     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20231     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20232   }
20233
20234   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20235                      N->getOperand(0), N->getOperand(1));
20236 }
20237
20238 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20239 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20240   // FAND(0.0, x) -> 0.0
20241   // FAND(x, 0.0) -> 0.0
20242   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20243     if (C->getValueAPF().isPosZero())
20244       return N->getOperand(0);
20245   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20246     if (C->getValueAPF().isPosZero())
20247       return N->getOperand(1);
20248   return SDValue();
20249 }
20250
20251 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20252 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20253   // FANDN(x, 0.0) -> 0.0
20254   // FANDN(0.0, x) -> x
20255   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20256     if (C->getValueAPF().isPosZero())
20257       return N->getOperand(1);
20258   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20259     if (C->getValueAPF().isPosZero())
20260       return N->getOperand(1);
20261   return SDValue();
20262 }
20263
20264 static SDValue PerformBTCombine(SDNode *N,
20265                                 SelectionDAG &DAG,
20266                                 TargetLowering::DAGCombinerInfo &DCI) {
20267   // BT ignores high bits in the bit index operand.
20268   SDValue Op1 = N->getOperand(1);
20269   if (Op1.hasOneUse()) {
20270     unsigned BitWidth = Op1.getValueSizeInBits();
20271     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20272     APInt KnownZero, KnownOne;
20273     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20274                                           !DCI.isBeforeLegalizeOps());
20275     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20276     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20277         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20278       DCI.CommitTargetLoweringOpt(TLO);
20279   }
20280   return SDValue();
20281 }
20282
20283 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20284   SDValue Op = N->getOperand(0);
20285   if (Op.getOpcode() == ISD::BITCAST)
20286     Op = Op.getOperand(0);
20287   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20288   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20289       VT.getVectorElementType().getSizeInBits() ==
20290       OpVT.getVectorElementType().getSizeInBits()) {
20291     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20292   }
20293   return SDValue();
20294 }
20295
20296 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20297                                                const X86Subtarget *Subtarget) {
20298   EVT VT = N->getValueType(0);
20299   if (!VT.isVector())
20300     return SDValue();
20301
20302   SDValue N0 = N->getOperand(0);
20303   SDValue N1 = N->getOperand(1);
20304   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20305   SDLoc dl(N);
20306
20307   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20308   // both SSE and AVX2 since there is no sign-extended shift right
20309   // operation on a vector with 64-bit elements.
20310   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20311   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20312   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20313       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20314     SDValue N00 = N0.getOperand(0);
20315
20316     // EXTLOAD has a better solution on AVX2,
20317     // it may be replaced with X86ISD::VSEXT node.
20318     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20319       if (!ISD::isNormalLoad(N00.getNode()))
20320         return SDValue();
20321
20322     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20323         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20324                                   N00, N1);
20325       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20326     }
20327   }
20328   return SDValue();
20329 }
20330
20331 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20332                                   TargetLowering::DAGCombinerInfo &DCI,
20333                                   const X86Subtarget *Subtarget) {
20334   if (!DCI.isBeforeLegalizeOps())
20335     return SDValue();
20336
20337   if (!Subtarget->hasFp256())
20338     return SDValue();
20339
20340   EVT VT = N->getValueType(0);
20341   if (VT.isVector() && VT.getSizeInBits() == 256) {
20342     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20343     if (R.getNode())
20344       return R;
20345   }
20346
20347   return SDValue();
20348 }
20349
20350 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20351                                  const X86Subtarget* Subtarget) {
20352   SDLoc dl(N);
20353   EVT VT = N->getValueType(0);
20354
20355   // Let legalize expand this if it isn't a legal type yet.
20356   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20357     return SDValue();
20358
20359   EVT ScalarVT = VT.getScalarType();
20360   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20361       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20362     return SDValue();
20363
20364   SDValue A = N->getOperand(0);
20365   SDValue B = N->getOperand(1);
20366   SDValue C = N->getOperand(2);
20367
20368   bool NegA = (A.getOpcode() == ISD::FNEG);
20369   bool NegB = (B.getOpcode() == ISD::FNEG);
20370   bool NegC = (C.getOpcode() == ISD::FNEG);
20371
20372   // Negative multiplication when NegA xor NegB
20373   bool NegMul = (NegA != NegB);
20374   if (NegA)
20375     A = A.getOperand(0);
20376   if (NegB)
20377     B = B.getOperand(0);
20378   if (NegC)
20379     C = C.getOperand(0);
20380
20381   unsigned Opcode;
20382   if (!NegMul)
20383     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20384   else
20385     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20386
20387   return DAG.getNode(Opcode, dl, VT, A, B, C);
20388 }
20389
20390 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20391                                   TargetLowering::DAGCombinerInfo &DCI,
20392                                   const X86Subtarget *Subtarget) {
20393   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20394   //           (and (i32 x86isd::setcc_carry), 1)
20395   // This eliminates the zext. This transformation is necessary because
20396   // ISD::SETCC is always legalized to i8.
20397   SDLoc dl(N);
20398   SDValue N0 = N->getOperand(0);
20399   EVT VT = N->getValueType(0);
20400
20401   if (N0.getOpcode() == ISD::AND &&
20402       N0.hasOneUse() &&
20403       N0.getOperand(0).hasOneUse()) {
20404     SDValue N00 = N0.getOperand(0);
20405     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20406       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20407       if (!C || C->getZExtValue() != 1)
20408         return SDValue();
20409       return DAG.getNode(ISD::AND, dl, VT,
20410                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20411                                      N00.getOperand(0), N00.getOperand(1)),
20412                          DAG.getConstant(1, VT));
20413     }
20414   }
20415
20416   if (N0.getOpcode() == ISD::TRUNCATE &&
20417       N0.hasOneUse() &&
20418       N0.getOperand(0).hasOneUse()) {
20419     SDValue N00 = N0.getOperand(0);
20420     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20421       return DAG.getNode(ISD::AND, dl, VT,
20422                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20423                                      N00.getOperand(0), N00.getOperand(1)),
20424                          DAG.getConstant(1, VT));
20425     }
20426   }
20427   if (VT.is256BitVector()) {
20428     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20429     if (R.getNode())
20430       return R;
20431   }
20432
20433   return SDValue();
20434 }
20435
20436 // Optimize x == -y --> x+y == 0
20437 //          x != -y --> x+y != 0
20438 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20439                                       const X86Subtarget* Subtarget) {
20440   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20441   SDValue LHS = N->getOperand(0);
20442   SDValue RHS = N->getOperand(1);
20443   EVT VT = N->getValueType(0);
20444   SDLoc DL(N);
20445
20446   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20447     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20448       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20449         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20450                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20451         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20452                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20453       }
20454   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20455     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20456       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20457         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20458                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20459         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20460                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20461       }
20462
20463   if (VT.getScalarType() == MVT::i1) {
20464     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20465       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20466     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20467     if (!IsSEXT0 && !IsVZero0)
20468       return SDValue();
20469     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20470       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20471     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20472
20473     if (!IsSEXT1 && !IsVZero1)
20474       return SDValue();
20475
20476     if (IsSEXT0 && IsVZero1) {
20477       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20478       if (CC == ISD::SETEQ)
20479         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20480       return LHS.getOperand(0);
20481     }
20482     if (IsSEXT1 && IsVZero0) {
20483       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20484       if (CC == ISD::SETEQ)
20485         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20486       return RHS.getOperand(0);
20487     }
20488   }
20489
20490   return SDValue();
20491 }
20492
20493 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20494                                       const X86Subtarget *Subtarget) {
20495   SDLoc dl(N);
20496   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20497   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20498          "X86insertps is only defined for v4x32");
20499
20500   SDValue Ld = N->getOperand(1);
20501   if (MayFoldLoad(Ld)) {
20502     // Extract the countS bits from the immediate so we can get the proper
20503     // address when narrowing the vector load to a specific element.
20504     // When the second source op is a memory address, interps doesn't use
20505     // countS and just gets an f32 from that address.
20506     unsigned DestIndex =
20507         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20508     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20509   } else
20510     return SDValue();
20511
20512   // Create this as a scalar to vector to match the instruction pattern.
20513   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20514   // countS bits are ignored when loading from memory on insertps, which
20515   // means we don't need to explicitly set them to 0.
20516   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20517                      LoadScalarToVector, N->getOperand(2));
20518 }
20519
20520 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20521 // as "sbb reg,reg", since it can be extended without zext and produces
20522 // an all-ones bit which is more useful than 0/1 in some cases.
20523 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20524                                MVT VT) {
20525   if (VT == MVT::i8)
20526     return DAG.getNode(ISD::AND, DL, VT,
20527                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20528                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20529                        DAG.getConstant(1, VT));
20530   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20531   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20532                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20533                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20534 }
20535
20536 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20537 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20538                                    TargetLowering::DAGCombinerInfo &DCI,
20539                                    const X86Subtarget *Subtarget) {
20540   SDLoc DL(N);
20541   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20542   SDValue EFLAGS = N->getOperand(1);
20543
20544   if (CC == X86::COND_A) {
20545     // Try to convert COND_A into COND_B in an attempt to facilitate
20546     // materializing "setb reg".
20547     //
20548     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20549     // cannot take an immediate as its first operand.
20550     //
20551     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20552         EFLAGS.getValueType().isInteger() &&
20553         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20554       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20555                                    EFLAGS.getNode()->getVTList(),
20556                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20557       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20558       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20559     }
20560   }
20561
20562   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20563   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20564   // cases.
20565   if (CC == X86::COND_B)
20566     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20567
20568   SDValue Flags;
20569
20570   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20571   if (Flags.getNode()) {
20572     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20573     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20574   }
20575
20576   return SDValue();
20577 }
20578
20579 // Optimize branch condition evaluation.
20580 //
20581 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20582                                     TargetLowering::DAGCombinerInfo &DCI,
20583                                     const X86Subtarget *Subtarget) {
20584   SDLoc DL(N);
20585   SDValue Chain = N->getOperand(0);
20586   SDValue Dest = N->getOperand(1);
20587   SDValue EFLAGS = N->getOperand(3);
20588   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20589
20590   SDValue Flags;
20591
20592   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20593   if (Flags.getNode()) {
20594     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20595     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20596                        Flags);
20597   }
20598
20599   return SDValue();
20600 }
20601
20602 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20603                                         const X86TargetLowering *XTLI) {
20604   SDValue Op0 = N->getOperand(0);
20605   EVT InVT = Op0->getValueType(0);
20606
20607   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20608   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20609     SDLoc dl(N);
20610     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20611     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20612     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20613   }
20614
20615   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20616   // a 32-bit target where SSE doesn't support i64->FP operations.
20617   if (Op0.getOpcode() == ISD::LOAD) {
20618     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20619     EVT VT = Ld->getValueType(0);
20620     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20621         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20622         !XTLI->getSubtarget()->is64Bit() &&
20623         VT == MVT::i64) {
20624       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20625                                           Ld->getChain(), Op0, DAG);
20626       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20627       return FILDChain;
20628     }
20629   }
20630   return SDValue();
20631 }
20632
20633 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20634 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20635                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20636   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20637   // the result is either zero or one (depending on the input carry bit).
20638   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20639   if (X86::isZeroNode(N->getOperand(0)) &&
20640       X86::isZeroNode(N->getOperand(1)) &&
20641       // We don't have a good way to replace an EFLAGS use, so only do this when
20642       // dead right now.
20643       SDValue(N, 1).use_empty()) {
20644     SDLoc DL(N);
20645     EVT VT = N->getValueType(0);
20646     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20647     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20648                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20649                                            DAG.getConstant(X86::COND_B,MVT::i8),
20650                                            N->getOperand(2)),
20651                                DAG.getConstant(1, VT));
20652     return DCI.CombineTo(N, Res1, CarryOut);
20653   }
20654
20655   return SDValue();
20656 }
20657
20658 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20659 //      (add Y, (setne X, 0)) -> sbb -1, Y
20660 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20661 //      (sub (setne X, 0), Y) -> adc -1, Y
20662 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20663   SDLoc DL(N);
20664
20665   // Look through ZExts.
20666   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20667   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20668     return SDValue();
20669
20670   SDValue SetCC = Ext.getOperand(0);
20671   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20672     return SDValue();
20673
20674   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20675   if (CC != X86::COND_E && CC != X86::COND_NE)
20676     return SDValue();
20677
20678   SDValue Cmp = SetCC.getOperand(1);
20679   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20680       !X86::isZeroNode(Cmp.getOperand(1)) ||
20681       !Cmp.getOperand(0).getValueType().isInteger())
20682     return SDValue();
20683
20684   SDValue CmpOp0 = Cmp.getOperand(0);
20685   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20686                                DAG.getConstant(1, CmpOp0.getValueType()));
20687
20688   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20689   if (CC == X86::COND_NE)
20690     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20691                        DL, OtherVal.getValueType(), OtherVal,
20692                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20693   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20694                      DL, OtherVal.getValueType(), OtherVal,
20695                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20696 }
20697
20698 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20699 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20700                                  const X86Subtarget *Subtarget) {
20701   EVT VT = N->getValueType(0);
20702   SDValue Op0 = N->getOperand(0);
20703   SDValue Op1 = N->getOperand(1);
20704
20705   // Try to synthesize horizontal adds from adds of shuffles.
20706   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20707        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20708       isHorizontalBinOp(Op0, Op1, true))
20709     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20710
20711   return OptimizeConditionalInDecrement(N, DAG);
20712 }
20713
20714 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20715                                  const X86Subtarget *Subtarget) {
20716   SDValue Op0 = N->getOperand(0);
20717   SDValue Op1 = N->getOperand(1);
20718
20719   // X86 can't encode an immediate LHS of a sub. See if we can push the
20720   // negation into a preceding instruction.
20721   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20722     // If the RHS of the sub is a XOR with one use and a constant, invert the
20723     // immediate. Then add one to the LHS of the sub so we can turn
20724     // X-Y -> X+~Y+1, saving one register.
20725     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20726         isa<ConstantSDNode>(Op1.getOperand(1))) {
20727       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20728       EVT VT = Op0.getValueType();
20729       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20730                                    Op1.getOperand(0),
20731                                    DAG.getConstant(~XorC, VT));
20732       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20733                          DAG.getConstant(C->getAPIntValue()+1, VT));
20734     }
20735   }
20736
20737   // Try to synthesize horizontal adds from adds of shuffles.
20738   EVT VT = N->getValueType(0);
20739   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20740        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20741       isHorizontalBinOp(Op0, Op1, true))
20742     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20743
20744   return OptimizeConditionalInDecrement(N, DAG);
20745 }
20746
20747 /// performVZEXTCombine - Performs build vector combines
20748 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20749                                         TargetLowering::DAGCombinerInfo &DCI,
20750                                         const X86Subtarget *Subtarget) {
20751   // (vzext (bitcast (vzext (x)) -> (vzext x)
20752   SDValue In = N->getOperand(0);
20753   while (In.getOpcode() == ISD::BITCAST)
20754     In = In.getOperand(0);
20755
20756   if (In.getOpcode() != X86ISD::VZEXT)
20757     return SDValue();
20758
20759   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20760                      In.getOperand(0));
20761 }
20762
20763 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20764                                              DAGCombinerInfo &DCI) const {
20765   SelectionDAG &DAG = DCI.DAG;
20766   switch (N->getOpcode()) {
20767   default: break;
20768   case ISD::EXTRACT_VECTOR_ELT:
20769     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20770   case ISD::VSELECT:
20771   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20772   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20773   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20774   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20775   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20776   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20777   case ISD::SHL:
20778   case ISD::SRA:
20779   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20780   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20781   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20782   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20783   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20784   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20785   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20786   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20787   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20788   case X86ISD::FXOR:
20789   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20790   case X86ISD::FMIN:
20791   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20792   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20793   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20794   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20795   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20796   case ISD::ANY_EXTEND:
20797   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20798   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20799   case ISD::SIGN_EXTEND_INREG:
20800     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20801   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20802   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20803   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20804   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20805   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20806   case X86ISD::SHUFP:       // Handle all target specific shuffles
20807   case X86ISD::PALIGNR:
20808   case X86ISD::UNPCKH:
20809   case X86ISD::UNPCKL:
20810   case X86ISD::MOVHLPS:
20811   case X86ISD::MOVLHPS:
20812   case X86ISD::PSHUFD:
20813   case X86ISD::PSHUFHW:
20814   case X86ISD::PSHUFLW:
20815   case X86ISD::MOVSS:
20816   case X86ISD::MOVSD:
20817   case X86ISD::VPERMILP:
20818   case X86ISD::VPERM2X128:
20819   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20820   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20821   case ISD::INTRINSIC_WO_CHAIN:
20822     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20823   case X86ISD::INSERTPS:
20824     return PerformINSERTPSCombine(N, DAG, Subtarget);
20825   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
20826   }
20827
20828   return SDValue();
20829 }
20830
20831 /// isTypeDesirableForOp - Return true if the target has native support for
20832 /// the specified value type and it is 'desirable' to use the type for the
20833 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20834 /// instruction encodings are longer and some i16 instructions are slow.
20835 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20836   if (!isTypeLegal(VT))
20837     return false;
20838   if (VT != MVT::i16)
20839     return true;
20840
20841   switch (Opc) {
20842   default:
20843     return true;
20844   case ISD::LOAD:
20845   case ISD::SIGN_EXTEND:
20846   case ISD::ZERO_EXTEND:
20847   case ISD::ANY_EXTEND:
20848   case ISD::SHL:
20849   case ISD::SRL:
20850   case ISD::SUB:
20851   case ISD::ADD:
20852   case ISD::MUL:
20853   case ISD::AND:
20854   case ISD::OR:
20855   case ISD::XOR:
20856     return false;
20857   }
20858 }
20859
20860 /// IsDesirableToPromoteOp - This method query the target whether it is
20861 /// beneficial for dag combiner to promote the specified node. If true, it
20862 /// should return the desired promotion type by reference.
20863 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20864   EVT VT = Op.getValueType();
20865   if (VT != MVT::i16)
20866     return false;
20867
20868   bool Promote = false;
20869   bool Commute = false;
20870   switch (Op.getOpcode()) {
20871   default: break;
20872   case ISD::LOAD: {
20873     LoadSDNode *LD = cast<LoadSDNode>(Op);
20874     // If the non-extending load has a single use and it's not live out, then it
20875     // might be folded.
20876     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20877                                                      Op.hasOneUse()*/) {
20878       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20879              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20880         // The only case where we'd want to promote LOAD (rather then it being
20881         // promoted as an operand is when it's only use is liveout.
20882         if (UI->getOpcode() != ISD::CopyToReg)
20883           return false;
20884       }
20885     }
20886     Promote = true;
20887     break;
20888   }
20889   case ISD::SIGN_EXTEND:
20890   case ISD::ZERO_EXTEND:
20891   case ISD::ANY_EXTEND:
20892     Promote = true;
20893     break;
20894   case ISD::SHL:
20895   case ISD::SRL: {
20896     SDValue N0 = Op.getOperand(0);
20897     // Look out for (store (shl (load), x)).
20898     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20899       return false;
20900     Promote = true;
20901     break;
20902   }
20903   case ISD::ADD:
20904   case ISD::MUL:
20905   case ISD::AND:
20906   case ISD::OR:
20907   case ISD::XOR:
20908     Commute = true;
20909     // fallthrough
20910   case ISD::SUB: {
20911     SDValue N0 = Op.getOperand(0);
20912     SDValue N1 = Op.getOperand(1);
20913     if (!Commute && MayFoldLoad(N1))
20914       return false;
20915     // Avoid disabling potential load folding opportunities.
20916     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20917       return false;
20918     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20919       return false;
20920     Promote = true;
20921   }
20922   }
20923
20924   PVT = MVT::i32;
20925   return Promote;
20926 }
20927
20928 //===----------------------------------------------------------------------===//
20929 //                           X86 Inline Assembly Support
20930 //===----------------------------------------------------------------------===//
20931
20932 namespace {
20933   // Helper to match a string separated by whitespace.
20934   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20935     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20936
20937     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20938       StringRef piece(*args[i]);
20939       if (!s.startswith(piece)) // Check if the piece matches.
20940         return false;
20941
20942       s = s.substr(piece.size());
20943       StringRef::size_type pos = s.find_first_not_of(" \t");
20944       if (pos == 0) // We matched a prefix.
20945         return false;
20946
20947       s = s.substr(pos);
20948     }
20949
20950     return s.empty();
20951   }
20952   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20953 }
20954
20955 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20956
20957   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20958     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20959         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20960         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20961
20962       if (AsmPieces.size() == 3)
20963         return true;
20964       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20965         return true;
20966     }
20967   }
20968   return false;
20969 }
20970
20971 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20972   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20973
20974   std::string AsmStr = IA->getAsmString();
20975
20976   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20977   if (!Ty || Ty->getBitWidth() % 16 != 0)
20978     return false;
20979
20980   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20981   SmallVector<StringRef, 4> AsmPieces;
20982   SplitString(AsmStr, AsmPieces, ";\n");
20983
20984   switch (AsmPieces.size()) {
20985   default: return false;
20986   case 1:
20987     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20988     // we will turn this bswap into something that will be lowered to logical
20989     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20990     // lower so don't worry about this.
20991     // bswap $0
20992     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20993         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20994         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20995         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20996         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20997         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20998       // No need to check constraints, nothing other than the equivalent of
20999       // "=r,0" would be valid here.
21000       return IntrinsicLowering::LowerToByteSwap(CI);
21001     }
21002
21003     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
21004     if (CI->getType()->isIntegerTy(16) &&
21005         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21006         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21007          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21008       AsmPieces.clear();
21009       const std::string &ConstraintsStr = IA->getConstraintString();
21010       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21011       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21012       if (clobbersFlagRegisters(AsmPieces))
21013         return IntrinsicLowering::LowerToByteSwap(CI);
21014     }
21015     break;
21016   case 3:
21017     if (CI->getType()->isIntegerTy(32) &&
21018         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21019         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21020         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21021         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21022       AsmPieces.clear();
21023       const std::string &ConstraintsStr = IA->getConstraintString();
21024       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21025       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21026       if (clobbersFlagRegisters(AsmPieces))
21027         return IntrinsicLowering::LowerToByteSwap(CI);
21028     }
21029
21030     if (CI->getType()->isIntegerTy(64)) {
21031       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21032       if (Constraints.size() >= 2 &&
21033           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21034           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21035         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
21036         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21037             matchAsm(AsmPieces[1], "bswap", "%edx") &&
21038             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21039           return IntrinsicLowering::LowerToByteSwap(CI);
21040       }
21041     }
21042     break;
21043   }
21044   return false;
21045 }
21046
21047 /// getConstraintType - Given a constraint letter, return the type of
21048 /// constraint it is for this target.
21049 X86TargetLowering::ConstraintType
21050 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21051   if (Constraint.size() == 1) {
21052     switch (Constraint[0]) {
21053     case 'R':
21054     case 'q':
21055     case 'Q':
21056     case 'f':
21057     case 't':
21058     case 'u':
21059     case 'y':
21060     case 'x':
21061     case 'Y':
21062     case 'l':
21063       return C_RegisterClass;
21064     case 'a':
21065     case 'b':
21066     case 'c':
21067     case 'd':
21068     case 'S':
21069     case 'D':
21070     case 'A':
21071       return C_Register;
21072     case 'I':
21073     case 'J':
21074     case 'K':
21075     case 'L':
21076     case 'M':
21077     case 'N':
21078     case 'G':
21079     case 'C':
21080     case 'e':
21081     case 'Z':
21082       return C_Other;
21083     default:
21084       break;
21085     }
21086   }
21087   return TargetLowering::getConstraintType(Constraint);
21088 }
21089
21090 /// Examine constraint type and operand type and determine a weight value.
21091 /// This object must already have been set up with the operand type
21092 /// and the current alternative constraint selected.
21093 TargetLowering::ConstraintWeight
21094   X86TargetLowering::getSingleConstraintMatchWeight(
21095     AsmOperandInfo &info, const char *constraint) const {
21096   ConstraintWeight weight = CW_Invalid;
21097   Value *CallOperandVal = info.CallOperandVal;
21098     // If we don't have a value, we can't do a match,
21099     // but allow it at the lowest weight.
21100   if (!CallOperandVal)
21101     return CW_Default;
21102   Type *type = CallOperandVal->getType();
21103   // Look at the constraint type.
21104   switch (*constraint) {
21105   default:
21106     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21107   case 'R':
21108   case 'q':
21109   case 'Q':
21110   case 'a':
21111   case 'b':
21112   case 'c':
21113   case 'd':
21114   case 'S':
21115   case 'D':
21116   case 'A':
21117     if (CallOperandVal->getType()->isIntegerTy())
21118       weight = CW_SpecificReg;
21119     break;
21120   case 'f':
21121   case 't':
21122   case 'u':
21123     if (type->isFloatingPointTy())
21124       weight = CW_SpecificReg;
21125     break;
21126   case 'y':
21127     if (type->isX86_MMXTy() && Subtarget->hasMMX())
21128       weight = CW_SpecificReg;
21129     break;
21130   case 'x':
21131   case 'Y':
21132     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21133         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21134       weight = CW_Register;
21135     break;
21136   case 'I':
21137     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21138       if (C->getZExtValue() <= 31)
21139         weight = CW_Constant;
21140     }
21141     break;
21142   case 'J':
21143     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21144       if (C->getZExtValue() <= 63)
21145         weight = CW_Constant;
21146     }
21147     break;
21148   case 'K':
21149     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21150       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21151         weight = CW_Constant;
21152     }
21153     break;
21154   case 'L':
21155     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21156       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21157         weight = CW_Constant;
21158     }
21159     break;
21160   case 'M':
21161     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21162       if (C->getZExtValue() <= 3)
21163         weight = CW_Constant;
21164     }
21165     break;
21166   case 'N':
21167     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21168       if (C->getZExtValue() <= 0xff)
21169         weight = CW_Constant;
21170     }
21171     break;
21172   case 'G':
21173   case 'C':
21174     if (dyn_cast<ConstantFP>(CallOperandVal)) {
21175       weight = CW_Constant;
21176     }
21177     break;
21178   case 'e':
21179     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21180       if ((C->getSExtValue() >= -0x80000000LL) &&
21181           (C->getSExtValue() <= 0x7fffffffLL))
21182         weight = CW_Constant;
21183     }
21184     break;
21185   case 'Z':
21186     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21187       if (C->getZExtValue() <= 0xffffffff)
21188         weight = CW_Constant;
21189     }
21190     break;
21191   }
21192   return weight;
21193 }
21194
21195 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21196 /// with another that has more specific requirements based on the type of the
21197 /// corresponding operand.
21198 const char *X86TargetLowering::
21199 LowerXConstraint(EVT ConstraintVT) const {
21200   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21201   // 'f' like normal targets.
21202   if (ConstraintVT.isFloatingPoint()) {
21203     if (Subtarget->hasSSE2())
21204       return "Y";
21205     if (Subtarget->hasSSE1())
21206       return "x";
21207   }
21208
21209   return TargetLowering::LowerXConstraint(ConstraintVT);
21210 }
21211
21212 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21213 /// vector.  If it is invalid, don't add anything to Ops.
21214 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21215                                                      std::string &Constraint,
21216                                                      std::vector<SDValue>&Ops,
21217                                                      SelectionDAG &DAG) const {
21218   SDValue Result;
21219
21220   // Only support length 1 constraints for now.
21221   if (Constraint.length() > 1) return;
21222
21223   char ConstraintLetter = Constraint[0];
21224   switch (ConstraintLetter) {
21225   default: break;
21226   case 'I':
21227     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21228       if (C->getZExtValue() <= 31) {
21229         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21230         break;
21231       }
21232     }
21233     return;
21234   case 'J':
21235     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21236       if (C->getZExtValue() <= 63) {
21237         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21238         break;
21239       }
21240     }
21241     return;
21242   case 'K':
21243     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21244       if (isInt<8>(C->getSExtValue())) {
21245         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21246         break;
21247       }
21248     }
21249     return;
21250   case 'N':
21251     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21252       if (C->getZExtValue() <= 255) {
21253         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21254         break;
21255       }
21256     }
21257     return;
21258   case 'e': {
21259     // 32-bit signed value
21260     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21261       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21262                                            C->getSExtValue())) {
21263         // Widen to 64 bits here to get it sign extended.
21264         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21265         break;
21266       }
21267     // FIXME gcc accepts some relocatable values here too, but only in certain
21268     // memory models; it's complicated.
21269     }
21270     return;
21271   }
21272   case 'Z': {
21273     // 32-bit unsigned value
21274     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21275       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21276                                            C->getZExtValue())) {
21277         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21278         break;
21279       }
21280     }
21281     // FIXME gcc accepts some relocatable values here too, but only in certain
21282     // memory models; it's complicated.
21283     return;
21284   }
21285   case 'i': {
21286     // Literal immediates are always ok.
21287     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21288       // Widen to 64 bits here to get it sign extended.
21289       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21290       break;
21291     }
21292
21293     // In any sort of PIC mode addresses need to be computed at runtime by
21294     // adding in a register or some sort of table lookup.  These can't
21295     // be used as immediates.
21296     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21297       return;
21298
21299     // If we are in non-pic codegen mode, we allow the address of a global (with
21300     // an optional displacement) to be used with 'i'.
21301     GlobalAddressSDNode *GA = nullptr;
21302     int64_t Offset = 0;
21303
21304     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21305     while (1) {
21306       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21307         Offset += GA->getOffset();
21308         break;
21309       } else if (Op.getOpcode() == ISD::ADD) {
21310         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21311           Offset += C->getZExtValue();
21312           Op = Op.getOperand(0);
21313           continue;
21314         }
21315       } else if (Op.getOpcode() == ISD::SUB) {
21316         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21317           Offset += -C->getZExtValue();
21318           Op = Op.getOperand(0);
21319           continue;
21320         }
21321       }
21322
21323       // Otherwise, this isn't something we can handle, reject it.
21324       return;
21325     }
21326
21327     const GlobalValue *GV = GA->getGlobal();
21328     // If we require an extra load to get this address, as in PIC mode, we
21329     // can't accept it.
21330     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21331                                                         getTargetMachine())))
21332       return;
21333
21334     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21335                                         GA->getValueType(0), Offset);
21336     break;
21337   }
21338   }
21339
21340   if (Result.getNode()) {
21341     Ops.push_back(Result);
21342     return;
21343   }
21344   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21345 }
21346
21347 std::pair<unsigned, const TargetRegisterClass*>
21348 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21349                                                 MVT VT) const {
21350   // First, see if this is a constraint that directly corresponds to an LLVM
21351   // register class.
21352   if (Constraint.size() == 1) {
21353     // GCC Constraint Letters
21354     switch (Constraint[0]) {
21355     default: break;
21356       // TODO: Slight differences here in allocation order and leaving
21357       // RIP in the class. Do they matter any more here than they do
21358       // in the normal allocation?
21359     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21360       if (Subtarget->is64Bit()) {
21361         if (VT == MVT::i32 || VT == MVT::f32)
21362           return std::make_pair(0U, &X86::GR32RegClass);
21363         if (VT == MVT::i16)
21364           return std::make_pair(0U, &X86::GR16RegClass);
21365         if (VT == MVT::i8 || VT == MVT::i1)
21366           return std::make_pair(0U, &X86::GR8RegClass);
21367         if (VT == MVT::i64 || VT == MVT::f64)
21368           return std::make_pair(0U, &X86::GR64RegClass);
21369         break;
21370       }
21371       // 32-bit fallthrough
21372     case 'Q':   // Q_REGS
21373       if (VT == MVT::i32 || VT == MVT::f32)
21374         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21375       if (VT == MVT::i16)
21376         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21377       if (VT == MVT::i8 || VT == MVT::i1)
21378         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21379       if (VT == MVT::i64)
21380         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21381       break;
21382     case 'r':   // GENERAL_REGS
21383     case 'l':   // INDEX_REGS
21384       if (VT == MVT::i8 || VT == MVT::i1)
21385         return std::make_pair(0U, &X86::GR8RegClass);
21386       if (VT == MVT::i16)
21387         return std::make_pair(0U, &X86::GR16RegClass);
21388       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21389         return std::make_pair(0U, &X86::GR32RegClass);
21390       return std::make_pair(0U, &X86::GR64RegClass);
21391     case 'R':   // LEGACY_REGS
21392       if (VT == MVT::i8 || VT == MVT::i1)
21393         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21394       if (VT == MVT::i16)
21395         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21396       if (VT == MVT::i32 || !Subtarget->is64Bit())
21397         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21398       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21399     case 'f':  // FP Stack registers.
21400       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21401       // value to the correct fpstack register class.
21402       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21403         return std::make_pair(0U, &X86::RFP32RegClass);
21404       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21405         return std::make_pair(0U, &X86::RFP64RegClass);
21406       return std::make_pair(0U, &X86::RFP80RegClass);
21407     case 'y':   // MMX_REGS if MMX allowed.
21408       if (!Subtarget->hasMMX()) break;
21409       return std::make_pair(0U, &X86::VR64RegClass);
21410     case 'Y':   // SSE_REGS if SSE2 allowed
21411       if (!Subtarget->hasSSE2()) break;
21412       // FALL THROUGH.
21413     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21414       if (!Subtarget->hasSSE1()) break;
21415
21416       switch (VT.SimpleTy) {
21417       default: break;
21418       // Scalar SSE types.
21419       case MVT::f32:
21420       case MVT::i32:
21421         return std::make_pair(0U, &X86::FR32RegClass);
21422       case MVT::f64:
21423       case MVT::i64:
21424         return std::make_pair(0U, &X86::FR64RegClass);
21425       // Vector types.
21426       case MVT::v16i8:
21427       case MVT::v8i16:
21428       case MVT::v4i32:
21429       case MVT::v2i64:
21430       case MVT::v4f32:
21431       case MVT::v2f64:
21432         return std::make_pair(0U, &X86::VR128RegClass);
21433       // AVX types.
21434       case MVT::v32i8:
21435       case MVT::v16i16:
21436       case MVT::v8i32:
21437       case MVT::v4i64:
21438       case MVT::v8f32:
21439       case MVT::v4f64:
21440         return std::make_pair(0U, &X86::VR256RegClass);
21441       case MVT::v8f64:
21442       case MVT::v16f32:
21443       case MVT::v16i32:
21444       case MVT::v8i64:
21445         return std::make_pair(0U, &X86::VR512RegClass);
21446       }
21447       break;
21448     }
21449   }
21450
21451   // Use the default implementation in TargetLowering to convert the register
21452   // constraint into a member of a register class.
21453   std::pair<unsigned, const TargetRegisterClass*> Res;
21454   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21455
21456   // Not found as a standard register?
21457   if (!Res.second) {
21458     // Map st(0) -> st(7) -> ST0
21459     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21460         tolower(Constraint[1]) == 's' &&
21461         tolower(Constraint[2]) == 't' &&
21462         Constraint[3] == '(' &&
21463         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21464         Constraint[5] == ')' &&
21465         Constraint[6] == '}') {
21466
21467       Res.first = X86::ST0+Constraint[4]-'0';
21468       Res.second = &X86::RFP80RegClass;
21469       return Res;
21470     }
21471
21472     // GCC allows "st(0)" to be called just plain "st".
21473     if (StringRef("{st}").equals_lower(Constraint)) {
21474       Res.first = X86::ST0;
21475       Res.second = &X86::RFP80RegClass;
21476       return Res;
21477     }
21478
21479     // flags -> EFLAGS
21480     if (StringRef("{flags}").equals_lower(Constraint)) {
21481       Res.first = X86::EFLAGS;
21482       Res.second = &X86::CCRRegClass;
21483       return Res;
21484     }
21485
21486     // 'A' means EAX + EDX.
21487     if (Constraint == "A") {
21488       Res.first = X86::EAX;
21489       Res.second = &X86::GR32_ADRegClass;
21490       return Res;
21491     }
21492     return Res;
21493   }
21494
21495   // Otherwise, check to see if this is a register class of the wrong value
21496   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21497   // turn into {ax},{dx}.
21498   if (Res.second->hasType(VT))
21499     return Res;   // Correct type already, nothing to do.
21500
21501   // All of the single-register GCC register classes map their values onto
21502   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21503   // really want an 8-bit or 32-bit register, map to the appropriate register
21504   // class and return the appropriate register.
21505   if (Res.second == &X86::GR16RegClass) {
21506     if (VT == MVT::i8 || VT == MVT::i1) {
21507       unsigned DestReg = 0;
21508       switch (Res.first) {
21509       default: break;
21510       case X86::AX: DestReg = X86::AL; break;
21511       case X86::DX: DestReg = X86::DL; break;
21512       case X86::CX: DestReg = X86::CL; break;
21513       case X86::BX: DestReg = X86::BL; break;
21514       }
21515       if (DestReg) {
21516         Res.first = DestReg;
21517         Res.second = &X86::GR8RegClass;
21518       }
21519     } else if (VT == MVT::i32 || VT == MVT::f32) {
21520       unsigned DestReg = 0;
21521       switch (Res.first) {
21522       default: break;
21523       case X86::AX: DestReg = X86::EAX; break;
21524       case X86::DX: DestReg = X86::EDX; break;
21525       case X86::CX: DestReg = X86::ECX; break;
21526       case X86::BX: DestReg = X86::EBX; break;
21527       case X86::SI: DestReg = X86::ESI; break;
21528       case X86::DI: DestReg = X86::EDI; break;
21529       case X86::BP: DestReg = X86::EBP; break;
21530       case X86::SP: DestReg = X86::ESP; break;
21531       }
21532       if (DestReg) {
21533         Res.first = DestReg;
21534         Res.second = &X86::GR32RegClass;
21535       }
21536     } else if (VT == MVT::i64 || VT == MVT::f64) {
21537       unsigned DestReg = 0;
21538       switch (Res.first) {
21539       default: break;
21540       case X86::AX: DestReg = X86::RAX; break;
21541       case X86::DX: DestReg = X86::RDX; break;
21542       case X86::CX: DestReg = X86::RCX; break;
21543       case X86::BX: DestReg = X86::RBX; break;
21544       case X86::SI: DestReg = X86::RSI; break;
21545       case X86::DI: DestReg = X86::RDI; break;
21546       case X86::BP: DestReg = X86::RBP; break;
21547       case X86::SP: DestReg = X86::RSP; break;
21548       }
21549       if (DestReg) {
21550         Res.first = DestReg;
21551         Res.second = &X86::GR64RegClass;
21552       }
21553     }
21554   } else if (Res.second == &X86::FR32RegClass ||
21555              Res.second == &X86::FR64RegClass ||
21556              Res.second == &X86::VR128RegClass ||
21557              Res.second == &X86::VR256RegClass ||
21558              Res.second == &X86::FR32XRegClass ||
21559              Res.second == &X86::FR64XRegClass ||
21560              Res.second == &X86::VR128XRegClass ||
21561              Res.second == &X86::VR256XRegClass ||
21562              Res.second == &X86::VR512RegClass) {
21563     // Handle references to XMM physical registers that got mapped into the
21564     // wrong class.  This can happen with constraints like {xmm0} where the
21565     // target independent register mapper will just pick the first match it can
21566     // find, ignoring the required type.
21567
21568     if (VT == MVT::f32 || VT == MVT::i32)
21569       Res.second = &X86::FR32RegClass;
21570     else if (VT == MVT::f64 || VT == MVT::i64)
21571       Res.second = &X86::FR64RegClass;
21572     else if (X86::VR128RegClass.hasType(VT))
21573       Res.second = &X86::VR128RegClass;
21574     else if (X86::VR256RegClass.hasType(VT))
21575       Res.second = &X86::VR256RegClass;
21576     else if (X86::VR512RegClass.hasType(VT))
21577       Res.second = &X86::VR512RegClass;
21578   }
21579
21580   return Res;
21581 }
21582
21583 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21584                                             Type *Ty) const {
21585   // Scaling factors are not free at all.
21586   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21587   // will take 2 allocations in the out of order engine instead of 1
21588   // for plain addressing mode, i.e. inst (reg1).
21589   // E.g.,
21590   // vaddps (%rsi,%drx), %ymm0, %ymm1
21591   // Requires two allocations (one for the load, one for the computation)
21592   // whereas:
21593   // vaddps (%rsi), %ymm0, %ymm1
21594   // Requires just 1 allocation, i.e., freeing allocations for other operations
21595   // and having less micro operations to execute.
21596   //
21597   // For some X86 architectures, this is even worse because for instance for
21598   // stores, the complex addressing mode forces the instruction to use the
21599   // "load" ports instead of the dedicated "store" port.
21600   // E.g., on Haswell:
21601   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21602   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21603   if (isLegalAddressingMode(AM, Ty))
21604     // Scale represents reg2 * scale, thus account for 1
21605     // as soon as we use a second register.
21606     return AM.Scale != 0;
21607   return -1;
21608 }