[C++] Use 'nullptr'.
[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/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <bitset>
51 #include <cctype>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "x86-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63                                 SelectionDAG &DAG, SDLoc dl,
64                                 unsigned vectorWidth) {
65   assert((vectorWidth == 128 || vectorWidth == 256) &&
66          "Unsupported vector width");
67   EVT VT = Vec.getValueType();
68   EVT ElVT = VT.getVectorElementType();
69   unsigned Factor = VT.getSizeInBits()/vectorWidth;
70   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71                                   VT.getVectorNumElements()/Factor);
72
73   // Extract from UNDEF is UNDEF.
74   if (Vec.getOpcode() == ISD::UNDEF)
75     return DAG.getUNDEF(ResultVT);
76
77   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
78   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79
80   // This is the index of the first element of the vectorWidth-bit chunk
81   // we want.
82   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
83                                * ElemsPerChunk);
84
85   // If the input is a buildvector just emit a smaller one.
86   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88                        ArrayRef<SDUse>(Vec->op_begin()+NormalizedIdxVal,
89                                        ElemsPerChunk));
90
91   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
92   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
93                                VecIdx);
94
95   return Result;
96
97 }
98 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
99 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
100 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
101 /// instructions or a simple subregister reference. Idx is an index in the
102 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
103 /// lowering EXTRACT_VECTOR_ELT operations easier.
104 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
105                                    SelectionDAG &DAG, SDLoc dl) {
106   assert((Vec.getValueType().is256BitVector() ||
107           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
108   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
109 }
110
111 /// Generate a DAG to grab 256-bits from a 512-bit vector.
112 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
113                                    SelectionDAG &DAG, SDLoc dl) {
114   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
115   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
116 }
117
118 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
119                                unsigned IdxVal, SelectionDAG &DAG,
120                                SDLoc dl, unsigned vectorWidth) {
121   assert((vectorWidth == 128 || vectorWidth == 256) &&
122          "Unsupported vector width");
123   // Inserting UNDEF is Result
124   if (Vec.getOpcode() == ISD::UNDEF)
125     return Result;
126   EVT VT = Vec.getValueType();
127   EVT ElVT = VT.getVectorElementType();
128   EVT ResultVT = Result.getValueType();
129
130   // Insert the relevant vectorWidth bits.
131   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
132
133   // This is the index of the first element of the vectorWidth-bit chunk
134   // we want.
135   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
136                                * ElemsPerChunk);
137
138   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
139   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
140                      VecIdx);
141 }
142 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
143 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
144 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
145 /// simple superregister reference.  Idx is an index in the 128 bits
146 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
147 /// lowering INSERT_VECTOR_ELT operations easier.
148 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
149                                   unsigned IdxVal, SelectionDAG &DAG,
150                                   SDLoc dl) {
151   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
152   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
153 }
154
155 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
156                                   unsigned IdxVal, SelectionDAG &DAG,
157                                   SDLoc dl) {
158   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
159   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
160 }
161
162 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
163 /// instructions. This is used because creating CONCAT_VECTOR nodes of
164 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
165 /// large BUILD_VECTORS.
166 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
167                                    unsigned NumElems, SelectionDAG &DAG,
168                                    SDLoc dl) {
169   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
170   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
171 }
172
173 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
174                                    unsigned NumElems, SelectionDAG &DAG,
175                                    SDLoc dl) {
176   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
177   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
178 }
179
180 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
181   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
182   bool is64Bit = Subtarget->is64Bit();
183
184   if (Subtarget->isTargetMacho()) {
185     if (is64Bit)
186       return new X86_64MachoTargetObjectFile();
187     return new TargetLoweringObjectFileMachO();
188   }
189
190   if (Subtarget->isTargetLinux())
191     return new X86LinuxTargetObjectFile();
192   if (Subtarget->isTargetELF())
193     return new TargetLoweringObjectFileELF();
194   if (Subtarget->isTargetKnownWindowsMSVC())
195     return new X86WindowsTargetObjectFile();
196   if (Subtarget->isTargetCOFF())
197     return new TargetLoweringObjectFileCOFF();
198   llvm_unreachable("unknown subtarget type");
199 }
200
201 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
202   : TargetLowering(TM, createTLOF(TM)) {
203   Subtarget = &TM.getSubtarget<X86Subtarget>();
204   X86ScalarSSEf64 = Subtarget->hasSSE2();
205   X86ScalarSSEf32 = Subtarget->hasSSE1();
206   TD = getDataLayout();
207
208   resetOperationActions();
209 }
210
211 void X86TargetLowering::resetOperationActions() {
212   const TargetMachine &TM = getTargetMachine();
213   static bool FirstTimeThrough = true;
214
215   // If none of the target options have changed, then we don't need to reset the
216   // operation actions.
217   if (!FirstTimeThrough && TO == TM.Options) return;
218
219   if (!FirstTimeThrough) {
220     // Reinitialize the actions.
221     initActions();
222     FirstTimeThrough = false;
223   }
224
225   TO = TM.Options;
226
227   // Set up the TargetLowering object.
228   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
229
230   // X86 is weird, it always uses i8 for shift amounts and setcc results.
231   setBooleanContents(ZeroOrOneBooleanContent);
232   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
233   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
234
235   // For 64-bit since we have so many registers use the ILP scheduler, for
236   // 32-bit code use the register pressure specific scheduling.
237   // For Atom, always use ILP scheduling.
238   if (Subtarget->isAtom())
239     setSchedulingPreference(Sched::ILP);
240   else if (Subtarget->is64Bit())
241     setSchedulingPreference(Sched::ILP);
242   else
243     setSchedulingPreference(Sched::RegPressure);
244   const X86RegisterInfo *RegInfo =
245     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
246   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
247
248   // Bypass expensive divides on Atom when compiling with O2
249   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
250     addBypassSlowDiv(32, 8);
251     if (Subtarget->is64Bit())
252       addBypassSlowDiv(64, 16);
253   }
254
255   if (Subtarget->isTargetKnownWindowsMSVC()) {
256     // Setup Windows compiler runtime calls.
257     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
258     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
259     setLibcallName(RTLIB::SREM_I64, "_allrem");
260     setLibcallName(RTLIB::UREM_I64, "_aullrem");
261     setLibcallName(RTLIB::MUL_I64, "_allmul");
262     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
266     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
267
268     // The _ftol2 runtime function has an unusual calling conv, which
269     // is modeled by a special pseudo-instruction.
270     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
273     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
274   }
275
276   if (Subtarget->isTargetDarwin()) {
277     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
278     setUseUnderscoreSetJmp(false);
279     setUseUnderscoreLongJmp(false);
280   } else if (Subtarget->isTargetWindowsGNU()) {
281     // MS runtime is weird: it exports _setjmp, but longjmp!
282     setUseUnderscoreSetJmp(true);
283     setUseUnderscoreLongJmp(false);
284   } else {
285     setUseUnderscoreSetJmp(true);
286     setUseUnderscoreLongJmp(true);
287   }
288
289   // Set up the register classes.
290   addRegisterClass(MVT::i8, &X86::GR8RegClass);
291   addRegisterClass(MVT::i16, &X86::GR16RegClass);
292   addRegisterClass(MVT::i32, &X86::GR32RegClass);
293   if (Subtarget->is64Bit())
294     addRegisterClass(MVT::i64, &X86::GR64RegClass);
295
296   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
297
298   // We don't accept any truncstore of integer registers.
299   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
301   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
302   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
303   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
304   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
305
306   // SETOEQ and SETUNE require checking two conditions.
307   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
308   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
313
314   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
315   // operation.
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
319
320   if (Subtarget->is64Bit()) {
321     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
323   } else if (!TM.Options.UseSoftFloat) {
324     // We have an algorithm for SSE2->double, and we turn this into a
325     // 64-bit FILD followed by conditional FADD for other targets.
326     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
327     // We have an algorithm for SSE2, and we turn this into a 64-bit
328     // FILD for other targets.
329     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
330   }
331
332   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
333   // this operation.
334   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
336
337   if (!TM.Options.UseSoftFloat) {
338     // SSE has no i16 to fp conversion, only i32
339     if (X86ScalarSSEf32) {
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
341       // f32 and f64 cases are Legal, f80 case is not
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
343     } else {
344       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
346     }
347   } else {
348     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
350   }
351
352   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
353   // are Legal, f80 is custom lowered.
354   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
355   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
356
357   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
358   // this operation.
359   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
361
362   if (X86ScalarSSEf32) {
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
364     // f32 and f64 cases are Legal, f80 case is not
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
366   } else {
367     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
369   }
370
371   // Handle FP_TO_UINT by promoting the destination to a larger signed
372   // conversion.
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
376
377   if (Subtarget->is64Bit()) {
378     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
380   } else if (!TM.Options.UseSoftFloat) {
381     // Since AVX is a superset of SSE3, only check for SSE here.
382     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
383       // Expand FP_TO_UINT into a select.
384       // FIXME: We would like to use a Custom expander here eventually to do
385       // the optimal thing for SSE vs. the default expansion in the legalizer.
386       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
387     else
388       // With SSE3 we can use fisttpll to convert to a signed i64; without
389       // SSE, we're stuck with a fistpll.
390       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
391   }
392
393   if (isTargetFTOL()) {
394     // Use the _ftol2 runtime function, which has a pseudo-instruction
395     // to handle its weird calling convention.
396     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
397   }
398
399   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
400   if (!X86ScalarSSEf64) {
401     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
402     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
403     if (Subtarget->is64Bit()) {
404       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
405       // Without SSE, i64->f64 goes through memory.
406       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
407     }
408   }
409
410   // Scalar integer divide and remainder are lowered to use operations that
411   // produce two results, to match the available instructions. This exposes
412   // the two-result form to trivial CSE, which is able to combine x/y and x%y
413   // into a single instruction.
414   //
415   // Scalar integer multiply-high is also lowered to use two-result
416   // operations, to match the available instructions. However, plain multiply
417   // (low) operations are left as Legal, as there are single-result
418   // instructions for this in x86. Using the two-result multiply instructions
419   // when both high and low results are needed must be arranged by dagcombine.
420   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
421     MVT VT = IntVTs[i];
422     setOperationAction(ISD::MULHS, VT, Expand);
423     setOperationAction(ISD::MULHU, VT, Expand);
424     setOperationAction(ISD::SDIV, VT, Expand);
425     setOperationAction(ISD::UDIV, VT, Expand);
426     setOperationAction(ISD::SREM, VT, Expand);
427     setOperationAction(ISD::UREM, VT, Expand);
428
429     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
430     setOperationAction(ISD::ADDC, VT, Custom);
431     setOperationAction(ISD::ADDE, VT, Custom);
432     setOperationAction(ISD::SUBC, VT, Custom);
433     setOperationAction(ISD::SUBE, VT, Custom);
434   }
435
436   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
437   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
438   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
445   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
446   if (Subtarget->is64Bit())
447     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
450   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
451   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
454   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
455   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
456
457   // Promote the i8 variants and force them on up to i32 which has a shorter
458   // encoding.
459   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
460   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
461   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
462   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
463   if (Subtarget->hasBMI()) {
464     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
465     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
466     if (Subtarget->is64Bit())
467       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
468   } else {
469     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
470     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
471     if (Subtarget->is64Bit())
472       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
473   }
474
475   if (Subtarget->hasLZCNT()) {
476     // When promoting the i8 variants, force them to i32 for a shorter
477     // encoding.
478     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
479     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
480     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
481     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
482     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
483     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
484     if (Subtarget->is64Bit())
485       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
486   } else {
487     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
488     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
492     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
493     if (Subtarget->is64Bit()) {
494       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
495       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
496     }
497   }
498
499   if (Subtarget->hasPOPCNT()) {
500     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
501   } else {
502     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
503     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
504     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
505     if (Subtarget->is64Bit())
506       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
507   }
508
509   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
510
511   if (!Subtarget->hasMOVBE())
512     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
513
514   // These should be promoted to a larger select which is supported.
515   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
516   // X86 wants to expand cmov itself.
517   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
518   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
522   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
528   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
529   if (Subtarget->is64Bit()) {
530     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
531     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
532   }
533   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
534   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
535   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
536   // support continuation, user-level threading, and etc.. As a result, no
537   // other SjLj exception interfaces are implemented and please don't build
538   // your own exception handling based on them.
539   // LLVM/Clang supports zero-cost DWARF exception handling.
540   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
541   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
542
543   // Darwin ABI issue.
544   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
545   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
546   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
547   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
548   if (Subtarget->is64Bit())
549     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
550   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
551   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
552   if (Subtarget->is64Bit()) {
553     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
554     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
555     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
556     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
557     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
558   }
559   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
560   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
561   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
562   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
563   if (Subtarget->is64Bit()) {
564     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
565     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
566     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
567   }
568
569   if (Subtarget->hasSSE1())
570     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
571
572   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
573
574   // Expand certain atomics
575   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
576     MVT VT = IntVTs[i];
577     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
578     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
579     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
580   }
581
582   if (!Subtarget->is64Bit()) {
583     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
594     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
595   }
596
597   if (Subtarget->hasCmpxchg16b()) {
598     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
599   }
600
601   // FIXME - use subtarget debug flags
602   if (!Subtarget->isTargetDarwin() &&
603       !Subtarget->isTargetELF() &&
604       !Subtarget->isTargetCygMing()) {
605     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
606   }
607
608   if (Subtarget->is64Bit()) {
609     setExceptionPointerRegister(X86::RAX);
610     setExceptionSelectorRegister(X86::RDX);
611   } else {
612     setExceptionPointerRegister(X86::EAX);
613     setExceptionSelectorRegister(X86::EDX);
614   }
615   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
616   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
617
618   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
619   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
620
621   setOperationAction(ISD::TRAP, MVT::Other, Legal);
622   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
623
624   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
625   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
626   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
627   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
628     // TargetInfo::X86_64ABIBuiltinVaList
629     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
630     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
631   } else {
632     // TargetInfo::CharPtrBuiltinVaList
633     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
634     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
635   }
636
637   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
638   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
639
640   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
641                      MVT::i64 : MVT::i32, Custom);
642
643   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
644     // f32 and f64 use SSE.
645     // Set up the FP register classes.
646     addRegisterClass(MVT::f32, &X86::FR32RegClass);
647     addRegisterClass(MVT::f64, &X86::FR64RegClass);
648
649     // Use ANDPD to simulate FABS.
650     setOperationAction(ISD::FABS , MVT::f64, Custom);
651     setOperationAction(ISD::FABS , MVT::f32, Custom);
652
653     // Use XORP to simulate FNEG.
654     setOperationAction(ISD::FNEG , MVT::f64, Custom);
655     setOperationAction(ISD::FNEG , MVT::f32, Custom);
656
657     // Use ANDPD and ORPD to simulate FCOPYSIGN.
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660
661     // Lower this to FGETSIGNx86 plus an AND.
662     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
663     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
664
665     // We don't support sin/cos/fmod
666     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
667     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
668     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
669     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
670     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
671     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
672
673     // Expand FP immediates into loads from the stack, except for the special
674     // cases we handle.
675     addLegalFPImmediate(APFloat(+0.0)); // xorpd
676     addLegalFPImmediate(APFloat(+0.0f)); // xorps
677   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
678     // Use SSE for f32, x87 for f64.
679     // Set up the FP register classes.
680     addRegisterClass(MVT::f32, &X86::FR32RegClass);
681     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682
683     // Use ANDPS to simulate FABS.
684     setOperationAction(ISD::FABS , MVT::f32, Custom);
685
686     // Use XORP to simulate FNEG.
687     setOperationAction(ISD::FNEG , MVT::f32, Custom);
688
689     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
690
691     // Use ANDPS and ORPS to simulate FCOPYSIGN.
692     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
693     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
694
695     // We don't support sin/cos/fmod
696     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
697     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
698     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
699
700     // Special cases we handle for FP constants.
701     addLegalFPImmediate(APFloat(+0.0f)); // xorps
702     addLegalFPImmediate(APFloat(+0.0)); // FLD0
703     addLegalFPImmediate(APFloat(+1.0)); // FLD1
704     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
705     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
706
707     if (!TM.Options.UnsafeFPMath) {
708       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
709       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
710       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
711     }
712   } else if (!TM.Options.UseSoftFloat) {
713     // f32 and f64 in x87.
714     // Set up the FP register classes.
715     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
716     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
717
718     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
719     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
720     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
722
723     if (!TM.Options.UnsafeFPMath) {
724       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
725       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
726       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
728       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
730     }
731     addLegalFPImmediate(APFloat(+0.0)); // FLD0
732     addLegalFPImmediate(APFloat(+1.0)); // FLD1
733     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
734     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
735     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
736     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
737     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
738     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
739   }
740
741   // We don't support FMA.
742   setOperationAction(ISD::FMA, MVT::f64, Expand);
743   setOperationAction(ISD::FMA, MVT::f32, Expand);
744
745   // Long double always uses X87.
746   if (!TM.Options.UseSoftFloat) {
747     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
748     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
749     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
750     {
751       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
752       addLegalFPImmediate(TmpFlt);  // FLD0
753       TmpFlt.changeSign();
754       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
755
756       bool ignored;
757       APFloat TmpFlt2(+1.0);
758       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
759                       &ignored);
760       addLegalFPImmediate(TmpFlt2);  // FLD1
761       TmpFlt2.changeSign();
762       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
763     }
764
765     if (!TM.Options.UnsafeFPMath) {
766       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
767       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
768       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
769     }
770
771     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
772     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
773     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
774     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
775     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
776     setOperationAction(ISD::FMA, MVT::f80, Expand);
777   }
778
779   // Always use a library call for pow.
780   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
781   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
783
784   setOperationAction(ISD::FLOG, MVT::f80, Expand);
785   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
787   setOperationAction(ISD::FEXP, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
789
790   // First set operation action for all vector types to either promote
791   // (for widening) or expand (for scalarization). Then we will selectively
792   // turn on ones that can be effectively codegen'd.
793   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
794            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
795     MVT VT = (MVT::SimpleValueType)i;
796     setOperationAction(ISD::ADD , VT, Expand);
797     setOperationAction(ISD::SUB , VT, Expand);
798     setOperationAction(ISD::FADD, VT, Expand);
799     setOperationAction(ISD::FNEG, VT, Expand);
800     setOperationAction(ISD::FSUB, VT, Expand);
801     setOperationAction(ISD::MUL , VT, Expand);
802     setOperationAction(ISD::FMUL, VT, Expand);
803     setOperationAction(ISD::SDIV, VT, Expand);
804     setOperationAction(ISD::UDIV, VT, Expand);
805     setOperationAction(ISD::FDIV, VT, Expand);
806     setOperationAction(ISD::SREM, VT, Expand);
807     setOperationAction(ISD::UREM, VT, Expand);
808     setOperationAction(ISD::LOAD, VT, Expand);
809     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
810     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
811     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
812     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
813     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::FABS, VT, Expand);
815     setOperationAction(ISD::FSIN, VT, Expand);
816     setOperationAction(ISD::FSINCOS, VT, Expand);
817     setOperationAction(ISD::FCOS, VT, Expand);
818     setOperationAction(ISD::FSINCOS, VT, Expand);
819     setOperationAction(ISD::FREM, VT, Expand);
820     setOperationAction(ISD::FMA,  VT, Expand);
821     setOperationAction(ISD::FPOWI, VT, Expand);
822     setOperationAction(ISD::FSQRT, VT, Expand);
823     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
824     setOperationAction(ISD::FFLOOR, VT, Expand);
825     setOperationAction(ISD::FCEIL, VT, Expand);
826     setOperationAction(ISD::FTRUNC, VT, Expand);
827     setOperationAction(ISD::FRINT, VT, Expand);
828     setOperationAction(ISD::FNEARBYINT, VT, Expand);
829     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
830     setOperationAction(ISD::MULHS, VT, Expand);
831     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
832     setOperationAction(ISD::MULHU, VT, Expand);
833     setOperationAction(ISD::SDIVREM, VT, Expand);
834     setOperationAction(ISD::UDIVREM, VT, Expand);
835     setOperationAction(ISD::FPOW, VT, Expand);
836     setOperationAction(ISD::CTPOP, VT, Expand);
837     setOperationAction(ISD::CTTZ, VT, Expand);
838     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
839     setOperationAction(ISD::CTLZ, VT, Expand);
840     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
841     setOperationAction(ISD::SHL, VT, Expand);
842     setOperationAction(ISD::SRA, VT, Expand);
843     setOperationAction(ISD::SRL, VT, Expand);
844     setOperationAction(ISD::ROTL, VT, Expand);
845     setOperationAction(ISD::ROTR, VT, Expand);
846     setOperationAction(ISD::BSWAP, VT, Expand);
847     setOperationAction(ISD::SETCC, VT, Expand);
848     setOperationAction(ISD::FLOG, VT, Expand);
849     setOperationAction(ISD::FLOG2, VT, Expand);
850     setOperationAction(ISD::FLOG10, VT, Expand);
851     setOperationAction(ISD::FEXP, VT, Expand);
852     setOperationAction(ISD::FEXP2, VT, Expand);
853     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
854     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
855     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
858     setOperationAction(ISD::TRUNCATE, VT, Expand);
859     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
860     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
861     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
862     setOperationAction(ISD::VSELECT, VT, Expand);
863     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
864              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
865       setTruncStoreAction(VT,
866                           (MVT::SimpleValueType)InnerVT, Expand);
867     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
869     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
870   }
871
872   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
873   // with -msoft-float, disable use of MMX as well.
874   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
875     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
876     // No operations on x86mmx supported, everything uses intrinsics.
877   }
878
879   // MMX-sized vectors (other than x86mmx) are expected to be expanded
880   // into smaller operations.
881   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
882   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
884   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
885   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
886   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
887   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
888   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
889   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
890   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
891   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
892   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
893   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
894   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
895   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
896   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
901   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
903   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
910
911   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
912     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
913
914     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
919     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
920     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
921     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
922     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
923     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
924     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
925     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
926   }
927
928   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
929     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
930
931     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
932     // registers cannot be used even for integer operations.
933     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
934     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
935     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
936     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
937
938     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
939     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
940     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
941     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
942     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
943     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
944     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
945     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
946     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
947     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
948     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
949     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
950     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
951     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
952     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
953     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
956     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
957     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
958     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
959     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
960
961     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
962     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
963     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
964     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
965
966     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
967     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
970     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
971
972     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
973     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
974       MVT VT = (MVT::SimpleValueType)i;
975       // Do not attempt to custom lower non-power-of-2 vectors
976       if (!isPowerOf2_32(VT.getVectorNumElements()))
977         continue;
978       // Do not attempt to custom lower non-128-bit vectors
979       if (!VT.is128BitVector())
980         continue;
981       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
982       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
983       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
984     }
985
986     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
987     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
988     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
989     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
991     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
992
993     if (Subtarget->is64Bit()) {
994       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
995       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
996     }
997
998     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
999     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1000       MVT VT = (MVT::SimpleValueType)i;
1001
1002       // Do not attempt to promote non-128-bit vectors
1003       if (!VT.is128BitVector())
1004         continue;
1005
1006       setOperationAction(ISD::AND,    VT, Promote);
1007       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1008       setOperationAction(ISD::OR,     VT, Promote);
1009       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1010       setOperationAction(ISD::XOR,    VT, Promote);
1011       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1012       setOperationAction(ISD::LOAD,   VT, Promote);
1013       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1014       setOperationAction(ISD::SELECT, VT, Promote);
1015       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1016     }
1017
1018     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1019
1020     // Custom lower v2i64 and v2f64 selects.
1021     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1022     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1023     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1024     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1025
1026     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1027     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1028
1029     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1030     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1031     // As there is no 64-bit GPR available, we need build a special custom
1032     // sequence to convert from v2i32 to v2f32.
1033     if (!Subtarget->is64Bit())
1034       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1035
1036     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1037     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1038
1039     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1040   }
1041
1042   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1043     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1044     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1045     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1046     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1047     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1051     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1053
1054     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1055     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1056     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1057     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1058     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1059     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1060     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1061     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1062     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1063     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1064
1065     // FIXME: Do we need to handle scalar-to-vector here?
1066     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1067
1068     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1069     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1070     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1071     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1072     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1073
1074     // i8 and i16 vectors are custom , because the source register and source
1075     // source memory operand types are not the same width.  f32 vectors are
1076     // custom since the immediate controlling the insert encodes additional
1077     // information.
1078     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1079     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1080     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1081     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1082
1083     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1084     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1085     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1086     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1087
1088     // FIXME: these should be Legal but thats only for the case where
1089     // the index is constant.  For now custom expand to deal with that.
1090     if (Subtarget->is64Bit()) {
1091       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1092       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1093     }
1094   }
1095
1096   if (Subtarget->hasSSE2()) {
1097     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1098     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1099
1100     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1101     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1102
1103     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1104     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1105
1106     // In the customized shift lowering, the legal cases in AVX2 will be
1107     // recognized.
1108     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1109     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1110
1111     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1112     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1113
1114     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1115   }
1116
1117   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1118     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1120     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1122     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1123     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1124
1125     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1126     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1127     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1128
1129     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1133     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1135     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1137     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1138     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1139     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1140     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1141
1142     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1145     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1146     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1148     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1150     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1151     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1152     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1153     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1154
1155     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1156     // even though v8i16 is a legal type.
1157     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1158     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1159     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1160
1161     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1162     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1163     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1164
1165     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1166     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1167
1168     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1169
1170     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1171     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1172
1173     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1174     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1175
1176     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1177     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1178
1179     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1182     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1183
1184     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1185     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1186     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1187
1188     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1191     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1192
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1195     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1198     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1200     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1201     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1203     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1204     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1205
1206     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1207       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1209       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1210       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1211       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1212       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1213     }
1214
1215     if (Subtarget->hasInt256()) {
1216       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1218       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1219       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1220
1221       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1223       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1224       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1225
1226       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1227       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1228       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1229       // Don't lower v32i8 because there is no 128-bit byte mul
1230
1231       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1232       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1233       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1234       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1235
1236       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1237     } else {
1238       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1239       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1240       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1241       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1242
1243       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1244       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1245       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1246       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1247
1248       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1249       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1250       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1251       // Don't lower v32i8 because there is no 128-bit byte mul
1252     }
1253
1254     // In the customized shift lowering, the legal cases in AVX2 will be
1255     // recognized.
1256     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1257     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1258
1259     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1260     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1261
1262     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1263
1264     // Custom lower several nodes for 256-bit types.
1265     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1266              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1267       MVT VT = (MVT::SimpleValueType)i;
1268
1269       // Extract subvector is special because the value type
1270       // (result) is 128-bit but the source is 256-bit wide.
1271       if (VT.is128BitVector())
1272         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1273
1274       // Do not attempt to custom lower other non-256-bit vectors
1275       if (!VT.is256BitVector())
1276         continue;
1277
1278       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1279       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1280       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1281       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1282       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1283       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1284       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1285     }
1286
1287     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1288     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1289       MVT VT = (MVT::SimpleValueType)i;
1290
1291       // Do not attempt to promote non-256-bit vectors
1292       if (!VT.is256BitVector())
1293         continue;
1294
1295       setOperationAction(ISD::AND,    VT, Promote);
1296       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1297       setOperationAction(ISD::OR,     VT, Promote);
1298       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1299       setOperationAction(ISD::XOR,    VT, Promote);
1300       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1301       setOperationAction(ISD::LOAD,   VT, Promote);
1302       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1303       setOperationAction(ISD::SELECT, VT, Promote);
1304       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1305     }
1306   }
1307
1308   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1309     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1310     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1311     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1312     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1313
1314     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1315     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1316     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1317
1318     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1319     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1320     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1321     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1322     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1323     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1324     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1325     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1327     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1328     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1329
1330     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1331     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1332     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1333     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1334     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1335     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1336
1337     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1338     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1340     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1342     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1343     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1344     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1345
1346     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1347     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1348     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1349     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1350     if (Subtarget->is64Bit()) {
1351       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1352       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1353       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1354       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1355     }
1356     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1358     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1359     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1360     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1361     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1363     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1364     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1365     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1366
1367     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1368     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1369     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1370     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1371     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1372     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1373     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1374     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1375     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1376     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1377     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1378     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1379     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1380
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1382     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1383     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1384     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1389     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1390
1391     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1392
1393     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1394     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1395     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1396     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1397     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1398     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1399     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1400     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1401     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1402
1403     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1404     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1405
1406     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1407     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1408
1409     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1410
1411     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1412     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1413
1414     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1415     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1416
1417     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1418     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1419
1420     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1421     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1422     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1423     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1424     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1425     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1426
1427     // Custom lower several nodes.
1428     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1429              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1430       MVT VT = (MVT::SimpleValueType)i;
1431
1432       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1433       // Extract subvector is special because the value type
1434       // (result) is 256/128-bit but the source is 512-bit wide.
1435       if (VT.is128BitVector() || VT.is256BitVector())
1436         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1437
1438       if (VT.getVectorElementType() == MVT::i1)
1439         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1440
1441       // Do not attempt to custom lower other non-512-bit vectors
1442       if (!VT.is512BitVector())
1443         continue;
1444
1445       if ( EltSize >= 32) {
1446         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1447         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1448         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1449         setOperationAction(ISD::VSELECT,             VT, Legal);
1450         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1451         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1452         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1453       }
1454     }
1455     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1456       MVT VT = (MVT::SimpleValueType)i;
1457
1458       // Do not attempt to promote non-256-bit vectors
1459       if (!VT.is512BitVector())
1460         continue;
1461
1462       setOperationAction(ISD::SELECT, VT, Promote);
1463       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1464     }
1465   }// has  AVX-512
1466
1467   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1468   // of this type with custom code.
1469   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1470            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1471     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1472                        Custom);
1473   }
1474
1475   // We want to custom lower some of our intrinsics.
1476   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1477   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1478   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1479   if (!Subtarget->is64Bit())
1480     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1481
1482   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1483   // handle type legalization for these operations here.
1484   //
1485   // FIXME: We really should do custom legalization for addition and
1486   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1487   // than generic legalization for 64-bit multiplication-with-overflow, though.
1488   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1489     // Add/Sub/Mul with overflow operations are custom lowered.
1490     MVT VT = IntVTs[i];
1491     setOperationAction(ISD::SADDO, VT, Custom);
1492     setOperationAction(ISD::UADDO, VT, Custom);
1493     setOperationAction(ISD::SSUBO, VT, Custom);
1494     setOperationAction(ISD::USUBO, VT, Custom);
1495     setOperationAction(ISD::SMULO, VT, Custom);
1496     setOperationAction(ISD::UMULO, VT, Custom);
1497   }
1498
1499   // There are no 8-bit 3-address imul/mul instructions
1500   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1501   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1502
1503   if (!Subtarget->is64Bit()) {
1504     // These libcalls are not available in 32-bit.
1505     setLibcallName(RTLIB::SHL_I128, nullptr);
1506     setLibcallName(RTLIB::SRL_I128, nullptr);
1507     setLibcallName(RTLIB::SRA_I128, nullptr);
1508   }
1509
1510   // Combine sin / cos into one node or libcall if possible.
1511   if (Subtarget->hasSinCos()) {
1512     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1513     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1514     if (Subtarget->isTargetDarwin()) {
1515       // For MacOSX, we don't want to the normal expansion of a libcall to
1516       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1517       // traffic.
1518       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1519       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1520     }
1521   }
1522
1523   // We have target-specific dag combine patterns for the following nodes:
1524   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1525   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1526   setTargetDAGCombine(ISD::VSELECT);
1527   setTargetDAGCombine(ISD::SELECT);
1528   setTargetDAGCombine(ISD::SHL);
1529   setTargetDAGCombine(ISD::SRA);
1530   setTargetDAGCombine(ISD::SRL);
1531   setTargetDAGCombine(ISD::OR);
1532   setTargetDAGCombine(ISD::AND);
1533   setTargetDAGCombine(ISD::ADD);
1534   setTargetDAGCombine(ISD::FADD);
1535   setTargetDAGCombine(ISD::FSUB);
1536   setTargetDAGCombine(ISD::FMA);
1537   setTargetDAGCombine(ISD::SUB);
1538   setTargetDAGCombine(ISD::LOAD);
1539   setTargetDAGCombine(ISD::STORE);
1540   setTargetDAGCombine(ISD::ZERO_EXTEND);
1541   setTargetDAGCombine(ISD::ANY_EXTEND);
1542   setTargetDAGCombine(ISD::SIGN_EXTEND);
1543   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1544   setTargetDAGCombine(ISD::TRUNCATE);
1545   setTargetDAGCombine(ISD::SINT_TO_FP);
1546   setTargetDAGCombine(ISD::SETCC);
1547   if (Subtarget->is64Bit())
1548     setTargetDAGCombine(ISD::MUL);
1549   setTargetDAGCombine(ISD::XOR);
1550
1551   computeRegisterProperties();
1552
1553   // On Darwin, -Os means optimize for size without hurting performance,
1554   // do not reduce the limit.
1555   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1556   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1557   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1558   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1559   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1560   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1561   setPrefLoopAlignment(4); // 2^4 bytes.
1562
1563   // Predictable cmov don't hurt on atom because it's in-order.
1564   PredictableSelectIsExpensive = !Subtarget->isAtom();
1565
1566   setPrefFunctionAlignment(4); // 2^4 bytes.
1567 }
1568
1569 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1570   if (!VT.isVector())
1571     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1572
1573   if (Subtarget->hasAVX512())
1574     switch(VT.getVectorNumElements()) {
1575     case  8: return MVT::v8i1;
1576     case 16: return MVT::v16i1;
1577   }
1578
1579   return VT.changeVectorElementTypeToInteger();
1580 }
1581
1582 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1583 /// the desired ByVal argument alignment.
1584 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1585   if (MaxAlign == 16)
1586     return;
1587   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1588     if (VTy->getBitWidth() == 128)
1589       MaxAlign = 16;
1590   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1591     unsigned EltAlign = 0;
1592     getMaxByValAlign(ATy->getElementType(), EltAlign);
1593     if (EltAlign > MaxAlign)
1594       MaxAlign = EltAlign;
1595   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1596     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1597       unsigned EltAlign = 0;
1598       getMaxByValAlign(STy->getElementType(i), EltAlign);
1599       if (EltAlign > MaxAlign)
1600         MaxAlign = EltAlign;
1601       if (MaxAlign == 16)
1602         break;
1603     }
1604   }
1605 }
1606
1607 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1608 /// function arguments in the caller parameter area. For X86, aggregates
1609 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1610 /// are at 4-byte boundaries.
1611 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1612   if (Subtarget->is64Bit()) {
1613     // Max of 8 and alignment of type.
1614     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1615     if (TyAlign > 8)
1616       return TyAlign;
1617     return 8;
1618   }
1619
1620   unsigned Align = 4;
1621   if (Subtarget->hasSSE1())
1622     getMaxByValAlign(Ty, Align);
1623   return Align;
1624 }
1625
1626 /// getOptimalMemOpType - Returns the target specific optimal type for load
1627 /// and store operations as a result of memset, memcpy, and memmove
1628 /// lowering. If DstAlign is zero that means it's safe to destination
1629 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1630 /// means there isn't a need to check it against alignment requirement,
1631 /// probably because the source does not need to be loaded. If 'IsMemset' is
1632 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1633 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1634 /// source is constant so it does not need to be loaded.
1635 /// It returns EVT::Other if the type should be determined using generic
1636 /// target-independent logic.
1637 EVT
1638 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1639                                        unsigned DstAlign, unsigned SrcAlign,
1640                                        bool IsMemset, bool ZeroMemset,
1641                                        bool MemcpyStrSrc,
1642                                        MachineFunction &MF) const {
1643   const Function *F = MF.getFunction();
1644   if ((!IsMemset || ZeroMemset) &&
1645       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1646                                        Attribute::NoImplicitFloat)) {
1647     if (Size >= 16 &&
1648         (Subtarget->isUnalignedMemAccessFast() ||
1649          ((DstAlign == 0 || DstAlign >= 16) &&
1650           (SrcAlign == 0 || SrcAlign >= 16)))) {
1651       if (Size >= 32) {
1652         if (Subtarget->hasInt256())
1653           return MVT::v8i32;
1654         if (Subtarget->hasFp256())
1655           return MVT::v8f32;
1656       }
1657       if (Subtarget->hasSSE2())
1658         return MVT::v4i32;
1659       if (Subtarget->hasSSE1())
1660         return MVT::v4f32;
1661     } else if (!MemcpyStrSrc && Size >= 8 &&
1662                !Subtarget->is64Bit() &&
1663                Subtarget->hasSSE2()) {
1664       // Do not use f64 to lower memcpy if source is string constant. It's
1665       // better to use i32 to avoid the loads.
1666       return MVT::f64;
1667     }
1668   }
1669   if (Subtarget->is64Bit() && Size >= 8)
1670     return MVT::i64;
1671   return MVT::i32;
1672 }
1673
1674 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1675   if (VT == MVT::f32)
1676     return X86ScalarSSEf32;
1677   else if (VT == MVT::f64)
1678     return X86ScalarSSEf64;
1679   return true;
1680 }
1681
1682 bool
1683 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1684                                                  unsigned,
1685                                                  bool *Fast) const {
1686   if (Fast)
1687     *Fast = Subtarget->isUnalignedMemAccessFast();
1688   return true;
1689 }
1690
1691 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1692 /// current function.  The returned value is a member of the
1693 /// MachineJumpTableInfo::JTEntryKind enum.
1694 unsigned X86TargetLowering::getJumpTableEncoding() const {
1695   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1696   // symbol.
1697   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1698       Subtarget->isPICStyleGOT())
1699     return MachineJumpTableInfo::EK_Custom32;
1700
1701   // Otherwise, use the normal jump table encoding heuristics.
1702   return TargetLowering::getJumpTableEncoding();
1703 }
1704
1705 const MCExpr *
1706 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1707                                              const MachineBasicBlock *MBB,
1708                                              unsigned uid,MCContext &Ctx) const{
1709   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1710          Subtarget->isPICStyleGOT());
1711   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1712   // entries.
1713   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1714                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1715 }
1716
1717 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1718 /// jumptable.
1719 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1720                                                     SelectionDAG &DAG) const {
1721   if (!Subtarget->is64Bit())
1722     // This doesn't have SDLoc associated with it, but is not really the
1723     // same as a Register.
1724     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1725   return Table;
1726 }
1727
1728 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1729 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1730 /// MCExpr.
1731 const MCExpr *X86TargetLowering::
1732 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1733                              MCContext &Ctx) const {
1734   // X86-64 uses RIP relative addressing based on the jump table label.
1735   if (Subtarget->isPICStyleRIPRel())
1736     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1737
1738   // Otherwise, the reference is relative to the PIC base.
1739   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1740 }
1741
1742 // FIXME: Why this routine is here? Move to RegInfo!
1743 std::pair<const TargetRegisterClass*, uint8_t>
1744 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1745   const TargetRegisterClass *RRC = nullptr;
1746   uint8_t Cost = 1;
1747   switch (VT.SimpleTy) {
1748   default:
1749     return TargetLowering::findRepresentativeClass(VT);
1750   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1751     RRC = Subtarget->is64Bit() ?
1752       (const TargetRegisterClass*)&X86::GR64RegClass :
1753       (const TargetRegisterClass*)&X86::GR32RegClass;
1754     break;
1755   case MVT::x86mmx:
1756     RRC = &X86::VR64RegClass;
1757     break;
1758   case MVT::f32: case MVT::f64:
1759   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1760   case MVT::v4f32: case MVT::v2f64:
1761   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1762   case MVT::v4f64:
1763     RRC = &X86::VR128RegClass;
1764     break;
1765   }
1766   return std::make_pair(RRC, Cost);
1767 }
1768
1769 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1770                                                unsigned &Offset) const {
1771   if (!Subtarget->isTargetLinux())
1772     return false;
1773
1774   if (Subtarget->is64Bit()) {
1775     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1776     Offset = 0x28;
1777     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1778       AddressSpace = 256;
1779     else
1780       AddressSpace = 257;
1781   } else {
1782     // %gs:0x14 on i386
1783     Offset = 0x14;
1784     AddressSpace = 256;
1785   }
1786   return true;
1787 }
1788
1789 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1790                                             unsigned DestAS) const {
1791   assert(SrcAS != DestAS && "Expected different address spaces!");
1792
1793   return SrcAS < 256 && DestAS < 256;
1794 }
1795
1796 //===----------------------------------------------------------------------===//
1797 //               Return Value Calling Convention Implementation
1798 //===----------------------------------------------------------------------===//
1799
1800 #include "X86GenCallingConv.inc"
1801
1802 bool
1803 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1804                                   MachineFunction &MF, bool isVarArg,
1805                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1806                         LLVMContext &Context) const {
1807   SmallVector<CCValAssign, 16> RVLocs;
1808   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1809                  RVLocs, Context);
1810   return CCInfo.CheckReturn(Outs, RetCC_X86);
1811 }
1812
1813 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1814   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1815   return ScratchRegs;
1816 }
1817
1818 SDValue
1819 X86TargetLowering::LowerReturn(SDValue Chain,
1820                                CallingConv::ID CallConv, bool isVarArg,
1821                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1822                                const SmallVectorImpl<SDValue> &OutVals,
1823                                SDLoc dl, SelectionDAG &DAG) const {
1824   MachineFunction &MF = DAG.getMachineFunction();
1825   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1826
1827   SmallVector<CCValAssign, 16> RVLocs;
1828   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1829                  RVLocs, *DAG.getContext());
1830   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1831
1832   SDValue Flag;
1833   SmallVector<SDValue, 6> RetOps;
1834   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1835   // Operand #1 = Bytes To Pop
1836   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1837                    MVT::i16));
1838
1839   // Copy the result values into the output registers.
1840   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1841     CCValAssign &VA = RVLocs[i];
1842     assert(VA.isRegLoc() && "Can only return in registers!");
1843     SDValue ValToCopy = OutVals[i];
1844     EVT ValVT = ValToCopy.getValueType();
1845
1846     // Promote values to the appropriate types
1847     if (VA.getLocInfo() == CCValAssign::SExt)
1848       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849     else if (VA.getLocInfo() == CCValAssign::ZExt)
1850       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1851     else if (VA.getLocInfo() == CCValAssign::AExt)
1852       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1853     else if (VA.getLocInfo() == CCValAssign::BCvt)
1854       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1855
1856     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1857            "Unexpected FP-extend for return value.");  
1858
1859     // If this is x86-64, and we disabled SSE, we can't return FP values,
1860     // or SSE or MMX vectors.
1861     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1862          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1863           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1864       report_fatal_error("SSE register return with SSE disabled");
1865     }
1866     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1867     // llvm-gcc has never done it right and no one has noticed, so this
1868     // should be OK for now.
1869     if (ValVT == MVT::f64 &&
1870         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1871       report_fatal_error("SSE2 register return with SSE2 disabled");
1872
1873     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1874     // the RET instruction and handled by the FP Stackifier.
1875     if (VA.getLocReg() == X86::ST0 ||
1876         VA.getLocReg() == X86::ST1) {
1877       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1878       // change the value to the FP stack register class.
1879       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1880         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1881       RetOps.push_back(ValToCopy);
1882       // Don't emit a copytoreg.
1883       continue;
1884     }
1885
1886     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1887     // which is returned in RAX / RDX.
1888     if (Subtarget->is64Bit()) {
1889       if (ValVT == MVT::x86mmx) {
1890         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1891           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1892           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1893                                   ValToCopy);
1894           // If we don't have SSE2 available, convert to v4f32 so the generated
1895           // register is legal.
1896           if (!Subtarget->hasSSE2())
1897             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1898         }
1899       }
1900     }
1901
1902     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1903     Flag = Chain.getValue(1);
1904     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1905   }
1906
1907   // The x86-64 ABIs require that for returning structs by value we copy
1908   // the sret argument into %rax/%eax (depending on ABI) for the return.
1909   // Win32 requires us to put the sret argument to %eax as well.
1910   // We saved the argument into a virtual register in the entry block,
1911   // so now we copy the value out and into %rax/%eax.
1912   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1913       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1914     MachineFunction &MF = DAG.getMachineFunction();
1915     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1916     unsigned Reg = FuncInfo->getSRetReturnReg();
1917     assert(Reg &&
1918            "SRetReturnReg should have been set in LowerFormalArguments().");
1919     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1920
1921     unsigned RetValReg
1922         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1923           X86::RAX : X86::EAX;
1924     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1925     Flag = Chain.getValue(1);
1926
1927     // RAX/EAX now acts like a return value.
1928     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1929   }
1930
1931   RetOps[0] = Chain;  // Update chain.
1932
1933   // Add the flag if we have it.
1934   if (Flag.getNode())
1935     RetOps.push_back(Flag);
1936
1937   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1938 }
1939
1940 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1941   if (N->getNumValues() != 1)
1942     return false;
1943   if (!N->hasNUsesOfValue(1, 0))
1944     return false;
1945
1946   SDValue TCChain = Chain;
1947   SDNode *Copy = *N->use_begin();
1948   if (Copy->getOpcode() == ISD::CopyToReg) {
1949     // If the copy has a glue operand, we conservatively assume it isn't safe to
1950     // perform a tail call.
1951     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1952       return false;
1953     TCChain = Copy->getOperand(0);
1954   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1955     return false;
1956
1957   bool HasRet = false;
1958   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1959        UI != UE; ++UI) {
1960     if (UI->getOpcode() != X86ISD::RET_FLAG)
1961       return false;
1962     HasRet = true;
1963   }
1964
1965   if (!HasRet)
1966     return false;
1967
1968   Chain = TCChain;
1969   return true;
1970 }
1971
1972 MVT
1973 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1974                                             ISD::NodeType ExtendKind) const {
1975   MVT ReturnMVT;
1976   // TODO: Is this also valid on 32-bit?
1977   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1978     ReturnMVT = MVT::i8;
1979   else
1980     ReturnMVT = MVT::i32;
1981
1982   MVT MinVT = getRegisterType(ReturnMVT);
1983   return VT.bitsLT(MinVT) ? MinVT : VT;
1984 }
1985
1986 /// LowerCallResult - Lower the result values of a call into the
1987 /// appropriate copies out of appropriate physical registers.
1988 ///
1989 SDValue
1990 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1991                                    CallingConv::ID CallConv, bool isVarArg,
1992                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1993                                    SDLoc dl, SelectionDAG &DAG,
1994                                    SmallVectorImpl<SDValue> &InVals) const {
1995
1996   // Assign locations to each value returned by this call.
1997   SmallVector<CCValAssign, 16> RVLocs;
1998   bool Is64Bit = Subtarget->is64Bit();
1999   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2000                  getTargetMachine(), RVLocs, *DAG.getContext());
2001   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2002
2003   // Copy all of the result registers out of their specified physreg.
2004   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2005     CCValAssign &VA = RVLocs[i];
2006     EVT CopyVT = VA.getValVT();
2007
2008     // If this is x86-64, and we disabled SSE, we can't return FP values
2009     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2010         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2011       report_fatal_error("SSE register return with SSE disabled");
2012     }
2013
2014     SDValue Val;
2015
2016     // If this is a call to a function that returns an fp value on the floating
2017     // point stack, we must guarantee the value is popped from the stack, so
2018     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2019     // if the return value is not used. We use the FpPOP_RETVAL instruction
2020     // instead.
2021     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2022       // If we prefer to use the value in xmm registers, copy it out as f80 and
2023       // use a truncate to move it from fp stack reg to xmm reg.
2024       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2025       SDValue Ops[] = { Chain, InFlag };
2026       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2027                                          MVT::Other, MVT::Glue, Ops), 1);
2028       Val = Chain.getValue(0);
2029
2030       // Round the f80 to the right size, which also moves it to the appropriate
2031       // xmm register.
2032       if (CopyVT != VA.getValVT())
2033         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2034                           // This truncation won't change the value.
2035                           DAG.getIntPtrConstant(1));
2036     } else {
2037       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2038                                  CopyVT, InFlag).getValue(1);
2039       Val = Chain.getValue(0);
2040     }
2041     InFlag = Chain.getValue(2);
2042     InVals.push_back(Val);
2043   }
2044
2045   return Chain;
2046 }
2047
2048 //===----------------------------------------------------------------------===//
2049 //                C & StdCall & Fast Calling Convention implementation
2050 //===----------------------------------------------------------------------===//
2051 //  StdCall calling convention seems to be standard for many Windows' API
2052 //  routines and around. It differs from C calling convention just a little:
2053 //  callee should clean up the stack, not caller. Symbols should be also
2054 //  decorated in some fancy way :) It doesn't support any vector arguments.
2055 //  For info on fast calling convention see Fast Calling Convention (tail call)
2056 //  implementation LowerX86_32FastCCCallTo.
2057
2058 /// CallIsStructReturn - Determines whether a call uses struct return
2059 /// semantics.
2060 enum StructReturnType {
2061   NotStructReturn,
2062   RegStructReturn,
2063   StackStructReturn
2064 };
2065 static StructReturnType
2066 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2067   if (Outs.empty())
2068     return NotStructReturn;
2069
2070   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2071   if (!Flags.isSRet())
2072     return NotStructReturn;
2073   if (Flags.isInReg())
2074     return RegStructReturn;
2075   return StackStructReturn;
2076 }
2077
2078 /// ArgsAreStructReturn - Determines whether a function uses struct
2079 /// return semantics.
2080 static StructReturnType
2081 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2082   if (Ins.empty())
2083     return NotStructReturn;
2084
2085   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2086   if (!Flags.isSRet())
2087     return NotStructReturn;
2088   if (Flags.isInReg())
2089     return RegStructReturn;
2090   return StackStructReturn;
2091 }
2092
2093 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2094 /// by "Src" to address "Dst" with size and alignment information specified by
2095 /// the specific parameter attribute. The copy will be passed as a byval
2096 /// function parameter.
2097 static SDValue
2098 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2099                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2100                           SDLoc dl) {
2101   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2102
2103   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2104                        /*isVolatile*/false, /*AlwaysInline=*/true,
2105                        MachinePointerInfo(), MachinePointerInfo());
2106 }
2107
2108 /// IsTailCallConvention - Return true if the calling convention is one that
2109 /// supports tail call optimization.
2110 static bool IsTailCallConvention(CallingConv::ID CC) {
2111   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2112           CC == CallingConv::HiPE);
2113 }
2114
2115 /// \brief Return true if the calling convention is a C calling convention.
2116 static bool IsCCallConvention(CallingConv::ID CC) {
2117   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2118           CC == CallingConv::X86_64_SysV);
2119 }
2120
2121 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2122   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2123     return false;
2124
2125   CallSite CS(CI);
2126   CallingConv::ID CalleeCC = CS.getCallingConv();
2127   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2128     return false;
2129
2130   return true;
2131 }
2132
2133 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2134 /// a tailcall target by changing its ABI.
2135 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2136                                    bool GuaranteedTailCallOpt) {
2137   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2138 }
2139
2140 SDValue
2141 X86TargetLowering::LowerMemArgument(SDValue Chain,
2142                                     CallingConv::ID CallConv,
2143                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2144                                     SDLoc dl, SelectionDAG &DAG,
2145                                     const CCValAssign &VA,
2146                                     MachineFrameInfo *MFI,
2147                                     unsigned i) const {
2148   // Create the nodes corresponding to a load from this parameter slot.
2149   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2150   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2151                               getTargetMachine().Options.GuaranteedTailCallOpt);
2152   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2153   EVT ValVT;
2154
2155   // If value is passed by pointer we have address passed instead of the value
2156   // itself.
2157   if (VA.getLocInfo() == CCValAssign::Indirect)
2158     ValVT = VA.getLocVT();
2159   else
2160     ValVT = VA.getValVT();
2161
2162   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2163   // changed with more analysis.
2164   // In case of tail call optimization mark all arguments mutable. Since they
2165   // could be overwritten by lowering of arguments in case of a tail call.
2166   if (Flags.isByVal()) {
2167     unsigned Bytes = Flags.getByValSize();
2168     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2169     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2170     return DAG.getFrameIndex(FI, getPointerTy());
2171   } else {
2172     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2173                                     VA.getLocMemOffset(), isImmutable);
2174     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2175     return DAG.getLoad(ValVT, dl, Chain, FIN,
2176                        MachinePointerInfo::getFixedStack(FI),
2177                        false, false, false, 0);
2178   }
2179 }
2180
2181 SDValue
2182 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2183                                         CallingConv::ID CallConv,
2184                                         bool isVarArg,
2185                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2186                                         SDLoc dl,
2187                                         SelectionDAG &DAG,
2188                                         SmallVectorImpl<SDValue> &InVals)
2189                                           const {
2190   MachineFunction &MF = DAG.getMachineFunction();
2191   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2192
2193   const Function* Fn = MF.getFunction();
2194   if (Fn->hasExternalLinkage() &&
2195       Subtarget->isTargetCygMing() &&
2196       Fn->getName() == "main")
2197     FuncInfo->setForceFramePointer(true);
2198
2199   MachineFrameInfo *MFI = MF.getFrameInfo();
2200   bool Is64Bit = Subtarget->is64Bit();
2201   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2202
2203   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2204          "Var args not supported with calling convention fastcc, ghc or hipe");
2205
2206   // Assign locations to all of the incoming arguments.
2207   SmallVector<CCValAssign, 16> ArgLocs;
2208   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2209                  ArgLocs, *DAG.getContext());
2210
2211   // Allocate shadow area for Win64
2212   if (IsWin64)
2213     CCInfo.AllocateStack(32, 8);
2214
2215   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2216
2217   unsigned LastVal = ~0U;
2218   SDValue ArgValue;
2219   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2220     CCValAssign &VA = ArgLocs[i];
2221     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2222     // places.
2223     assert(VA.getValNo() != LastVal &&
2224            "Don't support value assigned to multiple locs yet");
2225     (void)LastVal;
2226     LastVal = VA.getValNo();
2227
2228     if (VA.isRegLoc()) {
2229       EVT RegVT = VA.getLocVT();
2230       const TargetRegisterClass *RC;
2231       if (RegVT == MVT::i32)
2232         RC = &X86::GR32RegClass;
2233       else if (Is64Bit && RegVT == MVT::i64)
2234         RC = &X86::GR64RegClass;
2235       else if (RegVT == MVT::f32)
2236         RC = &X86::FR32RegClass;
2237       else if (RegVT == MVT::f64)
2238         RC = &X86::FR64RegClass;
2239       else if (RegVT.is512BitVector())
2240         RC = &X86::VR512RegClass;
2241       else if (RegVT.is256BitVector())
2242         RC = &X86::VR256RegClass;
2243       else if (RegVT.is128BitVector())
2244         RC = &X86::VR128RegClass;
2245       else if (RegVT == MVT::x86mmx)
2246         RC = &X86::VR64RegClass;
2247       else if (RegVT == MVT::i1)
2248         RC = &X86::VK1RegClass;
2249       else if (RegVT == MVT::v8i1)
2250         RC = &X86::VK8RegClass;
2251       else if (RegVT == MVT::v16i1)
2252         RC = &X86::VK16RegClass;
2253       else
2254         llvm_unreachable("Unknown argument type!");
2255
2256       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2257       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2258
2259       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2260       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2261       // right size.
2262       if (VA.getLocInfo() == CCValAssign::SExt)
2263         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2264                                DAG.getValueType(VA.getValVT()));
2265       else if (VA.getLocInfo() == CCValAssign::ZExt)
2266         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2267                                DAG.getValueType(VA.getValVT()));
2268       else if (VA.getLocInfo() == CCValAssign::BCvt)
2269         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2270
2271       if (VA.isExtInLoc()) {
2272         // Handle MMX values passed in XMM regs.
2273         if (RegVT.isVector())
2274           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2275         else
2276           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2277       }
2278     } else {
2279       assert(VA.isMemLoc());
2280       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2281     }
2282
2283     // If value is passed via pointer - do a load.
2284     if (VA.getLocInfo() == CCValAssign::Indirect)
2285       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2286                              MachinePointerInfo(), false, false, false, 0);
2287
2288     InVals.push_back(ArgValue);
2289   }
2290
2291   // The x86-64 ABIs require that for returning structs by value we copy
2292   // the sret argument into %rax/%eax (depending on ABI) for the return.
2293   // Win32 requires us to put the sret argument to %eax as well.
2294   // Save the argument into a virtual register so that we can access it
2295   // from the return points.
2296   if (MF.getFunction()->hasStructRetAttr() &&
2297       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2298     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2299     unsigned Reg = FuncInfo->getSRetReturnReg();
2300     if (!Reg) {
2301       MVT PtrTy = getPointerTy();
2302       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2303       FuncInfo->setSRetReturnReg(Reg);
2304     }
2305     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2306     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2307   }
2308
2309   unsigned StackSize = CCInfo.getNextStackOffset();
2310   // Align stack specially for tail calls.
2311   if (FuncIsMadeTailCallSafe(CallConv,
2312                              MF.getTarget().Options.GuaranteedTailCallOpt))
2313     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2314
2315   // If the function takes variable number of arguments, make a frame index for
2316   // the start of the first vararg value... for expansion of llvm.va_start.
2317   if (isVarArg) {
2318     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2319                     CallConv != CallingConv::X86_ThisCall)) {
2320       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2321     }
2322     if (Is64Bit) {
2323       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2324
2325       // FIXME: We should really autogenerate these arrays
2326       static const MCPhysReg GPR64ArgRegsWin64[] = {
2327         X86::RCX, X86::RDX, X86::R8,  X86::R9
2328       };
2329       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2330         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2331       };
2332       static const MCPhysReg XMMArgRegs64Bit[] = {
2333         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2334         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2335       };
2336       const MCPhysReg *GPR64ArgRegs;
2337       unsigned NumXMMRegs = 0;
2338
2339       if (IsWin64) {
2340         // The XMM registers which might contain var arg parameters are shadowed
2341         // in their paired GPR.  So we only need to save the GPR to their home
2342         // slots.
2343         TotalNumIntRegs = 4;
2344         GPR64ArgRegs = GPR64ArgRegsWin64;
2345       } else {
2346         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2347         GPR64ArgRegs = GPR64ArgRegs64Bit;
2348
2349         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2350                                                 TotalNumXMMRegs);
2351       }
2352       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2353                                                        TotalNumIntRegs);
2354
2355       bool NoImplicitFloatOps = Fn->getAttributes().
2356         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2357       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2358              "SSE register cannot be used when SSE is disabled!");
2359       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2360                NoImplicitFloatOps) &&
2361              "SSE register cannot be used when SSE is disabled!");
2362       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2363           !Subtarget->hasSSE1())
2364         // Kernel mode asks for SSE to be disabled, so don't push them
2365         // on the stack.
2366         TotalNumXMMRegs = 0;
2367
2368       if (IsWin64) {
2369         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2370         // Get to the caller-allocated home save location.  Add 8 to account
2371         // for the return address.
2372         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2373         FuncInfo->setRegSaveFrameIndex(
2374           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2375         // Fixup to set vararg frame on shadow area (4 x i64).
2376         if (NumIntRegs < 4)
2377           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2378       } else {
2379         // For X86-64, if there are vararg parameters that are passed via
2380         // registers, then we must store them to their spots on the stack so
2381         // they may be loaded by deferencing the result of va_next.
2382         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2383         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2384         FuncInfo->setRegSaveFrameIndex(
2385           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2386                                false));
2387       }
2388
2389       // Store the integer parameter registers.
2390       SmallVector<SDValue, 8> MemOps;
2391       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2392                                         getPointerTy());
2393       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2394       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2395         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2396                                   DAG.getIntPtrConstant(Offset));
2397         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2398                                      &X86::GR64RegClass);
2399         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2400         SDValue Store =
2401           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2402                        MachinePointerInfo::getFixedStack(
2403                          FuncInfo->getRegSaveFrameIndex(), Offset),
2404                        false, false, 0);
2405         MemOps.push_back(Store);
2406         Offset += 8;
2407       }
2408
2409       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2410         // Now store the XMM (fp + vector) parameter registers.
2411         SmallVector<SDValue, 11> SaveXMMOps;
2412         SaveXMMOps.push_back(Chain);
2413
2414         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2415         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2416         SaveXMMOps.push_back(ALVal);
2417
2418         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2419                                FuncInfo->getRegSaveFrameIndex()));
2420         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2421                                FuncInfo->getVarArgsFPOffset()));
2422
2423         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2424           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2425                                        &X86::VR128RegClass);
2426           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2427           SaveXMMOps.push_back(Val);
2428         }
2429         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2430                                      MVT::Other, SaveXMMOps));
2431       }
2432
2433       if (!MemOps.empty())
2434         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2435     }
2436   }
2437
2438   // Some CCs need callee pop.
2439   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2440                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2441     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2442   } else {
2443     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2444     // If this is an sret function, the return should pop the hidden pointer.
2445     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2446         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2447         argsAreStructReturn(Ins) == StackStructReturn)
2448       FuncInfo->setBytesToPopOnReturn(4);
2449   }
2450
2451   if (!Is64Bit) {
2452     // RegSaveFrameIndex is X86-64 only.
2453     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2454     if (CallConv == CallingConv::X86_FastCall ||
2455         CallConv == CallingConv::X86_ThisCall)
2456       // fastcc functions can't have varargs.
2457       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2458   }
2459
2460   FuncInfo->setArgumentStackSize(StackSize);
2461
2462   return Chain;
2463 }
2464
2465 SDValue
2466 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2467                                     SDValue StackPtr, SDValue Arg,
2468                                     SDLoc dl, SelectionDAG &DAG,
2469                                     const CCValAssign &VA,
2470                                     ISD::ArgFlagsTy Flags) const {
2471   unsigned LocMemOffset = VA.getLocMemOffset();
2472   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2473   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2474   if (Flags.isByVal())
2475     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2476
2477   return DAG.getStore(Chain, dl, Arg, PtrOff,
2478                       MachinePointerInfo::getStack(LocMemOffset),
2479                       false, false, 0);
2480 }
2481
2482 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2483 /// optimization is performed and it is required.
2484 SDValue
2485 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2486                                            SDValue &OutRetAddr, SDValue Chain,
2487                                            bool IsTailCall, bool Is64Bit,
2488                                            int FPDiff, SDLoc dl) const {
2489   // Adjust the Return address stack slot.
2490   EVT VT = getPointerTy();
2491   OutRetAddr = getReturnAddressFrameIndex(DAG);
2492
2493   // Load the "old" Return address.
2494   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2495                            false, false, false, 0);
2496   return SDValue(OutRetAddr.getNode(), 1);
2497 }
2498
2499 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2500 /// optimization is performed and it is required (FPDiff!=0).
2501 static SDValue
2502 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2503                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2504                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2505   // Store the return address to the appropriate stack slot.
2506   if (!FPDiff) return Chain;
2507   // Calculate the new stack slot for the return address.
2508   int NewReturnAddrFI =
2509     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2510                                          false);
2511   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2512   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2513                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2514                        false, false, 0);
2515   return Chain;
2516 }
2517
2518 SDValue
2519 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2520                              SmallVectorImpl<SDValue> &InVals) const {
2521   SelectionDAG &DAG                     = CLI.DAG;
2522   SDLoc &dl                             = CLI.DL;
2523   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2524   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2525   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2526   SDValue Chain                         = CLI.Chain;
2527   SDValue Callee                        = CLI.Callee;
2528   CallingConv::ID CallConv              = CLI.CallConv;
2529   bool &isTailCall                      = CLI.IsTailCall;
2530   bool isVarArg                         = CLI.IsVarArg;
2531
2532   MachineFunction &MF = DAG.getMachineFunction();
2533   bool Is64Bit        = Subtarget->is64Bit();
2534   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2535   StructReturnType SR = callIsStructReturn(Outs);
2536   bool IsSibcall      = false;
2537
2538   if (MF.getTarget().Options.DisableTailCalls)
2539     isTailCall = false;
2540
2541   if (isTailCall) {
2542     // Check if it's really possible to do a tail call.
2543     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2544                     isVarArg, SR != NotStructReturn,
2545                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2546                     Outs, OutVals, Ins, DAG);
2547
2548     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2549       report_fatal_error("failed to perform tail call elimination on a call "
2550                          "site marked musttail");
2551
2552     // Sibcalls are automatically detected tailcalls which do not require
2553     // ABI changes.
2554     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2555       IsSibcall = true;
2556
2557     if (isTailCall)
2558       ++NumTailCalls;
2559   }
2560
2561   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2562          "Var args not supported with calling convention fastcc, ghc or hipe");
2563
2564   // Analyze operands of the call, assigning locations to each operand.
2565   SmallVector<CCValAssign, 16> ArgLocs;
2566   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2567                  ArgLocs, *DAG.getContext());
2568
2569   // Allocate shadow area for Win64
2570   if (IsWin64)
2571     CCInfo.AllocateStack(32, 8);
2572
2573   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2574
2575   // Get a count of how many bytes are to be pushed on the stack.
2576   unsigned NumBytes = CCInfo.getNextStackOffset();
2577   if (IsSibcall)
2578     // This is a sibcall. The memory operands are available in caller's
2579     // own caller's stack.
2580     NumBytes = 0;
2581   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2582            IsTailCallConvention(CallConv))
2583     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2584
2585   int FPDiff = 0;
2586   if (isTailCall && !IsSibcall) {
2587     // Lower arguments at fp - stackoffset + fpdiff.
2588     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2589     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2590
2591     FPDiff = NumBytesCallerPushed - NumBytes;
2592
2593     // Set the delta of movement of the returnaddr stackslot.
2594     // But only set if delta is greater than previous delta.
2595     if (FPDiff < X86Info->getTCReturnAddrDelta())
2596       X86Info->setTCReturnAddrDelta(FPDiff);
2597   }
2598
2599   unsigned NumBytesToPush = NumBytes;
2600   unsigned NumBytesToPop = NumBytes;
2601
2602   // If we have an inalloca argument, all stack space has already been allocated
2603   // for us and be right at the top of the stack.  We don't support multiple
2604   // arguments passed in memory when using inalloca.
2605   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2606     NumBytesToPush = 0;
2607     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2608            "an inalloca argument must be the only memory argument");
2609   }
2610
2611   if (!IsSibcall)
2612     Chain = DAG.getCALLSEQ_START(
2613         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2614
2615   SDValue RetAddrFrIdx;
2616   // Load return address for tail calls.
2617   if (isTailCall && FPDiff)
2618     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2619                                     Is64Bit, FPDiff, dl);
2620
2621   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2622   SmallVector<SDValue, 8> MemOpChains;
2623   SDValue StackPtr;
2624
2625   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2626   // of tail call optimization arguments are handle later.
2627   const X86RegisterInfo *RegInfo =
2628     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2629   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2630     // Skip inalloca arguments, they have already been written.
2631     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2632     if (Flags.isInAlloca())
2633       continue;
2634
2635     CCValAssign &VA = ArgLocs[i];
2636     EVT RegVT = VA.getLocVT();
2637     SDValue Arg = OutVals[i];
2638     bool isByVal = Flags.isByVal();
2639
2640     // Promote the value if needed.
2641     switch (VA.getLocInfo()) {
2642     default: llvm_unreachable("Unknown loc info!");
2643     case CCValAssign::Full: break;
2644     case CCValAssign::SExt:
2645       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2646       break;
2647     case CCValAssign::ZExt:
2648       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2649       break;
2650     case CCValAssign::AExt:
2651       if (RegVT.is128BitVector()) {
2652         // Special case: passing MMX values in XMM registers.
2653         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2654         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2655         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2656       } else
2657         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2658       break;
2659     case CCValAssign::BCvt:
2660       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2661       break;
2662     case CCValAssign::Indirect: {
2663       // Store the argument.
2664       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2665       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2666       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2667                            MachinePointerInfo::getFixedStack(FI),
2668                            false, false, 0);
2669       Arg = SpillSlot;
2670       break;
2671     }
2672     }
2673
2674     if (VA.isRegLoc()) {
2675       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2676       if (isVarArg && IsWin64) {
2677         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2678         // shadow reg if callee is a varargs function.
2679         unsigned ShadowReg = 0;
2680         switch (VA.getLocReg()) {
2681         case X86::XMM0: ShadowReg = X86::RCX; break;
2682         case X86::XMM1: ShadowReg = X86::RDX; break;
2683         case X86::XMM2: ShadowReg = X86::R8; break;
2684         case X86::XMM3: ShadowReg = X86::R9; break;
2685         }
2686         if (ShadowReg)
2687           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2688       }
2689     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2690       assert(VA.isMemLoc());
2691       if (!StackPtr.getNode())
2692         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2693                                       getPointerTy());
2694       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2695                                              dl, DAG, VA, Flags));
2696     }
2697   }
2698
2699   if (!MemOpChains.empty())
2700     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2701
2702   if (Subtarget->isPICStyleGOT()) {
2703     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2704     // GOT pointer.
2705     if (!isTailCall) {
2706       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2707                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2708     } else {
2709       // If we are tail calling and generating PIC/GOT style code load the
2710       // address of the callee into ECX. The value in ecx is used as target of
2711       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2712       // for tail calls on PIC/GOT architectures. Normally we would just put the
2713       // address of GOT into ebx and then call target@PLT. But for tail calls
2714       // ebx would be restored (since ebx is callee saved) before jumping to the
2715       // target@PLT.
2716
2717       // Note: The actual moving to ECX is done further down.
2718       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2719       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2720           !G->getGlobal()->hasProtectedVisibility())
2721         Callee = LowerGlobalAddress(Callee, DAG);
2722       else if (isa<ExternalSymbolSDNode>(Callee))
2723         Callee = LowerExternalSymbol(Callee, DAG);
2724     }
2725   }
2726
2727   if (Is64Bit && isVarArg && !IsWin64) {
2728     // From AMD64 ABI document:
2729     // For calls that may call functions that use varargs or stdargs
2730     // (prototype-less calls or calls to functions containing ellipsis (...) in
2731     // the declaration) %al is used as hidden argument to specify the number
2732     // of SSE registers used. The contents of %al do not need to match exactly
2733     // the number of registers, but must be an ubound on the number of SSE
2734     // registers used and is in the range 0 - 8 inclusive.
2735
2736     // Count the number of XMM registers allocated.
2737     static const MCPhysReg XMMArgRegs[] = {
2738       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2739       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2740     };
2741     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2742     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2743            && "SSE registers cannot be used when SSE is disabled");
2744
2745     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2746                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2747   }
2748
2749   // For tail calls lower the arguments to the 'real' stack slot.
2750   if (isTailCall) {
2751     // Force all the incoming stack arguments to be loaded from the stack
2752     // before any new outgoing arguments are stored to the stack, because the
2753     // outgoing stack slots may alias the incoming argument stack slots, and
2754     // the alias isn't otherwise explicit. This is slightly more conservative
2755     // than necessary, because it means that each store effectively depends
2756     // on every argument instead of just those arguments it would clobber.
2757     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2758
2759     SmallVector<SDValue, 8> MemOpChains2;
2760     SDValue FIN;
2761     int FI = 0;
2762     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2763       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2764         CCValAssign &VA = ArgLocs[i];
2765         if (VA.isRegLoc())
2766           continue;
2767         assert(VA.isMemLoc());
2768         SDValue Arg = OutVals[i];
2769         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2770         // Create frame index.
2771         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2772         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2773         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2774         FIN = DAG.getFrameIndex(FI, getPointerTy());
2775
2776         if (Flags.isByVal()) {
2777           // Copy relative to framepointer.
2778           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2779           if (!StackPtr.getNode())
2780             StackPtr = DAG.getCopyFromReg(Chain, dl,
2781                                           RegInfo->getStackRegister(),
2782                                           getPointerTy());
2783           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2784
2785           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2786                                                            ArgChain,
2787                                                            Flags, DAG, dl));
2788         } else {
2789           // Store relative to framepointer.
2790           MemOpChains2.push_back(
2791             DAG.getStore(ArgChain, dl, Arg, FIN,
2792                          MachinePointerInfo::getFixedStack(FI),
2793                          false, false, 0));
2794         }
2795       }
2796     }
2797
2798     if (!MemOpChains2.empty())
2799       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2800
2801     // Store the return address to the appropriate stack slot.
2802     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2803                                      getPointerTy(), RegInfo->getSlotSize(),
2804                                      FPDiff, dl);
2805   }
2806
2807   // Build a sequence of copy-to-reg nodes chained together with token chain
2808   // and flag operands which copy the outgoing args into registers.
2809   SDValue InFlag;
2810   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2811     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2812                              RegsToPass[i].second, InFlag);
2813     InFlag = Chain.getValue(1);
2814   }
2815
2816   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2817     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2818     // In the 64-bit large code model, we have to make all calls
2819     // through a register, since the call instruction's 32-bit
2820     // pc-relative offset may not be large enough to hold the whole
2821     // address.
2822   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2823     // If the callee is a GlobalAddress node (quite common, every direct call
2824     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2825     // it.
2826
2827     // We should use extra load for direct calls to dllimported functions in
2828     // non-JIT mode.
2829     const GlobalValue *GV = G->getGlobal();
2830     if (!GV->hasDLLImportStorageClass()) {
2831       unsigned char OpFlags = 0;
2832       bool ExtraLoad = false;
2833       unsigned WrapperKind = ISD::DELETED_NODE;
2834
2835       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2836       // external symbols most go through the PLT in PIC mode.  If the symbol
2837       // has hidden or protected visibility, or if it is static or local, then
2838       // we don't need to use the PLT - we can directly call it.
2839       if (Subtarget->isTargetELF() &&
2840           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2841           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2842         OpFlags = X86II::MO_PLT;
2843       } else if (Subtarget->isPICStyleStubAny() &&
2844                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2845                  (!Subtarget->getTargetTriple().isMacOSX() ||
2846                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2847         // PC-relative references to external symbols should go through $stub,
2848         // unless we're building with the leopard linker or later, which
2849         // automatically synthesizes these stubs.
2850         OpFlags = X86II::MO_DARWIN_STUB;
2851       } else if (Subtarget->isPICStyleRIPRel() &&
2852                  isa<Function>(GV) &&
2853                  cast<Function>(GV)->getAttributes().
2854                    hasAttribute(AttributeSet::FunctionIndex,
2855                                 Attribute::NonLazyBind)) {
2856         // If the function is marked as non-lazy, generate an indirect call
2857         // which loads from the GOT directly. This avoids runtime overhead
2858         // at the cost of eager binding (and one extra byte of encoding).
2859         OpFlags = X86II::MO_GOTPCREL;
2860         WrapperKind = X86ISD::WrapperRIP;
2861         ExtraLoad = true;
2862       }
2863
2864       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2865                                           G->getOffset(), OpFlags);
2866
2867       // Add a wrapper if needed.
2868       if (WrapperKind != ISD::DELETED_NODE)
2869         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2870       // Add extra indirection if needed.
2871       if (ExtraLoad)
2872         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2873                              MachinePointerInfo::getGOT(),
2874                              false, false, false, 0);
2875     }
2876   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2877     unsigned char OpFlags = 0;
2878
2879     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2880     // external symbols should go through the PLT.
2881     if (Subtarget->isTargetELF() &&
2882         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2883       OpFlags = X86II::MO_PLT;
2884     } else if (Subtarget->isPICStyleStubAny() &&
2885                (!Subtarget->getTargetTriple().isMacOSX() ||
2886                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2887       // PC-relative references to external symbols should go through $stub,
2888       // unless we're building with the leopard linker or later, which
2889       // automatically synthesizes these stubs.
2890       OpFlags = X86II::MO_DARWIN_STUB;
2891     }
2892
2893     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2894                                          OpFlags);
2895   }
2896
2897   // Returns a chain & a flag for retval copy to use.
2898   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2899   SmallVector<SDValue, 8> Ops;
2900
2901   if (!IsSibcall && isTailCall) {
2902     Chain = DAG.getCALLSEQ_END(Chain,
2903                                DAG.getIntPtrConstant(NumBytesToPop, true),
2904                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2905     InFlag = Chain.getValue(1);
2906   }
2907
2908   Ops.push_back(Chain);
2909   Ops.push_back(Callee);
2910
2911   if (isTailCall)
2912     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2913
2914   // Add argument registers to the end of the list so that they are known live
2915   // into the call.
2916   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2917     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2918                                   RegsToPass[i].second.getValueType()));
2919
2920   // Add a register mask operand representing the call-preserved registers.
2921   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2922   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2923   assert(Mask && "Missing call preserved mask for calling convention");
2924   Ops.push_back(DAG.getRegisterMask(Mask));
2925
2926   if (InFlag.getNode())
2927     Ops.push_back(InFlag);
2928
2929   if (isTailCall) {
2930     // We used to do:
2931     //// If this is the first return lowered for this function, add the regs
2932     //// to the liveout set for the function.
2933     // This isn't right, although it's probably harmless on x86; liveouts
2934     // should be computed from returns not tail calls.  Consider a void
2935     // function making a tail call to a function returning int.
2936     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2937   }
2938
2939   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2940   InFlag = Chain.getValue(1);
2941
2942   // Create the CALLSEQ_END node.
2943   unsigned NumBytesForCalleeToPop;
2944   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2945                        getTargetMachine().Options.GuaranteedTailCallOpt))
2946     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2947   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2948            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2949            SR == StackStructReturn)
2950     // If this is a call to a struct-return function, the callee
2951     // pops the hidden struct pointer, so we have to push it back.
2952     // This is common for Darwin/X86, Linux & Mingw32 targets.
2953     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2954     NumBytesForCalleeToPop = 4;
2955   else
2956     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2957
2958   // Returns a flag for retval copy to use.
2959   if (!IsSibcall) {
2960     Chain = DAG.getCALLSEQ_END(Chain,
2961                                DAG.getIntPtrConstant(NumBytesToPop, true),
2962                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2963                                                      true),
2964                                InFlag, dl);
2965     InFlag = Chain.getValue(1);
2966   }
2967
2968   // Handle result values, copying them out of physregs into vregs that we
2969   // return.
2970   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2971                          Ins, dl, DAG, InVals);
2972 }
2973
2974 //===----------------------------------------------------------------------===//
2975 //                Fast Calling Convention (tail call) implementation
2976 //===----------------------------------------------------------------------===//
2977
2978 //  Like std call, callee cleans arguments, convention except that ECX is
2979 //  reserved for storing the tail called function address. Only 2 registers are
2980 //  free for argument passing (inreg). Tail call optimization is performed
2981 //  provided:
2982 //                * tailcallopt is enabled
2983 //                * caller/callee are fastcc
2984 //  On X86_64 architecture with GOT-style position independent code only local
2985 //  (within module) calls are supported at the moment.
2986 //  To keep the stack aligned according to platform abi the function
2987 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2988 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2989 //  If a tail called function callee has more arguments than the caller the
2990 //  caller needs to make sure that there is room to move the RETADDR to. This is
2991 //  achieved by reserving an area the size of the argument delta right after the
2992 //  original REtADDR, but before the saved framepointer or the spilled registers
2993 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2994 //  stack layout:
2995 //    arg1
2996 //    arg2
2997 //    RETADDR
2998 //    [ new RETADDR
2999 //      move area ]
3000 //    (possible EBP)
3001 //    ESI
3002 //    EDI
3003 //    local1 ..
3004
3005 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3006 /// for a 16 byte align requirement.
3007 unsigned
3008 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3009                                                SelectionDAG& DAG) const {
3010   MachineFunction &MF = DAG.getMachineFunction();
3011   const TargetMachine &TM = MF.getTarget();
3012   const X86RegisterInfo *RegInfo =
3013     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3014   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3015   unsigned StackAlignment = TFI.getStackAlignment();
3016   uint64_t AlignMask = StackAlignment - 1;
3017   int64_t Offset = StackSize;
3018   unsigned SlotSize = RegInfo->getSlotSize();
3019   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3020     // Number smaller than 12 so just add the difference.
3021     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3022   } else {
3023     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3024     Offset = ((~AlignMask) & Offset) + StackAlignment +
3025       (StackAlignment-SlotSize);
3026   }
3027   return Offset;
3028 }
3029
3030 /// MatchingStackOffset - Return true if the given stack call argument is
3031 /// already available in the same position (relatively) of the caller's
3032 /// incoming argument stack.
3033 static
3034 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3035                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3036                          const X86InstrInfo *TII) {
3037   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3038   int FI = INT_MAX;
3039   if (Arg.getOpcode() == ISD::CopyFromReg) {
3040     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3041     if (!TargetRegisterInfo::isVirtualRegister(VR))
3042       return false;
3043     MachineInstr *Def = MRI->getVRegDef(VR);
3044     if (!Def)
3045       return false;
3046     if (!Flags.isByVal()) {
3047       if (!TII->isLoadFromStackSlot(Def, FI))
3048         return false;
3049     } else {
3050       unsigned Opcode = Def->getOpcode();
3051       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3052           Def->getOperand(1).isFI()) {
3053         FI = Def->getOperand(1).getIndex();
3054         Bytes = Flags.getByValSize();
3055       } else
3056         return false;
3057     }
3058   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3059     if (Flags.isByVal())
3060       // ByVal argument is passed in as a pointer but it's now being
3061       // dereferenced. e.g.
3062       // define @foo(%struct.X* %A) {
3063       //   tail call @bar(%struct.X* byval %A)
3064       // }
3065       return false;
3066     SDValue Ptr = Ld->getBasePtr();
3067     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3068     if (!FINode)
3069       return false;
3070     FI = FINode->getIndex();
3071   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3072     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3073     FI = FINode->getIndex();
3074     Bytes = Flags.getByValSize();
3075   } else
3076     return false;
3077
3078   assert(FI != INT_MAX);
3079   if (!MFI->isFixedObjectIndex(FI))
3080     return false;
3081   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3082 }
3083
3084 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3085 /// for tail call optimization. Targets which want to do tail call
3086 /// optimization should implement this function.
3087 bool
3088 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3089                                                      CallingConv::ID CalleeCC,
3090                                                      bool isVarArg,
3091                                                      bool isCalleeStructRet,
3092                                                      bool isCallerStructRet,
3093                                                      Type *RetTy,
3094                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3095                                     const SmallVectorImpl<SDValue> &OutVals,
3096                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3097                                                      SelectionDAG &DAG) const {
3098   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3099     return false;
3100
3101   // If -tailcallopt is specified, make fastcc functions tail-callable.
3102   const MachineFunction &MF = DAG.getMachineFunction();
3103   const Function *CallerF = MF.getFunction();
3104
3105   // If the function return type is x86_fp80 and the callee return type is not,
3106   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3107   // perform a tailcall optimization here.
3108   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3109     return false;
3110
3111   CallingConv::ID CallerCC = CallerF->getCallingConv();
3112   bool CCMatch = CallerCC == CalleeCC;
3113   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3114   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3115
3116   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3117     if (IsTailCallConvention(CalleeCC) && CCMatch)
3118       return true;
3119     return false;
3120   }
3121
3122   // Look for obvious safe cases to perform tail call optimization that do not
3123   // require ABI changes. This is what gcc calls sibcall.
3124
3125   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3126   // emit a special epilogue.
3127   const X86RegisterInfo *RegInfo =
3128     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3129   if (RegInfo->needsStackRealignment(MF))
3130     return false;
3131
3132   // Also avoid sibcall optimization if either caller or callee uses struct
3133   // return semantics.
3134   if (isCalleeStructRet || isCallerStructRet)
3135     return false;
3136
3137   // An stdcall/thiscall caller is expected to clean up its arguments; the
3138   // callee isn't going to do that.
3139   // FIXME: this is more restrictive than needed. We could produce a tailcall
3140   // when the stack adjustment matches. For example, with a thiscall that takes
3141   // only one argument.
3142   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3143                    CallerCC == CallingConv::X86_ThisCall))
3144     return false;
3145
3146   // Do not sibcall optimize vararg calls unless all arguments are passed via
3147   // registers.
3148   if (isVarArg && !Outs.empty()) {
3149
3150     // Optimizing for varargs on Win64 is unlikely to be safe without
3151     // additional testing.
3152     if (IsCalleeWin64 || IsCallerWin64)
3153       return false;
3154
3155     SmallVector<CCValAssign, 16> ArgLocs;
3156     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3157                    getTargetMachine(), ArgLocs, *DAG.getContext());
3158
3159     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3160     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3161       if (!ArgLocs[i].isRegLoc())
3162         return false;
3163   }
3164
3165   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3166   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3167   // this into a sibcall.
3168   bool Unused = false;
3169   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3170     if (!Ins[i].Used) {
3171       Unused = true;
3172       break;
3173     }
3174   }
3175   if (Unused) {
3176     SmallVector<CCValAssign, 16> RVLocs;
3177     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3178                    getTargetMachine(), RVLocs, *DAG.getContext());
3179     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3180     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3181       CCValAssign &VA = RVLocs[i];
3182       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3183         return false;
3184     }
3185   }
3186
3187   // If the calling conventions do not match, then we'd better make sure the
3188   // results are returned in the same way as what the caller expects.
3189   if (!CCMatch) {
3190     SmallVector<CCValAssign, 16> RVLocs1;
3191     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3192                     getTargetMachine(), RVLocs1, *DAG.getContext());
3193     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3194
3195     SmallVector<CCValAssign, 16> RVLocs2;
3196     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3197                     getTargetMachine(), RVLocs2, *DAG.getContext());
3198     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3199
3200     if (RVLocs1.size() != RVLocs2.size())
3201       return false;
3202     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3203       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3204         return false;
3205       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3206         return false;
3207       if (RVLocs1[i].isRegLoc()) {
3208         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3209           return false;
3210       } else {
3211         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3212           return false;
3213       }
3214     }
3215   }
3216
3217   // If the callee takes no arguments then go on to check the results of the
3218   // call.
3219   if (!Outs.empty()) {
3220     // Check if stack adjustment is needed. For now, do not do this if any
3221     // argument is passed on the stack.
3222     SmallVector<CCValAssign, 16> ArgLocs;
3223     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3224                    getTargetMachine(), ArgLocs, *DAG.getContext());
3225
3226     // Allocate shadow area for Win64
3227     if (IsCalleeWin64)
3228       CCInfo.AllocateStack(32, 8);
3229
3230     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3231     if (CCInfo.getNextStackOffset()) {
3232       MachineFunction &MF = DAG.getMachineFunction();
3233       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3234         return false;
3235
3236       // Check if the arguments are already laid out in the right way as
3237       // the caller's fixed stack objects.
3238       MachineFrameInfo *MFI = MF.getFrameInfo();
3239       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3240       const X86InstrInfo *TII =
3241         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3242       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3243         CCValAssign &VA = ArgLocs[i];
3244         SDValue Arg = OutVals[i];
3245         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3246         if (VA.getLocInfo() == CCValAssign::Indirect)
3247           return false;
3248         if (!VA.isRegLoc()) {
3249           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3250                                    MFI, MRI, TII))
3251             return false;
3252         }
3253       }
3254     }
3255
3256     // If the tailcall address may be in a register, then make sure it's
3257     // possible to register allocate for it. In 32-bit, the call address can
3258     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3259     // callee-saved registers are restored. These happen to be the same
3260     // registers used to pass 'inreg' arguments so watch out for those.
3261     if (!Subtarget->is64Bit() &&
3262         ((!isa<GlobalAddressSDNode>(Callee) &&
3263           !isa<ExternalSymbolSDNode>(Callee)) ||
3264          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3265       unsigned NumInRegs = 0;
3266       // In PIC we need an extra register to formulate the address computation
3267       // for the callee.
3268       unsigned MaxInRegs =
3269           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3270
3271       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3272         CCValAssign &VA = ArgLocs[i];
3273         if (!VA.isRegLoc())
3274           continue;
3275         unsigned Reg = VA.getLocReg();
3276         switch (Reg) {
3277         default: break;
3278         case X86::EAX: case X86::EDX: case X86::ECX:
3279           if (++NumInRegs == MaxInRegs)
3280             return false;
3281           break;
3282         }
3283       }
3284     }
3285   }
3286
3287   return true;
3288 }
3289
3290 FastISel *
3291 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3292                                   const TargetLibraryInfo *libInfo) const {
3293   return X86::createFastISel(funcInfo, libInfo);
3294 }
3295
3296 //===----------------------------------------------------------------------===//
3297 //                           Other Lowering Hooks
3298 //===----------------------------------------------------------------------===//
3299
3300 static bool MayFoldLoad(SDValue Op) {
3301   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3302 }
3303
3304 static bool MayFoldIntoStore(SDValue Op) {
3305   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3306 }
3307
3308 static bool isTargetShuffle(unsigned Opcode) {
3309   switch(Opcode) {
3310   default: return false;
3311   case X86ISD::PSHUFD:
3312   case X86ISD::PSHUFHW:
3313   case X86ISD::PSHUFLW:
3314   case X86ISD::SHUFP:
3315   case X86ISD::PALIGNR:
3316   case X86ISD::MOVLHPS:
3317   case X86ISD::MOVLHPD:
3318   case X86ISD::MOVHLPS:
3319   case X86ISD::MOVLPS:
3320   case X86ISD::MOVLPD:
3321   case X86ISD::MOVSHDUP:
3322   case X86ISD::MOVSLDUP:
3323   case X86ISD::MOVDDUP:
3324   case X86ISD::MOVSS:
3325   case X86ISD::MOVSD:
3326   case X86ISD::UNPCKL:
3327   case X86ISD::UNPCKH:
3328   case X86ISD::VPERMILP:
3329   case X86ISD::VPERM2X128:
3330   case X86ISD::VPERMI:
3331     return true;
3332   }
3333 }
3334
3335 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3336                                     SDValue V1, SelectionDAG &DAG) {
3337   switch(Opc) {
3338   default: llvm_unreachable("Unknown x86 shuffle node");
3339   case X86ISD::MOVSHDUP:
3340   case X86ISD::MOVSLDUP:
3341   case X86ISD::MOVDDUP:
3342     return DAG.getNode(Opc, dl, VT, V1);
3343   }
3344 }
3345
3346 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3347                                     SDValue V1, unsigned TargetMask,
3348                                     SelectionDAG &DAG) {
3349   switch(Opc) {
3350   default: llvm_unreachable("Unknown x86 shuffle node");
3351   case X86ISD::PSHUFD:
3352   case X86ISD::PSHUFHW:
3353   case X86ISD::PSHUFLW:
3354   case X86ISD::VPERMILP:
3355   case X86ISD::VPERMI:
3356     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3357   }
3358 }
3359
3360 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3361                                     SDValue V1, SDValue V2, unsigned TargetMask,
3362                                     SelectionDAG &DAG) {
3363   switch(Opc) {
3364   default: llvm_unreachable("Unknown x86 shuffle node");
3365   case X86ISD::PALIGNR:
3366   case X86ISD::SHUFP:
3367   case X86ISD::VPERM2X128:
3368     return DAG.getNode(Opc, dl, VT, V1, V2,
3369                        DAG.getConstant(TargetMask, MVT::i8));
3370   }
3371 }
3372
3373 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3374                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3375   switch(Opc) {
3376   default: llvm_unreachable("Unknown x86 shuffle node");
3377   case X86ISD::MOVLHPS:
3378   case X86ISD::MOVLHPD:
3379   case X86ISD::MOVHLPS:
3380   case X86ISD::MOVLPS:
3381   case X86ISD::MOVLPD:
3382   case X86ISD::MOVSS:
3383   case X86ISD::MOVSD:
3384   case X86ISD::UNPCKL:
3385   case X86ISD::UNPCKH:
3386     return DAG.getNode(Opc, dl, VT, V1, V2);
3387   }
3388 }
3389
3390 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3391   MachineFunction &MF = DAG.getMachineFunction();
3392   const X86RegisterInfo *RegInfo =
3393     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3394   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3395   int ReturnAddrIndex = FuncInfo->getRAIndex();
3396
3397   if (ReturnAddrIndex == 0) {
3398     // Set up a frame object for the return address.
3399     unsigned SlotSize = RegInfo->getSlotSize();
3400     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3401                                                            -(int64_t)SlotSize,
3402                                                            false);
3403     FuncInfo->setRAIndex(ReturnAddrIndex);
3404   }
3405
3406   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3407 }
3408
3409 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3410                                        bool hasSymbolicDisplacement) {
3411   // Offset should fit into 32 bit immediate field.
3412   if (!isInt<32>(Offset))
3413     return false;
3414
3415   // If we don't have a symbolic displacement - we don't have any extra
3416   // restrictions.
3417   if (!hasSymbolicDisplacement)
3418     return true;
3419
3420   // FIXME: Some tweaks might be needed for medium code model.
3421   if (M != CodeModel::Small && M != CodeModel::Kernel)
3422     return false;
3423
3424   // For small code model we assume that latest object is 16MB before end of 31
3425   // bits boundary. We may also accept pretty large negative constants knowing
3426   // that all objects are in the positive half of address space.
3427   if (M == CodeModel::Small && Offset < 16*1024*1024)
3428     return true;
3429
3430   // For kernel code model we know that all object resist in the negative half
3431   // of 32bits address space. We may not accept negative offsets, since they may
3432   // be just off and we may accept pretty large positive ones.
3433   if (M == CodeModel::Kernel && Offset > 0)
3434     return true;
3435
3436   return false;
3437 }
3438
3439 /// isCalleePop - Determines whether the callee is required to pop its
3440 /// own arguments. Callee pop is necessary to support tail calls.
3441 bool X86::isCalleePop(CallingConv::ID CallingConv,
3442                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3443   if (IsVarArg)
3444     return false;
3445
3446   switch (CallingConv) {
3447   default:
3448     return false;
3449   case CallingConv::X86_StdCall:
3450     return !is64Bit;
3451   case CallingConv::X86_FastCall:
3452     return !is64Bit;
3453   case CallingConv::X86_ThisCall:
3454     return !is64Bit;
3455   case CallingConv::Fast:
3456     return TailCallOpt;
3457   case CallingConv::GHC:
3458     return TailCallOpt;
3459   case CallingConv::HiPE:
3460     return TailCallOpt;
3461   }
3462 }
3463
3464 /// \brief Return true if the condition is an unsigned comparison operation.
3465 static bool isX86CCUnsigned(unsigned X86CC) {
3466   switch (X86CC) {
3467   default: llvm_unreachable("Invalid integer condition!");
3468   case X86::COND_E:     return true;
3469   case X86::COND_G:     return false;
3470   case X86::COND_GE:    return false;
3471   case X86::COND_L:     return false;
3472   case X86::COND_LE:    return false;
3473   case X86::COND_NE:    return true;
3474   case X86::COND_B:     return true;
3475   case X86::COND_A:     return true;
3476   case X86::COND_BE:    return true;
3477   case X86::COND_AE:    return true;
3478   }
3479   llvm_unreachable("covered switch fell through?!");
3480 }
3481
3482 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3483 /// specific condition code, returning the condition code and the LHS/RHS of the
3484 /// comparison to make.
3485 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3486                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3487   if (!isFP) {
3488     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3489       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3490         // X > -1   -> X == 0, jump !sign.
3491         RHS = DAG.getConstant(0, RHS.getValueType());
3492         return X86::COND_NS;
3493       }
3494       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3495         // X < 0   -> X == 0, jump on sign.
3496         return X86::COND_S;
3497       }
3498       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3499         // X < 1   -> X <= 0
3500         RHS = DAG.getConstant(0, RHS.getValueType());
3501         return X86::COND_LE;
3502       }
3503     }
3504
3505     switch (SetCCOpcode) {
3506     default: llvm_unreachable("Invalid integer condition!");
3507     case ISD::SETEQ:  return X86::COND_E;
3508     case ISD::SETGT:  return X86::COND_G;
3509     case ISD::SETGE:  return X86::COND_GE;
3510     case ISD::SETLT:  return X86::COND_L;
3511     case ISD::SETLE:  return X86::COND_LE;
3512     case ISD::SETNE:  return X86::COND_NE;
3513     case ISD::SETULT: return X86::COND_B;
3514     case ISD::SETUGT: return X86::COND_A;
3515     case ISD::SETULE: return X86::COND_BE;
3516     case ISD::SETUGE: return X86::COND_AE;
3517     }
3518   }
3519
3520   // First determine if it is required or is profitable to flip the operands.
3521
3522   // If LHS is a foldable load, but RHS is not, flip the condition.
3523   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3524       !ISD::isNON_EXTLoad(RHS.getNode())) {
3525     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3526     std::swap(LHS, RHS);
3527   }
3528
3529   switch (SetCCOpcode) {
3530   default: break;
3531   case ISD::SETOLT:
3532   case ISD::SETOLE:
3533   case ISD::SETUGT:
3534   case ISD::SETUGE:
3535     std::swap(LHS, RHS);
3536     break;
3537   }
3538
3539   // On a floating point condition, the flags are set as follows:
3540   // ZF  PF  CF   op
3541   //  0 | 0 | 0 | X > Y
3542   //  0 | 0 | 1 | X < Y
3543   //  1 | 0 | 0 | X == Y
3544   //  1 | 1 | 1 | unordered
3545   switch (SetCCOpcode) {
3546   default: llvm_unreachable("Condcode should be pre-legalized away");
3547   case ISD::SETUEQ:
3548   case ISD::SETEQ:   return X86::COND_E;
3549   case ISD::SETOLT:              // flipped
3550   case ISD::SETOGT:
3551   case ISD::SETGT:   return X86::COND_A;
3552   case ISD::SETOLE:              // flipped
3553   case ISD::SETOGE:
3554   case ISD::SETGE:   return X86::COND_AE;
3555   case ISD::SETUGT:              // flipped
3556   case ISD::SETULT:
3557   case ISD::SETLT:   return X86::COND_B;
3558   case ISD::SETUGE:              // flipped
3559   case ISD::SETULE:
3560   case ISD::SETLE:   return X86::COND_BE;
3561   case ISD::SETONE:
3562   case ISD::SETNE:   return X86::COND_NE;
3563   case ISD::SETUO:   return X86::COND_P;
3564   case ISD::SETO:    return X86::COND_NP;
3565   case ISD::SETOEQ:
3566   case ISD::SETUNE:  return X86::COND_INVALID;
3567   }
3568 }
3569
3570 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3571 /// code. Current x86 isa includes the following FP cmov instructions:
3572 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3573 static bool hasFPCMov(unsigned X86CC) {
3574   switch (X86CC) {
3575   default:
3576     return false;
3577   case X86::COND_B:
3578   case X86::COND_BE:
3579   case X86::COND_E:
3580   case X86::COND_P:
3581   case X86::COND_A:
3582   case X86::COND_AE:
3583   case X86::COND_NE:
3584   case X86::COND_NP:
3585     return true;
3586   }
3587 }
3588
3589 /// isFPImmLegal - Returns true if the target can instruction select the
3590 /// specified FP immediate natively. If false, the legalizer will
3591 /// materialize the FP immediate as a load from a constant pool.
3592 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3593   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3594     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3595       return true;
3596   }
3597   return false;
3598 }
3599
3600 /// \brief Returns true if it is beneficial to convert a load of a constant
3601 /// to just the constant itself.
3602 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3603                                                           Type *Ty) const {
3604   assert(Ty->isIntegerTy());
3605
3606   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3607   if (BitSize == 0 || BitSize > 64)
3608     return false;
3609   return true;
3610 }
3611
3612 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3613 /// the specified range (L, H].
3614 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3615   return (Val < 0) || (Val >= Low && Val < Hi);
3616 }
3617
3618 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3619 /// specified value.
3620 static bool isUndefOrEqual(int Val, int CmpVal) {
3621   return (Val < 0 || Val == CmpVal);
3622 }
3623
3624 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3625 /// from position Pos and ending in Pos+Size, falls within the specified
3626 /// sequential range (L, L+Pos]. or is undef.
3627 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3628                                        unsigned Pos, unsigned Size, int Low) {
3629   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3630     if (!isUndefOrEqual(Mask[i], Low))
3631       return false;
3632   return true;
3633 }
3634
3635 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3636 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3637 /// the second operand.
3638 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3639   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3640     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3641   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3642     return (Mask[0] < 2 && Mask[1] < 2);
3643   return false;
3644 }
3645
3646 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3647 /// is suitable for input to PSHUFHW.
3648 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3649   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3650     return false;
3651
3652   // Lower quadword copied in order or undef.
3653   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3654     return false;
3655
3656   // Upper quadword shuffled.
3657   for (unsigned i = 4; i != 8; ++i)
3658     if (!isUndefOrInRange(Mask[i], 4, 8))
3659       return false;
3660
3661   if (VT == MVT::v16i16) {
3662     // Lower quadword copied in order or undef.
3663     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3664       return false;
3665
3666     // Upper quadword shuffled.
3667     for (unsigned i = 12; i != 16; ++i)
3668       if (!isUndefOrInRange(Mask[i], 12, 16))
3669         return false;
3670   }
3671
3672   return true;
3673 }
3674
3675 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3676 /// is suitable for input to PSHUFLW.
3677 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3678   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3679     return false;
3680
3681   // Upper quadword copied in order.
3682   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3683     return false;
3684
3685   // Lower quadword shuffled.
3686   for (unsigned i = 0; i != 4; ++i)
3687     if (!isUndefOrInRange(Mask[i], 0, 4))
3688       return false;
3689
3690   if (VT == MVT::v16i16) {
3691     // Upper quadword copied in order.
3692     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3693       return false;
3694
3695     // Lower quadword shuffled.
3696     for (unsigned i = 8; i != 12; ++i)
3697       if (!isUndefOrInRange(Mask[i], 8, 12))
3698         return false;
3699   }
3700
3701   return true;
3702 }
3703
3704 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3705 /// is suitable for input to PALIGNR.
3706 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3707                           const X86Subtarget *Subtarget) {
3708   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3709       (VT.is256BitVector() && !Subtarget->hasInt256()))
3710     return false;
3711
3712   unsigned NumElts = VT.getVectorNumElements();
3713   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3714   unsigned NumLaneElts = NumElts/NumLanes;
3715
3716   // Do not handle 64-bit element shuffles with palignr.
3717   if (NumLaneElts == 2)
3718     return false;
3719
3720   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3721     unsigned i;
3722     for (i = 0; i != NumLaneElts; ++i) {
3723       if (Mask[i+l] >= 0)
3724         break;
3725     }
3726
3727     // Lane is all undef, go to next lane
3728     if (i == NumLaneElts)
3729       continue;
3730
3731     int Start = Mask[i+l];
3732
3733     // Make sure its in this lane in one of the sources
3734     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3735         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3736       return false;
3737
3738     // If not lane 0, then we must match lane 0
3739     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3740       return false;
3741
3742     // Correct second source to be contiguous with first source
3743     if (Start >= (int)NumElts)
3744       Start -= NumElts - NumLaneElts;
3745
3746     // Make sure we're shifting in the right direction.
3747     if (Start <= (int)(i+l))
3748       return false;
3749
3750     Start -= i;
3751
3752     // Check the rest of the elements to see if they are consecutive.
3753     for (++i; i != NumLaneElts; ++i) {
3754       int Idx = Mask[i+l];
3755
3756       // Make sure its in this lane
3757       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3758           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3759         return false;
3760
3761       // If not lane 0, then we must match lane 0
3762       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3763         return false;
3764
3765       if (Idx >= (int)NumElts)
3766         Idx -= NumElts - NumLaneElts;
3767
3768       if (!isUndefOrEqual(Idx, Start+i))
3769         return false;
3770
3771     }
3772   }
3773
3774   return true;
3775 }
3776
3777 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3778 /// the two vector operands have swapped position.
3779 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3780                                      unsigned NumElems) {
3781   for (unsigned i = 0; i != NumElems; ++i) {
3782     int idx = Mask[i];
3783     if (idx < 0)
3784       continue;
3785     else if (idx < (int)NumElems)
3786       Mask[i] = idx + NumElems;
3787     else
3788       Mask[i] = idx - NumElems;
3789   }
3790 }
3791
3792 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3793 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3794 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3795 /// reverse of what x86 shuffles want.
3796 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3797
3798   unsigned NumElems = VT.getVectorNumElements();
3799   unsigned NumLanes = VT.getSizeInBits()/128;
3800   unsigned NumLaneElems = NumElems/NumLanes;
3801
3802   if (NumLaneElems != 2 && NumLaneElems != 4)
3803     return false;
3804
3805   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3806   bool symetricMaskRequired =
3807     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3808
3809   // VSHUFPSY divides the resulting vector into 4 chunks.
3810   // The sources are also splitted into 4 chunks, and each destination
3811   // chunk must come from a different source chunk.
3812   //
3813   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3814   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3815   //
3816   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3817   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3818   //
3819   // VSHUFPDY divides the resulting vector into 4 chunks.
3820   // The sources are also splitted into 4 chunks, and each destination
3821   // chunk must come from a different source chunk.
3822   //
3823   //  SRC1 =>      X3       X2       X1       X0
3824   //  SRC2 =>      Y3       Y2       Y1       Y0
3825   //
3826   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3827   //
3828   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3829   unsigned HalfLaneElems = NumLaneElems/2;
3830   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3831     for (unsigned i = 0; i != NumLaneElems; ++i) {
3832       int Idx = Mask[i+l];
3833       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3834       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3835         return false;
3836       // For VSHUFPSY, the mask of the second half must be the same as the
3837       // first but with the appropriate offsets. This works in the same way as
3838       // VPERMILPS works with masks.
3839       if (!symetricMaskRequired || Idx < 0)
3840         continue;
3841       if (MaskVal[i] < 0) {
3842         MaskVal[i] = Idx - l;
3843         continue;
3844       }
3845       if ((signed)(Idx - l) != MaskVal[i])
3846         return false;
3847     }
3848   }
3849
3850   return true;
3851 }
3852
3853 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3854 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3855 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3856   if (!VT.is128BitVector())
3857     return false;
3858
3859   unsigned NumElems = VT.getVectorNumElements();
3860
3861   if (NumElems != 4)
3862     return false;
3863
3864   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3865   return isUndefOrEqual(Mask[0], 6) &&
3866          isUndefOrEqual(Mask[1], 7) &&
3867          isUndefOrEqual(Mask[2], 2) &&
3868          isUndefOrEqual(Mask[3], 3);
3869 }
3870
3871 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3872 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3873 /// <2, 3, 2, 3>
3874 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3875   if (!VT.is128BitVector())
3876     return false;
3877
3878   unsigned NumElems = VT.getVectorNumElements();
3879
3880   if (NumElems != 4)
3881     return false;
3882
3883   return isUndefOrEqual(Mask[0], 2) &&
3884          isUndefOrEqual(Mask[1], 3) &&
3885          isUndefOrEqual(Mask[2], 2) &&
3886          isUndefOrEqual(Mask[3], 3);
3887 }
3888
3889 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3890 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3891 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3892   if (!VT.is128BitVector())
3893     return false;
3894
3895   unsigned NumElems = VT.getVectorNumElements();
3896
3897   if (NumElems != 2 && NumElems != 4)
3898     return false;
3899
3900   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3901     if (!isUndefOrEqual(Mask[i], i + NumElems))
3902       return false;
3903
3904   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3905     if (!isUndefOrEqual(Mask[i], i))
3906       return false;
3907
3908   return true;
3909 }
3910
3911 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3912 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3913 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3914   if (!VT.is128BitVector())
3915     return false;
3916
3917   unsigned NumElems = VT.getVectorNumElements();
3918
3919   if (NumElems != 2 && NumElems != 4)
3920     return false;
3921
3922   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3923     if (!isUndefOrEqual(Mask[i], i))
3924       return false;
3925
3926   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3927     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3928       return false;
3929
3930   return true;
3931 }
3932
3933 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3934 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3935 /// i. e: If all but one element come from the same vector.
3936 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3937   // TODO: Deal with AVX's VINSERTPS
3938   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3939     return false;
3940
3941   unsigned CorrectPosV1 = 0;
3942   unsigned CorrectPosV2 = 0;
3943   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3944     if (Mask[i] == i)
3945       ++CorrectPosV1;
3946     else if (Mask[i] == i + 4)
3947       ++CorrectPosV2;
3948
3949   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3950     // We have 3 elements from one vector, and one from another.
3951     return true;
3952
3953   return false;
3954 }
3955
3956 //
3957 // Some special combinations that can be optimized.
3958 //
3959 static
3960 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3961                                SelectionDAG &DAG) {
3962   MVT VT = SVOp->getSimpleValueType(0);
3963   SDLoc dl(SVOp);
3964
3965   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3966     return SDValue();
3967
3968   ArrayRef<int> Mask = SVOp->getMask();
3969
3970   // These are the special masks that may be optimized.
3971   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3972   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3973   bool MatchEvenMask = true;
3974   bool MatchOddMask  = true;
3975   for (int i=0; i<8; ++i) {
3976     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3977       MatchEvenMask = false;
3978     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3979       MatchOddMask = false;
3980   }
3981
3982   if (!MatchEvenMask && !MatchOddMask)
3983     return SDValue();
3984
3985   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3986
3987   SDValue Op0 = SVOp->getOperand(0);
3988   SDValue Op1 = SVOp->getOperand(1);
3989
3990   if (MatchEvenMask) {
3991     // Shift the second operand right to 32 bits.
3992     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3993     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3994   } else {
3995     // Shift the first operand left to 32 bits.
3996     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3997     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3998   }
3999   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4000   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4001 }
4002
4003 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4004 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4005 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4006                          bool HasInt256, bool V2IsSplat = false) {
4007
4008   assert(VT.getSizeInBits() >= 128 &&
4009          "Unsupported vector type for unpckl");
4010
4011   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4012   unsigned NumLanes;
4013   unsigned NumOf256BitLanes;
4014   unsigned NumElts = VT.getVectorNumElements();
4015   if (VT.is256BitVector()) {
4016     if (NumElts != 4 && NumElts != 8 &&
4017         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4018     return false;
4019     NumLanes = 2;
4020     NumOf256BitLanes = 1;
4021   } else if (VT.is512BitVector()) {
4022     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4023            "Unsupported vector type for unpckh");
4024     NumLanes = 2;
4025     NumOf256BitLanes = 2;
4026   } else {
4027     NumLanes = 1;
4028     NumOf256BitLanes = 1;
4029   }
4030
4031   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4032   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4033
4034   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4035     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4036       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4037         int BitI  = Mask[l256*NumEltsInStride+l+i];
4038         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4039         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4040           return false;
4041         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4042           return false;
4043         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4044           return false;
4045       }
4046     }
4047   }
4048   return true;
4049 }
4050
4051 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4052 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4053 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4054                          bool HasInt256, bool V2IsSplat = false) {
4055   assert(VT.getSizeInBits() >= 128 &&
4056          "Unsupported vector type for unpckh");
4057
4058   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4059   unsigned NumLanes;
4060   unsigned NumOf256BitLanes;
4061   unsigned NumElts = VT.getVectorNumElements();
4062   if (VT.is256BitVector()) {
4063     if (NumElts != 4 && NumElts != 8 &&
4064         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4065     return false;
4066     NumLanes = 2;
4067     NumOf256BitLanes = 1;
4068   } else if (VT.is512BitVector()) {
4069     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4070            "Unsupported vector type for unpckh");
4071     NumLanes = 2;
4072     NumOf256BitLanes = 2;
4073   } else {
4074     NumLanes = 1;
4075     NumOf256BitLanes = 1;
4076   }
4077
4078   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4079   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4080
4081   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4082     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4083       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4084         int BitI  = Mask[l256*NumEltsInStride+l+i];
4085         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4086         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4087           return false;
4088         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4089           return false;
4090         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4091           return false;
4092       }
4093     }
4094   }
4095   return true;
4096 }
4097
4098 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4099 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4100 /// <0, 0, 1, 1>
4101 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4102   unsigned NumElts = VT.getVectorNumElements();
4103   bool Is256BitVec = VT.is256BitVector();
4104
4105   if (VT.is512BitVector())
4106     return false;
4107   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4108          "Unsupported vector type for unpckh");
4109
4110   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4111       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4112     return false;
4113
4114   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4115   // FIXME: Need a better way to get rid of this, there's no latency difference
4116   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4117   // the former later. We should also remove the "_undef" special mask.
4118   if (NumElts == 4 && Is256BitVec)
4119     return false;
4120
4121   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4122   // independently on 128-bit lanes.
4123   unsigned NumLanes = VT.getSizeInBits()/128;
4124   unsigned NumLaneElts = NumElts/NumLanes;
4125
4126   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4127     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4128       int BitI  = Mask[l+i];
4129       int BitI1 = Mask[l+i+1];
4130
4131       if (!isUndefOrEqual(BitI, j))
4132         return false;
4133       if (!isUndefOrEqual(BitI1, j))
4134         return false;
4135     }
4136   }
4137
4138   return true;
4139 }
4140
4141 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4142 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4143 /// <2, 2, 3, 3>
4144 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4145   unsigned NumElts = VT.getVectorNumElements();
4146
4147   if (VT.is512BitVector())
4148     return false;
4149
4150   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4151          "Unsupported vector type for unpckh");
4152
4153   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4154       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4155     return false;
4156
4157   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4158   // independently on 128-bit lanes.
4159   unsigned NumLanes = VT.getSizeInBits()/128;
4160   unsigned NumLaneElts = NumElts/NumLanes;
4161
4162   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4163     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4164       int BitI  = Mask[l+i];
4165       int BitI1 = Mask[l+i+1];
4166       if (!isUndefOrEqual(BitI, j))
4167         return false;
4168       if (!isUndefOrEqual(BitI1, j))
4169         return false;
4170     }
4171   }
4172   return true;
4173 }
4174
4175 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4176 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4177 /// MOVSD, and MOVD, i.e. setting the lowest element.
4178 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4179   if (VT.getVectorElementType().getSizeInBits() < 32)
4180     return false;
4181   if (!VT.is128BitVector())
4182     return false;
4183
4184   unsigned NumElts = VT.getVectorNumElements();
4185
4186   if (!isUndefOrEqual(Mask[0], NumElts))
4187     return false;
4188
4189   for (unsigned i = 1; i != NumElts; ++i)
4190     if (!isUndefOrEqual(Mask[i], i))
4191       return false;
4192
4193   return true;
4194 }
4195
4196 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4197 /// as permutations between 128-bit chunks or halves. As an example: this
4198 /// shuffle bellow:
4199 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4200 /// The first half comes from the second half of V1 and the second half from the
4201 /// the second half of V2.
4202 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4203   if (!HasFp256 || !VT.is256BitVector())
4204     return false;
4205
4206   // The shuffle result is divided into half A and half B. In total the two
4207   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4208   // B must come from C, D, E or F.
4209   unsigned HalfSize = VT.getVectorNumElements()/2;
4210   bool MatchA = false, MatchB = false;
4211
4212   // Check if A comes from one of C, D, E, F.
4213   for (unsigned Half = 0; Half != 4; ++Half) {
4214     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4215       MatchA = true;
4216       break;
4217     }
4218   }
4219
4220   // Check if B comes from one of C, D, E, F.
4221   for (unsigned Half = 0; Half != 4; ++Half) {
4222     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4223       MatchB = true;
4224       break;
4225     }
4226   }
4227
4228   return MatchA && MatchB;
4229 }
4230
4231 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4232 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4233 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4234   MVT VT = SVOp->getSimpleValueType(0);
4235
4236   unsigned HalfSize = VT.getVectorNumElements()/2;
4237
4238   unsigned FstHalf = 0, SndHalf = 0;
4239   for (unsigned i = 0; i < HalfSize; ++i) {
4240     if (SVOp->getMaskElt(i) > 0) {
4241       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4242       break;
4243     }
4244   }
4245   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4246     if (SVOp->getMaskElt(i) > 0) {
4247       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4248       break;
4249     }
4250   }
4251
4252   return (FstHalf | (SndHalf << 4));
4253 }
4254
4255 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4256 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4257   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4258   if (EltSize < 32)
4259     return false;
4260
4261   unsigned NumElts = VT.getVectorNumElements();
4262   Imm8 = 0;
4263   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4264     for (unsigned i = 0; i != NumElts; ++i) {
4265       if (Mask[i] < 0)
4266         continue;
4267       Imm8 |= Mask[i] << (i*2);
4268     }
4269     return true;
4270   }
4271
4272   unsigned LaneSize = 4;
4273   SmallVector<int, 4> MaskVal(LaneSize, -1);
4274
4275   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4276     for (unsigned i = 0; i != LaneSize; ++i) {
4277       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4278         return false;
4279       if (Mask[i+l] < 0)
4280         continue;
4281       if (MaskVal[i] < 0) {
4282         MaskVal[i] = Mask[i+l] - l;
4283         Imm8 |= MaskVal[i] << (i*2);
4284         continue;
4285       }
4286       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4287         return false;
4288     }
4289   }
4290   return true;
4291 }
4292
4293 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4294 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4295 /// Note that VPERMIL mask matching is different depending whether theunderlying
4296 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4297 /// to the same elements of the low, but to the higher half of the source.
4298 /// In VPERMILPD the two lanes could be shuffled independently of each other
4299 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4300 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4301   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4302   if (VT.getSizeInBits() < 256 || EltSize < 32)
4303     return false;
4304   bool symetricMaskRequired = (EltSize == 32);
4305   unsigned NumElts = VT.getVectorNumElements();
4306
4307   unsigned NumLanes = VT.getSizeInBits()/128;
4308   unsigned LaneSize = NumElts/NumLanes;
4309   // 2 or 4 elements in one lane
4310
4311   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4312   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4313     for (unsigned i = 0; i != LaneSize; ++i) {
4314       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4315         return false;
4316       if (symetricMaskRequired) {
4317         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4318           ExpectedMaskVal[i] = Mask[i+l] - l;
4319           continue;
4320         }
4321         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4322           return false;
4323       }
4324     }
4325   }
4326   return true;
4327 }
4328
4329 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4330 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4331 /// element of vector 2 and the other elements to come from vector 1 in order.
4332 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4333                                bool V2IsSplat = false, bool V2IsUndef = false) {
4334   if (!VT.is128BitVector())
4335     return false;
4336
4337   unsigned NumOps = VT.getVectorNumElements();
4338   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4339     return false;
4340
4341   if (!isUndefOrEqual(Mask[0], 0))
4342     return false;
4343
4344   for (unsigned i = 1; i != NumOps; ++i)
4345     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4346           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4347           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4348       return false;
4349
4350   return true;
4351 }
4352
4353 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4354 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4355 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4356 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4357                            const X86Subtarget *Subtarget) {
4358   if (!Subtarget->hasSSE3())
4359     return false;
4360
4361   unsigned NumElems = VT.getVectorNumElements();
4362
4363   if ((VT.is128BitVector() && NumElems != 4) ||
4364       (VT.is256BitVector() && NumElems != 8) ||
4365       (VT.is512BitVector() && NumElems != 16))
4366     return false;
4367
4368   // "i+1" is the value the indexed mask element must have
4369   for (unsigned i = 0; i != NumElems; i += 2)
4370     if (!isUndefOrEqual(Mask[i], i+1) ||
4371         !isUndefOrEqual(Mask[i+1], i+1))
4372       return false;
4373
4374   return true;
4375 }
4376
4377 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4378 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4379 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4380 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4381                            const X86Subtarget *Subtarget) {
4382   if (!Subtarget->hasSSE3())
4383     return false;
4384
4385   unsigned NumElems = VT.getVectorNumElements();
4386
4387   if ((VT.is128BitVector() && NumElems != 4) ||
4388       (VT.is256BitVector() && NumElems != 8) ||
4389       (VT.is512BitVector() && NumElems != 16))
4390     return false;
4391
4392   // "i" is the value the indexed mask element must have
4393   for (unsigned i = 0; i != NumElems; i += 2)
4394     if (!isUndefOrEqual(Mask[i], i) ||
4395         !isUndefOrEqual(Mask[i+1], i))
4396       return false;
4397
4398   return true;
4399 }
4400
4401 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4402 /// specifies a shuffle of elements that is suitable for input to 256-bit
4403 /// version of MOVDDUP.
4404 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4405   if (!HasFp256 || !VT.is256BitVector())
4406     return false;
4407
4408   unsigned NumElts = VT.getVectorNumElements();
4409   if (NumElts != 4)
4410     return false;
4411
4412   for (unsigned i = 0; i != NumElts/2; ++i)
4413     if (!isUndefOrEqual(Mask[i], 0))
4414       return false;
4415   for (unsigned i = NumElts/2; i != NumElts; ++i)
4416     if (!isUndefOrEqual(Mask[i], NumElts/2))
4417       return false;
4418   return true;
4419 }
4420
4421 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4422 /// specifies a shuffle of elements that is suitable for input to 128-bit
4423 /// version of MOVDDUP.
4424 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4425   if (!VT.is128BitVector())
4426     return false;
4427
4428   unsigned e = VT.getVectorNumElements() / 2;
4429   for (unsigned i = 0; i != e; ++i)
4430     if (!isUndefOrEqual(Mask[i], i))
4431       return false;
4432   for (unsigned i = 0; i != e; ++i)
4433     if (!isUndefOrEqual(Mask[e+i], i))
4434       return false;
4435   return true;
4436 }
4437
4438 /// isVEXTRACTIndex - Return true if the specified
4439 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4440 /// suitable for instruction that extract 128 or 256 bit vectors
4441 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4442   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4443   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4444     return false;
4445
4446   // The index should be aligned on a vecWidth-bit boundary.
4447   uint64_t Index =
4448     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4449
4450   MVT VT = N->getSimpleValueType(0);
4451   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4452   bool Result = (Index * ElSize) % vecWidth == 0;
4453
4454   return Result;
4455 }
4456
4457 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4458 /// operand specifies a subvector insert that is suitable for input to
4459 /// insertion of 128 or 256-bit subvectors
4460 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4461   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4462   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4463     return false;
4464   // The index should be aligned on a vecWidth-bit boundary.
4465   uint64_t Index =
4466     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4467
4468   MVT VT = N->getSimpleValueType(0);
4469   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4470   bool Result = (Index * ElSize) % vecWidth == 0;
4471
4472   return Result;
4473 }
4474
4475 bool X86::isVINSERT128Index(SDNode *N) {
4476   return isVINSERTIndex(N, 128);
4477 }
4478
4479 bool X86::isVINSERT256Index(SDNode *N) {
4480   return isVINSERTIndex(N, 256);
4481 }
4482
4483 bool X86::isVEXTRACT128Index(SDNode *N) {
4484   return isVEXTRACTIndex(N, 128);
4485 }
4486
4487 bool X86::isVEXTRACT256Index(SDNode *N) {
4488   return isVEXTRACTIndex(N, 256);
4489 }
4490
4491 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4492 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4493 /// Handles 128-bit and 256-bit.
4494 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4495   MVT VT = N->getSimpleValueType(0);
4496
4497   assert((VT.getSizeInBits() >= 128) &&
4498          "Unsupported vector type for PSHUF/SHUFP");
4499
4500   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4501   // independently on 128-bit lanes.
4502   unsigned NumElts = VT.getVectorNumElements();
4503   unsigned NumLanes = VT.getSizeInBits()/128;
4504   unsigned NumLaneElts = NumElts/NumLanes;
4505
4506   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4507          "Only supports 2, 4 or 8 elements per lane");
4508
4509   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4510   unsigned Mask = 0;
4511   for (unsigned i = 0; i != NumElts; ++i) {
4512     int Elt = N->getMaskElt(i);
4513     if (Elt < 0) continue;
4514     Elt &= NumLaneElts - 1;
4515     unsigned ShAmt = (i << Shift) % 8;
4516     Mask |= Elt << ShAmt;
4517   }
4518
4519   return Mask;
4520 }
4521
4522 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4523 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4524 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4525   MVT VT = N->getSimpleValueType(0);
4526
4527   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4528          "Unsupported vector type for PSHUFHW");
4529
4530   unsigned NumElts = VT.getVectorNumElements();
4531
4532   unsigned Mask = 0;
4533   for (unsigned l = 0; l != NumElts; l += 8) {
4534     // 8 nodes per lane, but we only care about the last 4.
4535     for (unsigned i = 0; i < 4; ++i) {
4536       int Elt = N->getMaskElt(l+i+4);
4537       if (Elt < 0) continue;
4538       Elt &= 0x3; // only 2-bits.
4539       Mask |= Elt << (i * 2);
4540     }
4541   }
4542
4543   return Mask;
4544 }
4545
4546 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4547 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4548 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4549   MVT VT = N->getSimpleValueType(0);
4550
4551   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4552          "Unsupported vector type for PSHUFHW");
4553
4554   unsigned NumElts = VT.getVectorNumElements();
4555
4556   unsigned Mask = 0;
4557   for (unsigned l = 0; l != NumElts; l += 8) {
4558     // 8 nodes per lane, but we only care about the first 4.
4559     for (unsigned i = 0; i < 4; ++i) {
4560       int Elt = N->getMaskElt(l+i);
4561       if (Elt < 0) continue;
4562       Elt &= 0x3; // only 2-bits
4563       Mask |= Elt << (i * 2);
4564     }
4565   }
4566
4567   return Mask;
4568 }
4569
4570 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4571 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4572 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4573   MVT VT = SVOp->getSimpleValueType(0);
4574   unsigned EltSize = VT.is512BitVector() ? 1 :
4575     VT.getVectorElementType().getSizeInBits() >> 3;
4576
4577   unsigned NumElts = VT.getVectorNumElements();
4578   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4579   unsigned NumLaneElts = NumElts/NumLanes;
4580
4581   int Val = 0;
4582   unsigned i;
4583   for (i = 0; i != NumElts; ++i) {
4584     Val = SVOp->getMaskElt(i);
4585     if (Val >= 0)
4586       break;
4587   }
4588   if (Val >= (int)NumElts)
4589     Val -= NumElts - NumLaneElts;
4590
4591   assert(Val - i > 0 && "PALIGNR imm should be positive");
4592   return (Val - i) * EltSize;
4593 }
4594
4595 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4596   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4597   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4598     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4599
4600   uint64_t Index =
4601     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4602
4603   MVT VecVT = N->getOperand(0).getSimpleValueType();
4604   MVT ElVT = VecVT.getVectorElementType();
4605
4606   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4607   return Index / NumElemsPerChunk;
4608 }
4609
4610 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4611   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4612   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4613     llvm_unreachable("Illegal insert subvector for VINSERT");
4614
4615   uint64_t Index =
4616     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4617
4618   MVT VecVT = N->getSimpleValueType(0);
4619   MVT ElVT = VecVT.getVectorElementType();
4620
4621   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4622   return Index / NumElemsPerChunk;
4623 }
4624
4625 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4626 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4627 /// and VINSERTI128 instructions.
4628 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4629   return getExtractVEXTRACTImmediate(N, 128);
4630 }
4631
4632 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4633 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4634 /// and VINSERTI64x4 instructions.
4635 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4636   return getExtractVEXTRACTImmediate(N, 256);
4637 }
4638
4639 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4640 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4641 /// and VINSERTI128 instructions.
4642 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4643   return getInsertVINSERTImmediate(N, 128);
4644 }
4645
4646 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4647 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4648 /// and VINSERTI64x4 instructions.
4649 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4650   return getInsertVINSERTImmediate(N, 256);
4651 }
4652
4653 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4654 /// constant +0.0.
4655 bool X86::isZeroNode(SDValue Elt) {
4656   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4657     return CN->isNullValue();
4658   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4659     return CFP->getValueAPF().isPosZero();
4660   return false;
4661 }
4662
4663 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4664 /// their permute mask.
4665 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4666                                     SelectionDAG &DAG) {
4667   MVT VT = SVOp->getSimpleValueType(0);
4668   unsigned NumElems = VT.getVectorNumElements();
4669   SmallVector<int, 8> MaskVec;
4670
4671   for (unsigned i = 0; i != NumElems; ++i) {
4672     int Idx = SVOp->getMaskElt(i);
4673     if (Idx >= 0) {
4674       if (Idx < (int)NumElems)
4675         Idx += NumElems;
4676       else
4677         Idx -= NumElems;
4678     }
4679     MaskVec.push_back(Idx);
4680   }
4681   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4682                               SVOp->getOperand(0), &MaskVec[0]);
4683 }
4684
4685 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4686 /// match movhlps. The lower half elements should come from upper half of
4687 /// V1 (and in order), and the upper half elements should come from the upper
4688 /// half of V2 (and in order).
4689 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4690   if (!VT.is128BitVector())
4691     return false;
4692   if (VT.getVectorNumElements() != 4)
4693     return false;
4694   for (unsigned i = 0, e = 2; i != e; ++i)
4695     if (!isUndefOrEqual(Mask[i], i+2))
4696       return false;
4697   for (unsigned i = 2; i != 4; ++i)
4698     if (!isUndefOrEqual(Mask[i], i+4))
4699       return false;
4700   return true;
4701 }
4702
4703 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4704 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4705 /// required.
4706 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4707   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4708     return false;
4709   N = N->getOperand(0).getNode();
4710   if (!ISD::isNON_EXTLoad(N))
4711     return false;
4712   if (LD)
4713     *LD = cast<LoadSDNode>(N);
4714   return true;
4715 }
4716
4717 // Test whether the given value is a vector value which will be legalized
4718 // into a load.
4719 static bool WillBeConstantPoolLoad(SDNode *N) {
4720   if (N->getOpcode() != ISD::BUILD_VECTOR)
4721     return false;
4722
4723   // Check for any non-constant elements.
4724   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4725     switch (N->getOperand(i).getNode()->getOpcode()) {
4726     case ISD::UNDEF:
4727     case ISD::ConstantFP:
4728     case ISD::Constant:
4729       break;
4730     default:
4731       return false;
4732     }
4733
4734   // Vectors of all-zeros and all-ones are materialized with special
4735   // instructions rather than being loaded.
4736   return !ISD::isBuildVectorAllZeros(N) &&
4737          !ISD::isBuildVectorAllOnes(N);
4738 }
4739
4740 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4741 /// match movlp{s|d}. The lower half elements should come from lower half of
4742 /// V1 (and in order), and the upper half elements should come from the upper
4743 /// half of V2 (and in order). And since V1 will become the source of the
4744 /// MOVLP, it must be either a vector load or a scalar load to vector.
4745 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4746                                ArrayRef<int> Mask, MVT VT) {
4747   if (!VT.is128BitVector())
4748     return false;
4749
4750   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4751     return false;
4752   // Is V2 is a vector load, don't do this transformation. We will try to use
4753   // load folding shufps op.
4754   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4755     return false;
4756
4757   unsigned NumElems = VT.getVectorNumElements();
4758
4759   if (NumElems != 2 && NumElems != 4)
4760     return false;
4761   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4762     if (!isUndefOrEqual(Mask[i], i))
4763       return false;
4764   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4765     if (!isUndefOrEqual(Mask[i], i+NumElems))
4766       return false;
4767   return true;
4768 }
4769
4770 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4771 /// all the same.
4772 static bool isSplatVector(SDNode *N) {
4773   if (N->getOpcode() != ISD::BUILD_VECTOR)
4774     return false;
4775
4776   SDValue SplatValue = N->getOperand(0);
4777   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4778     if (N->getOperand(i) != SplatValue)
4779       return false;
4780   return true;
4781 }
4782
4783 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4784 /// to an zero vector.
4785 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4786 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4787   SDValue V1 = N->getOperand(0);
4788   SDValue V2 = N->getOperand(1);
4789   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4790   for (unsigned i = 0; i != NumElems; ++i) {
4791     int Idx = N->getMaskElt(i);
4792     if (Idx >= (int)NumElems) {
4793       unsigned Opc = V2.getOpcode();
4794       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4795         continue;
4796       if (Opc != ISD::BUILD_VECTOR ||
4797           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4798         return false;
4799     } else if (Idx >= 0) {
4800       unsigned Opc = V1.getOpcode();
4801       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4802         continue;
4803       if (Opc != ISD::BUILD_VECTOR ||
4804           !X86::isZeroNode(V1.getOperand(Idx)))
4805         return false;
4806     }
4807   }
4808   return true;
4809 }
4810
4811 /// getZeroVector - Returns a vector of specified type with all zero elements.
4812 ///
4813 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4814                              SelectionDAG &DAG, SDLoc dl) {
4815   assert(VT.isVector() && "Expected a vector type");
4816
4817   // Always build SSE zero vectors as <4 x i32> bitcasted
4818   // to their dest type. This ensures they get CSE'd.
4819   SDValue Vec;
4820   if (VT.is128BitVector()) {  // SSE
4821     if (Subtarget->hasSSE2()) {  // SSE2
4822       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4823       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4824     } else { // SSE1
4825       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4826       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4827     }
4828   } else if (VT.is256BitVector()) { // AVX
4829     if (Subtarget->hasInt256()) { // AVX2
4830       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4831       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4832       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4833     } else {
4834       // 256-bit logic and arithmetic instructions in AVX are all
4835       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4836       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4837       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4838       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4839     }
4840   } else if (VT.is512BitVector()) { // AVX-512
4841       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4842       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4843                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4844       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4845   } else if (VT.getScalarType() == MVT::i1) {
4846     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4847     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4848     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4849     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4850   } else
4851     llvm_unreachable("Unexpected vector type");
4852
4853   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4854 }
4855
4856 /// getOnesVector - Returns a vector of specified type with all bits set.
4857 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4858 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4859 /// Then bitcast to their original type, ensuring they get CSE'd.
4860 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4861                              SDLoc dl) {
4862   assert(VT.isVector() && "Expected a vector type");
4863
4864   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4865   SDValue Vec;
4866   if (VT.is256BitVector()) {
4867     if (HasInt256) { // AVX2
4868       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4869       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4870     } else { // AVX
4871       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4872       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4873     }
4874   } else if (VT.is128BitVector()) {
4875     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4876   } else
4877     llvm_unreachable("Unexpected vector type");
4878
4879   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4880 }
4881
4882 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4883 /// that point to V2 points to its first element.
4884 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4885   for (unsigned i = 0; i != NumElems; ++i) {
4886     if (Mask[i] > (int)NumElems) {
4887       Mask[i] = NumElems;
4888     }
4889   }
4890 }
4891
4892 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4893 /// operation of specified width.
4894 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4895                        SDValue V2) {
4896   unsigned NumElems = VT.getVectorNumElements();
4897   SmallVector<int, 8> Mask;
4898   Mask.push_back(NumElems);
4899   for (unsigned i = 1; i != NumElems; ++i)
4900     Mask.push_back(i);
4901   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4902 }
4903
4904 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4905 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4906                           SDValue V2) {
4907   unsigned NumElems = VT.getVectorNumElements();
4908   SmallVector<int, 8> Mask;
4909   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4910     Mask.push_back(i);
4911     Mask.push_back(i + NumElems);
4912   }
4913   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4914 }
4915
4916 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4917 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4918                           SDValue V2) {
4919   unsigned NumElems = VT.getVectorNumElements();
4920   SmallVector<int, 8> Mask;
4921   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4922     Mask.push_back(i + Half);
4923     Mask.push_back(i + NumElems + Half);
4924   }
4925   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4926 }
4927
4928 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4929 // a generic shuffle instruction because the target has no such instructions.
4930 // Generate shuffles which repeat i16 and i8 several times until they can be
4931 // represented by v4f32 and then be manipulated by target suported shuffles.
4932 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4933   MVT VT = V.getSimpleValueType();
4934   int NumElems = VT.getVectorNumElements();
4935   SDLoc dl(V);
4936
4937   while (NumElems > 4) {
4938     if (EltNo < NumElems/2) {
4939       V = getUnpackl(DAG, dl, VT, V, V);
4940     } else {
4941       V = getUnpackh(DAG, dl, VT, V, V);
4942       EltNo -= NumElems/2;
4943     }
4944     NumElems >>= 1;
4945   }
4946   return V;
4947 }
4948
4949 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4950 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4951   MVT VT = V.getSimpleValueType();
4952   SDLoc dl(V);
4953
4954   if (VT.is128BitVector()) {
4955     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4956     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4957     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4958                              &SplatMask[0]);
4959   } else if (VT.is256BitVector()) {
4960     // To use VPERMILPS to splat scalars, the second half of indicies must
4961     // refer to the higher part, which is a duplication of the lower one,
4962     // because VPERMILPS can only handle in-lane permutations.
4963     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4964                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4965
4966     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4967     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4968                              &SplatMask[0]);
4969   } else
4970     llvm_unreachable("Vector size not supported");
4971
4972   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4973 }
4974
4975 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4976 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4977   MVT SrcVT = SV->getSimpleValueType(0);
4978   SDValue V1 = SV->getOperand(0);
4979   SDLoc dl(SV);
4980
4981   int EltNo = SV->getSplatIndex();
4982   int NumElems = SrcVT.getVectorNumElements();
4983   bool Is256BitVec = SrcVT.is256BitVector();
4984
4985   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4986          "Unknown how to promote splat for type");
4987
4988   // Extract the 128-bit part containing the splat element and update
4989   // the splat element index when it refers to the higher register.
4990   if (Is256BitVec) {
4991     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4992     if (EltNo >= NumElems/2)
4993       EltNo -= NumElems/2;
4994   }
4995
4996   // All i16 and i8 vector types can't be used directly by a generic shuffle
4997   // instruction because the target has no such instruction. Generate shuffles
4998   // which repeat i16 and i8 several times until they fit in i32, and then can
4999   // be manipulated by target suported shuffles.
5000   MVT EltVT = SrcVT.getVectorElementType();
5001   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5002     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5003
5004   // Recreate the 256-bit vector and place the same 128-bit vector
5005   // into the low and high part. This is necessary because we want
5006   // to use VPERM* to shuffle the vectors
5007   if (Is256BitVec) {
5008     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5009   }
5010
5011   return getLegalSplat(DAG, V1, EltNo);
5012 }
5013
5014 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5015 /// vector of zero or undef vector.  This produces a shuffle where the low
5016 /// element of V2 is swizzled into the zero/undef vector, landing at element
5017 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5018 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5019                                            bool IsZero,
5020                                            const X86Subtarget *Subtarget,
5021                                            SelectionDAG &DAG) {
5022   MVT VT = V2.getSimpleValueType();
5023   SDValue V1 = IsZero
5024     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5025   unsigned NumElems = VT.getVectorNumElements();
5026   SmallVector<int, 16> MaskVec;
5027   for (unsigned i = 0; i != NumElems; ++i)
5028     // If this is the insertion idx, put the low elt of V2 here.
5029     MaskVec.push_back(i == Idx ? NumElems : i);
5030   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5031 }
5032
5033 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5034 /// target specific opcode. Returns true if the Mask could be calculated.
5035 /// Sets IsUnary to true if only uses one source.
5036 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5037                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5038   unsigned NumElems = VT.getVectorNumElements();
5039   SDValue ImmN;
5040
5041   IsUnary = false;
5042   switch(N->getOpcode()) {
5043   case X86ISD::SHUFP:
5044     ImmN = N->getOperand(N->getNumOperands()-1);
5045     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5046     break;
5047   case X86ISD::UNPCKH:
5048     DecodeUNPCKHMask(VT, Mask);
5049     break;
5050   case X86ISD::UNPCKL:
5051     DecodeUNPCKLMask(VT, Mask);
5052     break;
5053   case X86ISD::MOVHLPS:
5054     DecodeMOVHLPSMask(NumElems, Mask);
5055     break;
5056   case X86ISD::MOVLHPS:
5057     DecodeMOVLHPSMask(NumElems, Mask);
5058     break;
5059   case X86ISD::PALIGNR:
5060     ImmN = N->getOperand(N->getNumOperands()-1);
5061     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5062     break;
5063   case X86ISD::PSHUFD:
5064   case X86ISD::VPERMILP:
5065     ImmN = N->getOperand(N->getNumOperands()-1);
5066     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5067     IsUnary = true;
5068     break;
5069   case X86ISD::PSHUFHW:
5070     ImmN = N->getOperand(N->getNumOperands()-1);
5071     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5072     IsUnary = true;
5073     break;
5074   case X86ISD::PSHUFLW:
5075     ImmN = N->getOperand(N->getNumOperands()-1);
5076     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5077     IsUnary = true;
5078     break;
5079   case X86ISD::VPERMI:
5080     ImmN = N->getOperand(N->getNumOperands()-1);
5081     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5082     IsUnary = true;
5083     break;
5084   case X86ISD::MOVSS:
5085   case X86ISD::MOVSD: {
5086     // The index 0 always comes from the first element of the second source,
5087     // this is why MOVSS and MOVSD are used in the first place. The other
5088     // elements come from the other positions of the first source vector
5089     Mask.push_back(NumElems);
5090     for (unsigned i = 1; i != NumElems; ++i) {
5091       Mask.push_back(i);
5092     }
5093     break;
5094   }
5095   case X86ISD::VPERM2X128:
5096     ImmN = N->getOperand(N->getNumOperands()-1);
5097     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5098     if (Mask.empty()) return false;
5099     break;
5100   case X86ISD::MOVDDUP:
5101   case X86ISD::MOVLHPD:
5102   case X86ISD::MOVLPD:
5103   case X86ISD::MOVLPS:
5104   case X86ISD::MOVSHDUP:
5105   case X86ISD::MOVSLDUP:
5106     // Not yet implemented
5107     return false;
5108   default: llvm_unreachable("unknown target shuffle node");
5109   }
5110
5111   return true;
5112 }
5113
5114 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5115 /// element of the result of the vector shuffle.
5116 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5117                                    unsigned Depth) {
5118   if (Depth == 6)
5119     return SDValue();  // Limit search depth.
5120
5121   SDValue V = SDValue(N, 0);
5122   EVT VT = V.getValueType();
5123   unsigned Opcode = V.getOpcode();
5124
5125   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5126   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5127     int Elt = SV->getMaskElt(Index);
5128
5129     if (Elt < 0)
5130       return DAG.getUNDEF(VT.getVectorElementType());
5131
5132     unsigned NumElems = VT.getVectorNumElements();
5133     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5134                                          : SV->getOperand(1);
5135     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5136   }
5137
5138   // Recurse into target specific vector shuffles to find scalars.
5139   if (isTargetShuffle(Opcode)) {
5140     MVT ShufVT = V.getSimpleValueType();
5141     unsigned NumElems = ShufVT.getVectorNumElements();
5142     SmallVector<int, 16> ShuffleMask;
5143     bool IsUnary;
5144
5145     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5146       return SDValue();
5147
5148     int Elt = ShuffleMask[Index];
5149     if (Elt < 0)
5150       return DAG.getUNDEF(ShufVT.getVectorElementType());
5151
5152     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5153                                          : N->getOperand(1);
5154     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5155                                Depth+1);
5156   }
5157
5158   // Actual nodes that may contain scalar elements
5159   if (Opcode == ISD::BITCAST) {
5160     V = V.getOperand(0);
5161     EVT SrcVT = V.getValueType();
5162     unsigned NumElems = VT.getVectorNumElements();
5163
5164     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5165       return SDValue();
5166   }
5167
5168   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5169     return (Index == 0) ? V.getOperand(0)
5170                         : DAG.getUNDEF(VT.getVectorElementType());
5171
5172   if (V.getOpcode() == ISD::BUILD_VECTOR)
5173     return V.getOperand(Index);
5174
5175   return SDValue();
5176 }
5177
5178 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5179 /// shuffle operation which come from a consecutively from a zero. The
5180 /// search can start in two different directions, from left or right.
5181 /// We count undefs as zeros until PreferredNum is reached.
5182 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5183                                          unsigned NumElems, bool ZerosFromLeft,
5184                                          SelectionDAG &DAG,
5185                                          unsigned PreferredNum = -1U) {
5186   unsigned NumZeros = 0;
5187   for (unsigned i = 0; i != NumElems; ++i) {
5188     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5189     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5190     if (!Elt.getNode())
5191       break;
5192
5193     if (X86::isZeroNode(Elt))
5194       ++NumZeros;
5195     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5196       NumZeros = std::min(NumZeros + 1, PreferredNum);
5197     else
5198       break;
5199   }
5200
5201   return NumZeros;
5202 }
5203
5204 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5205 /// correspond consecutively to elements from one of the vector operands,
5206 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5207 static
5208 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5209                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5210                               unsigned NumElems, unsigned &OpNum) {
5211   bool SeenV1 = false;
5212   bool SeenV2 = false;
5213
5214   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5215     int Idx = SVOp->getMaskElt(i);
5216     // Ignore undef indicies
5217     if (Idx < 0)
5218       continue;
5219
5220     if (Idx < (int)NumElems)
5221       SeenV1 = true;
5222     else
5223       SeenV2 = true;
5224
5225     // Only accept consecutive elements from the same vector
5226     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5227       return false;
5228   }
5229
5230   OpNum = SeenV1 ? 0 : 1;
5231   return true;
5232 }
5233
5234 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5235 /// logical left shift of a vector.
5236 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5237                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5238   unsigned NumElems =
5239     SVOp->getSimpleValueType(0).getVectorNumElements();
5240   unsigned NumZeros = getNumOfConsecutiveZeros(
5241       SVOp, NumElems, false /* check zeros from right */, DAG,
5242       SVOp->getMaskElt(0));
5243   unsigned OpSrc;
5244
5245   if (!NumZeros)
5246     return false;
5247
5248   // Considering the elements in the mask that are not consecutive zeros,
5249   // check if they consecutively come from only one of the source vectors.
5250   //
5251   //               V1 = {X, A, B, C}     0
5252   //                         \  \  \    /
5253   //   vector_shuffle V1, V2 <1, 2, 3, X>
5254   //
5255   if (!isShuffleMaskConsecutive(SVOp,
5256             0,                   // Mask Start Index
5257             NumElems-NumZeros,   // Mask End Index(exclusive)
5258             NumZeros,            // Where to start looking in the src vector
5259             NumElems,            // Number of elements in vector
5260             OpSrc))              // Which source operand ?
5261     return false;
5262
5263   isLeft = false;
5264   ShAmt = NumZeros;
5265   ShVal = SVOp->getOperand(OpSrc);
5266   return true;
5267 }
5268
5269 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5270 /// logical left shift of a vector.
5271 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5272                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5273   unsigned NumElems =
5274     SVOp->getSimpleValueType(0).getVectorNumElements();
5275   unsigned NumZeros = getNumOfConsecutiveZeros(
5276       SVOp, NumElems, true /* check zeros from left */, DAG,
5277       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5278   unsigned OpSrc;
5279
5280   if (!NumZeros)
5281     return false;
5282
5283   // Considering the elements in the mask that are not consecutive zeros,
5284   // check if they consecutively come from only one of the source vectors.
5285   //
5286   //                           0    { A, B, X, X } = V2
5287   //                          / \    /  /
5288   //   vector_shuffle V1, V2 <X, X, 4, 5>
5289   //
5290   if (!isShuffleMaskConsecutive(SVOp,
5291             NumZeros,     // Mask Start Index
5292             NumElems,     // Mask End Index(exclusive)
5293             0,            // Where to start looking in the src vector
5294             NumElems,     // Number of elements in vector
5295             OpSrc))       // Which source operand ?
5296     return false;
5297
5298   isLeft = true;
5299   ShAmt = NumZeros;
5300   ShVal = SVOp->getOperand(OpSrc);
5301   return true;
5302 }
5303
5304 /// isVectorShift - Returns true if the shuffle can be implemented as a
5305 /// logical left or right shift of a vector.
5306 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5307                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5308   // Although the logic below support any bitwidth size, there are no
5309   // shift instructions which handle more than 128-bit vectors.
5310   if (!SVOp->getSimpleValueType(0).is128BitVector())
5311     return false;
5312
5313   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5314       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5315     return true;
5316
5317   return false;
5318 }
5319
5320 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5321 ///
5322 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5323                                        unsigned NumNonZero, unsigned NumZero,
5324                                        SelectionDAG &DAG,
5325                                        const X86Subtarget* Subtarget,
5326                                        const TargetLowering &TLI) {
5327   if (NumNonZero > 8)
5328     return SDValue();
5329
5330   SDLoc dl(Op);
5331   SDValue V;
5332   bool First = true;
5333   for (unsigned i = 0; i < 16; ++i) {
5334     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5335     if (ThisIsNonZero && First) {
5336       if (NumZero)
5337         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5338       else
5339         V = DAG.getUNDEF(MVT::v8i16);
5340       First = false;
5341     }
5342
5343     if ((i & 1) != 0) {
5344       SDValue ThisElt, LastElt;
5345       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5346       if (LastIsNonZero) {
5347         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5348                               MVT::i16, Op.getOperand(i-1));
5349       }
5350       if (ThisIsNonZero) {
5351         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5352         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5353                               ThisElt, DAG.getConstant(8, MVT::i8));
5354         if (LastIsNonZero)
5355           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5356       } else
5357         ThisElt = LastElt;
5358
5359       if (ThisElt.getNode())
5360         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5361                         DAG.getIntPtrConstant(i/2));
5362     }
5363   }
5364
5365   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5366 }
5367
5368 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5369 ///
5370 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5371                                      unsigned NumNonZero, unsigned NumZero,
5372                                      SelectionDAG &DAG,
5373                                      const X86Subtarget* Subtarget,
5374                                      const TargetLowering &TLI) {
5375   if (NumNonZero > 4)
5376     return SDValue();
5377
5378   SDLoc dl(Op);
5379   SDValue V;
5380   bool First = true;
5381   for (unsigned i = 0; i < 8; ++i) {
5382     bool isNonZero = (NonZeros & (1 << i)) != 0;
5383     if (isNonZero) {
5384       if (First) {
5385         if (NumZero)
5386           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5387         else
5388           V = DAG.getUNDEF(MVT::v8i16);
5389         First = false;
5390       }
5391       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5392                       MVT::v8i16, V, Op.getOperand(i),
5393                       DAG.getIntPtrConstant(i));
5394     }
5395   }
5396
5397   return V;
5398 }
5399
5400 /// getVShift - Return a vector logical shift node.
5401 ///
5402 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5403                          unsigned NumBits, SelectionDAG &DAG,
5404                          const TargetLowering &TLI, SDLoc dl) {
5405   assert(VT.is128BitVector() && "Unknown type for VShift");
5406   EVT ShVT = MVT::v2i64;
5407   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5408   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5409   return DAG.getNode(ISD::BITCAST, dl, VT,
5410                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5411                              DAG.getConstant(NumBits,
5412                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5413 }
5414
5415 static SDValue
5416 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5417
5418   // Check if the scalar load can be widened into a vector load. And if
5419   // the address is "base + cst" see if the cst can be "absorbed" into
5420   // the shuffle mask.
5421   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5422     SDValue Ptr = LD->getBasePtr();
5423     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5424       return SDValue();
5425     EVT PVT = LD->getValueType(0);
5426     if (PVT != MVT::i32 && PVT != MVT::f32)
5427       return SDValue();
5428
5429     int FI = -1;
5430     int64_t Offset = 0;
5431     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5432       FI = FINode->getIndex();
5433       Offset = 0;
5434     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5435                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5436       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5437       Offset = Ptr.getConstantOperandVal(1);
5438       Ptr = Ptr.getOperand(0);
5439     } else {
5440       return SDValue();
5441     }
5442
5443     // FIXME: 256-bit vector instructions don't require a strict alignment,
5444     // improve this code to support it better.
5445     unsigned RequiredAlign = VT.getSizeInBits()/8;
5446     SDValue Chain = LD->getChain();
5447     // Make sure the stack object alignment is at least 16 or 32.
5448     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5449     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5450       if (MFI->isFixedObjectIndex(FI)) {
5451         // Can't change the alignment. FIXME: It's possible to compute
5452         // the exact stack offset and reference FI + adjust offset instead.
5453         // If someone *really* cares about this. That's the way to implement it.
5454         return SDValue();
5455       } else {
5456         MFI->setObjectAlignment(FI, RequiredAlign);
5457       }
5458     }
5459
5460     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5461     // Ptr + (Offset & ~15).
5462     if (Offset < 0)
5463       return SDValue();
5464     if ((Offset % RequiredAlign) & 3)
5465       return SDValue();
5466     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5467     if (StartOffset)
5468       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5469                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5470
5471     int EltNo = (Offset - StartOffset) >> 2;
5472     unsigned NumElems = VT.getVectorNumElements();
5473
5474     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5475     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5476                              LD->getPointerInfo().getWithOffset(StartOffset),
5477                              false, false, false, 0);
5478
5479     SmallVector<int, 8> Mask;
5480     for (unsigned i = 0; i != NumElems; ++i)
5481       Mask.push_back(EltNo);
5482
5483     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5484   }
5485
5486   return SDValue();
5487 }
5488
5489 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5490 /// vector of type 'VT', see if the elements can be replaced by a single large
5491 /// load which has the same value as a build_vector whose operands are 'elts'.
5492 ///
5493 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5494 ///
5495 /// FIXME: we'd also like to handle the case where the last elements are zero
5496 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5497 /// There's even a handy isZeroNode for that purpose.
5498 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5499                                         SDLoc &DL, SelectionDAG &DAG,
5500                                         bool isAfterLegalize) {
5501   EVT EltVT = VT.getVectorElementType();
5502   unsigned NumElems = Elts.size();
5503
5504   LoadSDNode *LDBase = nullptr;
5505   unsigned LastLoadedElt = -1U;
5506
5507   // For each element in the initializer, see if we've found a load or an undef.
5508   // If we don't find an initial load element, or later load elements are
5509   // non-consecutive, bail out.
5510   for (unsigned i = 0; i < NumElems; ++i) {
5511     SDValue Elt = Elts[i];
5512
5513     if (!Elt.getNode() ||
5514         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5515       return SDValue();
5516     if (!LDBase) {
5517       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5518         return SDValue();
5519       LDBase = cast<LoadSDNode>(Elt.getNode());
5520       LastLoadedElt = i;
5521       continue;
5522     }
5523     if (Elt.getOpcode() == ISD::UNDEF)
5524       continue;
5525
5526     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5527     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5528       return SDValue();
5529     LastLoadedElt = i;
5530   }
5531
5532   // If we have found an entire vector of loads and undefs, then return a large
5533   // load of the entire vector width starting at the base pointer.  If we found
5534   // consecutive loads for the low half, generate a vzext_load node.
5535   if (LastLoadedElt == NumElems - 1) {
5536
5537     if (isAfterLegalize &&
5538         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5539       return SDValue();
5540
5541     SDValue NewLd = SDValue();
5542
5543     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5544       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5545                           LDBase->getPointerInfo(),
5546                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5547                           LDBase->isInvariant(), 0);
5548     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5549                         LDBase->getPointerInfo(),
5550                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5551                         LDBase->isInvariant(), LDBase->getAlignment());
5552
5553     if (LDBase->hasAnyUseOfValue(1)) {
5554       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5555                                      SDValue(LDBase, 1),
5556                                      SDValue(NewLd.getNode(), 1));
5557       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5558       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5559                              SDValue(NewLd.getNode(), 1));
5560     }
5561
5562     return NewLd;
5563   }
5564   if (NumElems == 4 && LastLoadedElt == 1 &&
5565       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5566     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5567     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5568     SDValue ResNode =
5569         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5570                                 LDBase->getPointerInfo(),
5571                                 LDBase->getAlignment(),
5572                                 false/*isVolatile*/, true/*ReadMem*/,
5573                                 false/*WriteMem*/);
5574
5575     // Make sure the newly-created LOAD is in the same position as LDBase in
5576     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5577     // update uses of LDBase's output chain to use the TokenFactor.
5578     if (LDBase->hasAnyUseOfValue(1)) {
5579       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5580                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5581       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5582       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5583                              SDValue(ResNode.getNode(), 1));
5584     }
5585
5586     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5587   }
5588   return SDValue();
5589 }
5590
5591 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5592 /// to generate a splat value for the following cases:
5593 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5594 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5595 /// a scalar load, or a constant.
5596 /// The VBROADCAST node is returned when a pattern is found,
5597 /// or SDValue() otherwise.
5598 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5599                                     SelectionDAG &DAG) {
5600   if (!Subtarget->hasFp256())
5601     return SDValue();
5602
5603   MVT VT = Op.getSimpleValueType();
5604   SDLoc dl(Op);
5605
5606   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5607          "Unsupported vector type for broadcast.");
5608
5609   SDValue Ld;
5610   bool ConstSplatVal;
5611
5612   switch (Op.getOpcode()) {
5613     default:
5614       // Unknown pattern found.
5615       return SDValue();
5616
5617     case ISD::BUILD_VECTOR: {
5618       // The BUILD_VECTOR node must be a splat.
5619       if (!isSplatVector(Op.getNode()))
5620         return SDValue();
5621
5622       Ld = Op.getOperand(0);
5623       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5624                      Ld.getOpcode() == ISD::ConstantFP);
5625
5626       // The suspected load node has several users. Make sure that all
5627       // of its users are from the BUILD_VECTOR node.
5628       // Constants may have multiple users.
5629       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5630         return SDValue();
5631       break;
5632     }
5633
5634     case ISD::VECTOR_SHUFFLE: {
5635       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5636
5637       // Shuffles must have a splat mask where the first element is
5638       // broadcasted.
5639       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5640         return SDValue();
5641
5642       SDValue Sc = Op.getOperand(0);
5643       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5644           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5645
5646         if (!Subtarget->hasInt256())
5647           return SDValue();
5648
5649         // Use the register form of the broadcast instruction available on AVX2.
5650         if (VT.getSizeInBits() >= 256)
5651           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5652         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5653       }
5654
5655       Ld = Sc.getOperand(0);
5656       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5657                        Ld.getOpcode() == ISD::ConstantFP);
5658
5659       // The scalar_to_vector node and the suspected
5660       // load node must have exactly one user.
5661       // Constants may have multiple users.
5662
5663       // AVX-512 has register version of the broadcast
5664       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5665         Ld.getValueType().getSizeInBits() >= 32;
5666       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5667           !hasRegVer))
5668         return SDValue();
5669       break;
5670     }
5671   }
5672
5673   bool IsGE256 = (VT.getSizeInBits() >= 256);
5674
5675   // Handle the broadcasting a single constant scalar from the constant pool
5676   // into a vector. On Sandybridge it is still better to load a constant vector
5677   // from the constant pool and not to broadcast it from a scalar.
5678   if (ConstSplatVal && Subtarget->hasInt256()) {
5679     EVT CVT = Ld.getValueType();
5680     assert(!CVT.isVector() && "Must not broadcast a vector type");
5681     unsigned ScalarSize = CVT.getSizeInBits();
5682
5683     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5684       const Constant *C = nullptr;
5685       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5686         C = CI->getConstantIntValue();
5687       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5688         C = CF->getConstantFPValue();
5689
5690       assert(C && "Invalid constant type");
5691
5692       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5693       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5694       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5695       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5696                        MachinePointerInfo::getConstantPool(),
5697                        false, false, false, Alignment);
5698
5699       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5700     }
5701   }
5702
5703   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5704   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5705
5706   // Handle AVX2 in-register broadcasts.
5707   if (!IsLoad && Subtarget->hasInt256() &&
5708       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5709     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5710
5711   // The scalar source must be a normal load.
5712   if (!IsLoad)
5713     return SDValue();
5714
5715   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5716     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5717
5718   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5719   // double since there is no vbroadcastsd xmm
5720   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5721     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5722       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5723   }
5724
5725   // Unsupported broadcast.
5726   return SDValue();
5727 }
5728
5729 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5730 /// underlying vector and index.
5731 ///
5732 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5733 /// index.
5734 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5735                                          SDValue ExtIdx) {
5736   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5737   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5738     return Idx;
5739
5740   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5741   // lowered this:
5742   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5743   // to:
5744   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5745   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5746   //                           undef)
5747   //                       Constant<0>)
5748   // In this case the vector is the extract_subvector expression and the index
5749   // is 2, as specified by the shuffle.
5750   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5751   SDValue ShuffleVec = SVOp->getOperand(0);
5752   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5753   assert(ShuffleVecVT.getVectorElementType() ==
5754          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5755
5756   int ShuffleIdx = SVOp->getMaskElt(Idx);
5757   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5758     ExtractedFromVec = ShuffleVec;
5759     return ShuffleIdx;
5760   }
5761   return Idx;
5762 }
5763
5764 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5765   MVT VT = Op.getSimpleValueType();
5766
5767   // Skip if insert_vec_elt is not supported.
5768   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5769   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5770     return SDValue();
5771
5772   SDLoc DL(Op);
5773   unsigned NumElems = Op.getNumOperands();
5774
5775   SDValue VecIn1;
5776   SDValue VecIn2;
5777   SmallVector<unsigned, 4> InsertIndices;
5778   SmallVector<int, 8> Mask(NumElems, -1);
5779
5780   for (unsigned i = 0; i != NumElems; ++i) {
5781     unsigned Opc = Op.getOperand(i).getOpcode();
5782
5783     if (Opc == ISD::UNDEF)
5784       continue;
5785
5786     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5787       // Quit if more than 1 elements need inserting.
5788       if (InsertIndices.size() > 1)
5789         return SDValue();
5790
5791       InsertIndices.push_back(i);
5792       continue;
5793     }
5794
5795     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5796     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5797     // Quit if non-constant index.
5798     if (!isa<ConstantSDNode>(ExtIdx))
5799       return SDValue();
5800     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5801
5802     // Quit if extracted from vector of different type.
5803     if (ExtractedFromVec.getValueType() != VT)
5804       return SDValue();
5805
5806     if (!VecIn1.getNode())
5807       VecIn1 = ExtractedFromVec;
5808     else if (VecIn1 != ExtractedFromVec) {
5809       if (!VecIn2.getNode())
5810         VecIn2 = ExtractedFromVec;
5811       else if (VecIn2 != ExtractedFromVec)
5812         // Quit if more than 2 vectors to shuffle
5813         return SDValue();
5814     }
5815
5816     if (ExtractedFromVec == VecIn1)
5817       Mask[i] = Idx;
5818     else if (ExtractedFromVec == VecIn2)
5819       Mask[i] = Idx + NumElems;
5820   }
5821
5822   if (!VecIn1.getNode())
5823     return SDValue();
5824
5825   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5826   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5827   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5828     unsigned Idx = InsertIndices[i];
5829     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5830                      DAG.getIntPtrConstant(Idx));
5831   }
5832
5833   return NV;
5834 }
5835
5836 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5837 SDValue
5838 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5839
5840   MVT VT = Op.getSimpleValueType();
5841   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5842          "Unexpected type in LowerBUILD_VECTORvXi1!");
5843
5844   SDLoc dl(Op);
5845   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5846     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5847     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5848     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5849   }
5850
5851   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5852     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5853     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5854     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5855   }
5856
5857   bool AllContants = true;
5858   uint64_t Immediate = 0;
5859   int NonConstIdx = -1;
5860   bool IsSplat = true;
5861   unsigned NumNonConsts = 0;
5862   unsigned NumConsts = 0;
5863   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5864     SDValue In = Op.getOperand(idx);
5865     if (In.getOpcode() == ISD::UNDEF)
5866       continue;
5867     if (!isa<ConstantSDNode>(In)) {
5868       AllContants = false;
5869       NonConstIdx = idx;
5870       NumNonConsts++;
5871     }
5872     else {
5873       NumConsts++;
5874       if (cast<ConstantSDNode>(In)->getZExtValue())
5875       Immediate |= (1ULL << idx);
5876     }
5877     if (In != Op.getOperand(0))
5878       IsSplat = false;
5879   }
5880
5881   if (AllContants) {
5882     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5883       DAG.getConstant(Immediate, MVT::i16));
5884     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5885                        DAG.getIntPtrConstant(0));
5886   }
5887
5888   if (NumNonConsts == 1 && NonConstIdx != 0) {
5889     SDValue DstVec;
5890     if (NumConsts) {
5891       SDValue VecAsImm = DAG.getConstant(Immediate,
5892                                          MVT::getIntegerVT(VT.getSizeInBits()));
5893       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5894     }
5895     else 
5896       DstVec = DAG.getUNDEF(VT);
5897     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5898                        Op.getOperand(NonConstIdx),
5899                        DAG.getIntPtrConstant(NonConstIdx));
5900   }
5901   if (!IsSplat && (NonConstIdx != 0))
5902     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5903   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5904   SDValue Select;
5905   if (IsSplat)
5906     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5907                           DAG.getConstant(-1, SelectVT),
5908                           DAG.getConstant(0, SelectVT));
5909   else
5910     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5911                          DAG.getConstant((Immediate | 1), SelectVT),
5912                          DAG.getConstant(Immediate, SelectVT));
5913   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5914 }
5915
5916 SDValue
5917 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5918   SDLoc dl(Op);
5919
5920   MVT VT = Op.getSimpleValueType();
5921   MVT ExtVT = VT.getVectorElementType();
5922   unsigned NumElems = Op.getNumOperands();
5923
5924   // Generate vectors for predicate vectors.
5925   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5926     return LowerBUILD_VECTORvXi1(Op, DAG);
5927
5928   // Vectors containing all zeros can be matched by pxor and xorps later
5929   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5930     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5931     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5932     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5933       return Op;
5934
5935     return getZeroVector(VT, Subtarget, DAG, dl);
5936   }
5937
5938   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5939   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5940   // vpcmpeqd on 256-bit vectors.
5941   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5942     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5943       return Op;
5944
5945     if (!VT.is512BitVector())
5946       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5947   }
5948
5949   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5950   if (Broadcast.getNode())
5951     return Broadcast;
5952
5953   unsigned EVTBits = ExtVT.getSizeInBits();
5954
5955   unsigned NumZero  = 0;
5956   unsigned NumNonZero = 0;
5957   unsigned NonZeros = 0;
5958   bool IsAllConstants = true;
5959   SmallSet<SDValue, 8> Values;
5960   for (unsigned i = 0; i < NumElems; ++i) {
5961     SDValue Elt = Op.getOperand(i);
5962     if (Elt.getOpcode() == ISD::UNDEF)
5963       continue;
5964     Values.insert(Elt);
5965     if (Elt.getOpcode() != ISD::Constant &&
5966         Elt.getOpcode() != ISD::ConstantFP)
5967       IsAllConstants = false;
5968     if (X86::isZeroNode(Elt))
5969       NumZero++;
5970     else {
5971       NonZeros |= (1 << i);
5972       NumNonZero++;
5973     }
5974   }
5975
5976   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5977   if (NumNonZero == 0)
5978     return DAG.getUNDEF(VT);
5979
5980   // Special case for single non-zero, non-undef, element.
5981   if (NumNonZero == 1) {
5982     unsigned Idx = countTrailingZeros(NonZeros);
5983     SDValue Item = Op.getOperand(Idx);
5984
5985     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5986     // the value are obviously zero, truncate the value to i32 and do the
5987     // insertion that way.  Only do this if the value is non-constant or if the
5988     // value is a constant being inserted into element 0.  It is cheaper to do
5989     // a constant pool load than it is to do a movd + shuffle.
5990     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5991         (!IsAllConstants || Idx == 0)) {
5992       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5993         // Handle SSE only.
5994         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5995         EVT VecVT = MVT::v4i32;
5996         unsigned VecElts = 4;
5997
5998         // Truncate the value (which may itself be a constant) to i32, and
5999         // convert it to a vector with movd (S2V+shuffle to zero extend).
6000         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6001         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6002         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6003
6004         // Now we have our 32-bit value zero extended in the low element of
6005         // a vector.  If Idx != 0, swizzle it into place.
6006         if (Idx != 0) {
6007           SmallVector<int, 4> Mask;
6008           Mask.push_back(Idx);
6009           for (unsigned i = 1; i != VecElts; ++i)
6010             Mask.push_back(i);
6011           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6012                                       &Mask[0]);
6013         }
6014         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6015       }
6016     }
6017
6018     // If we have a constant or non-constant insertion into the low element of
6019     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6020     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6021     // depending on what the source datatype is.
6022     if (Idx == 0) {
6023       if (NumZero == 0)
6024         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6025
6026       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6027           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6028         if (VT.is256BitVector() || VT.is512BitVector()) {
6029           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6030           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6031                              Item, DAG.getIntPtrConstant(0));
6032         }
6033         assert(VT.is128BitVector() && "Expected an SSE value type!");
6034         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6035         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6036         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6037       }
6038
6039       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6040         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6041         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6042         if (VT.is256BitVector()) {
6043           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6044           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6045         } else {
6046           assert(VT.is128BitVector() && "Expected an SSE value type!");
6047           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6048         }
6049         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6050       }
6051     }
6052
6053     // Is it a vector logical left shift?
6054     if (NumElems == 2 && Idx == 1 &&
6055         X86::isZeroNode(Op.getOperand(0)) &&
6056         !X86::isZeroNode(Op.getOperand(1))) {
6057       unsigned NumBits = VT.getSizeInBits();
6058       return getVShift(true, VT,
6059                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6060                                    VT, Op.getOperand(1)),
6061                        NumBits/2, DAG, *this, dl);
6062     }
6063
6064     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6065       return SDValue();
6066
6067     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6068     // is a non-constant being inserted into an element other than the low one,
6069     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6070     // movd/movss) to move this into the low element, then shuffle it into
6071     // place.
6072     if (EVTBits == 32) {
6073       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6074
6075       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6076       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6077       SmallVector<int, 8> MaskVec;
6078       for (unsigned i = 0; i != NumElems; ++i)
6079         MaskVec.push_back(i == Idx ? 0 : 1);
6080       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6081     }
6082   }
6083
6084   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6085   if (Values.size() == 1) {
6086     if (EVTBits == 32) {
6087       // Instead of a shuffle like this:
6088       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6089       // Check if it's possible to issue this instead.
6090       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6091       unsigned Idx = countTrailingZeros(NonZeros);
6092       SDValue Item = Op.getOperand(Idx);
6093       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6094         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6095     }
6096     return SDValue();
6097   }
6098
6099   // A vector full of immediates; various special cases are already
6100   // handled, so this is best done with a single constant-pool load.
6101   if (IsAllConstants)
6102     return SDValue();
6103
6104   // For AVX-length vectors, build the individual 128-bit pieces and use
6105   // shuffles to put them in place.
6106   if (VT.is256BitVector() || VT.is512BitVector()) {
6107     SmallVector<SDValue, 64> V;
6108     for (unsigned i = 0; i != NumElems; ++i)
6109       V.push_back(Op.getOperand(i));
6110
6111     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6112
6113     // Build both the lower and upper subvector.
6114     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6115                                 ArrayRef<SDValue>(&V[0], NumElems/2));
6116     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6117                                 ArrayRef<SDValue>(&V[NumElems / 2],
6118                                                   NumElems/2));
6119
6120     // Recreate the wider vector with the lower and upper part.
6121     if (VT.is256BitVector())
6122       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6123     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6124   }
6125
6126   // Let legalizer expand 2-wide build_vectors.
6127   if (EVTBits == 64) {
6128     if (NumNonZero == 1) {
6129       // One half is zero or undef.
6130       unsigned Idx = countTrailingZeros(NonZeros);
6131       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6132                                  Op.getOperand(Idx));
6133       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6134     }
6135     return SDValue();
6136   }
6137
6138   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6139   if (EVTBits == 8 && NumElems == 16) {
6140     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6141                                         Subtarget, *this);
6142     if (V.getNode()) return V;
6143   }
6144
6145   if (EVTBits == 16 && NumElems == 8) {
6146     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6147                                       Subtarget, *this);
6148     if (V.getNode()) return V;
6149   }
6150
6151   // If element VT is == 32 bits, turn it into a number of shuffles.
6152   SmallVector<SDValue, 8> V(NumElems);
6153   if (NumElems == 4 && NumZero > 0) {
6154     for (unsigned i = 0; i < 4; ++i) {
6155       bool isZero = !(NonZeros & (1 << i));
6156       if (isZero)
6157         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6158       else
6159         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6160     }
6161
6162     for (unsigned i = 0; i < 2; ++i) {
6163       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6164         default: break;
6165         case 0:
6166           V[i] = V[i*2];  // Must be a zero vector.
6167           break;
6168         case 1:
6169           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6170           break;
6171         case 2:
6172           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6173           break;
6174         case 3:
6175           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6176           break;
6177       }
6178     }
6179
6180     bool Reverse1 = (NonZeros & 0x3) == 2;
6181     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6182     int MaskVec[] = {
6183       Reverse1 ? 1 : 0,
6184       Reverse1 ? 0 : 1,
6185       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6186       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6187     };
6188     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6189   }
6190
6191   if (Values.size() > 1 && VT.is128BitVector()) {
6192     // Check for a build vector of consecutive loads.
6193     for (unsigned i = 0; i < NumElems; ++i)
6194       V[i] = Op.getOperand(i);
6195
6196     // Check for elements which are consecutive loads.
6197     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6198     if (LD.getNode())
6199       return LD;
6200
6201     // Check for a build vector from mostly shuffle plus few inserting.
6202     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6203     if (Sh.getNode())
6204       return Sh;
6205
6206     // For SSE 4.1, use insertps to put the high elements into the low element.
6207     if (getSubtarget()->hasSSE41()) {
6208       SDValue Result;
6209       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6210         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6211       else
6212         Result = DAG.getUNDEF(VT);
6213
6214       for (unsigned i = 1; i < NumElems; ++i) {
6215         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6216         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6217                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6218       }
6219       return Result;
6220     }
6221
6222     // Otherwise, expand into a number of unpckl*, start by extending each of
6223     // our (non-undef) elements to the full vector width with the element in the
6224     // bottom slot of the vector (which generates no code for SSE).
6225     for (unsigned i = 0; i < NumElems; ++i) {
6226       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6227         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6228       else
6229         V[i] = DAG.getUNDEF(VT);
6230     }
6231
6232     // Next, we iteratively mix elements, e.g. for v4f32:
6233     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6234     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6235     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6236     unsigned EltStride = NumElems >> 1;
6237     while (EltStride != 0) {
6238       for (unsigned i = 0; i < EltStride; ++i) {
6239         // If V[i+EltStride] is undef and this is the first round of mixing,
6240         // then it is safe to just drop this shuffle: V[i] is already in the
6241         // right place, the one element (since it's the first round) being
6242         // inserted as undef can be dropped.  This isn't safe for successive
6243         // rounds because they will permute elements within both vectors.
6244         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6245             EltStride == NumElems/2)
6246           continue;
6247
6248         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6249       }
6250       EltStride >>= 1;
6251     }
6252     return V[0];
6253   }
6254   return SDValue();
6255 }
6256
6257 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6258 // to create 256-bit vectors from two other 128-bit ones.
6259 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6260   SDLoc dl(Op);
6261   MVT ResVT = Op.getSimpleValueType();
6262
6263   assert((ResVT.is256BitVector() ||
6264           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6265
6266   SDValue V1 = Op.getOperand(0);
6267   SDValue V2 = Op.getOperand(1);
6268   unsigned NumElems = ResVT.getVectorNumElements();
6269   if(ResVT.is256BitVector())
6270     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6271
6272   if (Op.getNumOperands() == 4) {
6273     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6274                                 ResVT.getVectorNumElements()/2);
6275     SDValue V3 = Op.getOperand(2);
6276     SDValue V4 = Op.getOperand(3);
6277     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6278       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6279   }
6280   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6281 }
6282
6283 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6284   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6285   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6286          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6287           Op.getNumOperands() == 4)));
6288
6289   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6290   // from two other 128-bit ones.
6291
6292   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6293   return LowerAVXCONCAT_VECTORS(Op, DAG);
6294 }
6295
6296 // Try to lower a shuffle node into a simple blend instruction.
6297 static SDValue
6298 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6299                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6300   SDValue V1 = SVOp->getOperand(0);
6301   SDValue V2 = SVOp->getOperand(1);
6302   SDLoc dl(SVOp);
6303   MVT VT = SVOp->getSimpleValueType(0);
6304   MVT EltVT = VT.getVectorElementType();
6305   unsigned NumElems = VT.getVectorNumElements();
6306
6307   // There is no blend with immediate in AVX-512.
6308   if (VT.is512BitVector())
6309     return SDValue();
6310
6311   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6312     return SDValue();
6313   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6314     return SDValue();
6315
6316   // Check the mask for BLEND and build the value.
6317   unsigned MaskValue = 0;
6318   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6319   unsigned NumLanes = (NumElems-1)/8 + 1;
6320   unsigned NumElemsInLane = NumElems / NumLanes;
6321
6322   // Blend for v16i16 should be symetric for the both lanes.
6323   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6324
6325     int SndLaneEltIdx = (NumLanes == 2) ?
6326       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6327     int EltIdx = SVOp->getMaskElt(i);
6328
6329     if ((EltIdx < 0 || EltIdx == (int)i) &&
6330         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6331       continue;
6332
6333     if (((unsigned)EltIdx == (i + NumElems)) &&
6334         (SndLaneEltIdx < 0 ||
6335          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6336       MaskValue |= (1<<i);
6337     else
6338       return SDValue();
6339   }
6340
6341   // Convert i32 vectors to floating point if it is not AVX2.
6342   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6343   MVT BlendVT = VT;
6344   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6345     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6346                                NumElems);
6347     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6348     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6349   }
6350
6351   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6352                             DAG.getConstant(MaskValue, MVT::i32));
6353   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6354 }
6355
6356 /// In vector type \p VT, return true if the element at index \p InputIdx
6357 /// falls on a different 128-bit lane than \p OutputIdx.
6358 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6359                                      unsigned OutputIdx) {
6360   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6361   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6362 }
6363
6364 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6365 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6366 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6367 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6368 /// zero.
6369 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6370                          SelectionDAG &DAG) {
6371   MVT VT = V1.getSimpleValueType();
6372   assert(VT.is128BitVector() || VT.is256BitVector());
6373
6374   MVT EltVT = VT.getVectorElementType();
6375   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6376   unsigned NumElts = VT.getVectorNumElements();
6377
6378   SmallVector<SDValue, 32> PshufbMask;
6379   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6380     int InputIdx = MaskVals[OutputIdx];
6381     unsigned InputByteIdx;
6382
6383     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6384       InputByteIdx = 0x80;
6385     else {
6386       // Cross lane is not allowed.
6387       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6388         return SDValue();
6389       InputByteIdx = InputIdx * EltSizeInBytes;
6390       // Index is an byte offset within the 128-bit lane.
6391       InputByteIdx &= 0xf;
6392     }
6393
6394     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6395       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6396       if (InputByteIdx != 0x80)
6397         ++InputByteIdx;
6398     }
6399   }
6400
6401   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6402   if (ShufVT != VT)
6403     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6404   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6405                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6406 }
6407
6408 // v8i16 shuffles - Prefer shuffles in the following order:
6409 // 1. [all]   pshuflw, pshufhw, optional move
6410 // 2. [ssse3] 1 x pshufb
6411 // 3. [ssse3] 2 x pshufb + 1 x por
6412 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6413 static SDValue
6414 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6415                          SelectionDAG &DAG) {
6416   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6417   SDValue V1 = SVOp->getOperand(0);
6418   SDValue V2 = SVOp->getOperand(1);
6419   SDLoc dl(SVOp);
6420   SmallVector<int, 8> MaskVals;
6421
6422   // Determine if more than 1 of the words in each of the low and high quadwords
6423   // of the result come from the same quadword of one of the two inputs.  Undef
6424   // mask values count as coming from any quadword, for better codegen.
6425   //
6426   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6427   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6428   unsigned LoQuad[] = { 0, 0, 0, 0 };
6429   unsigned HiQuad[] = { 0, 0, 0, 0 };
6430   // Indices of quads used.
6431   std::bitset<4> InputQuads;
6432   for (unsigned i = 0; i < 8; ++i) {
6433     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6434     int EltIdx = SVOp->getMaskElt(i);
6435     MaskVals.push_back(EltIdx);
6436     if (EltIdx < 0) {
6437       ++Quad[0];
6438       ++Quad[1];
6439       ++Quad[2];
6440       ++Quad[3];
6441       continue;
6442     }
6443     ++Quad[EltIdx / 4];
6444     InputQuads.set(EltIdx / 4);
6445   }
6446
6447   int BestLoQuad = -1;
6448   unsigned MaxQuad = 1;
6449   for (unsigned i = 0; i < 4; ++i) {
6450     if (LoQuad[i] > MaxQuad) {
6451       BestLoQuad = i;
6452       MaxQuad = LoQuad[i];
6453     }
6454   }
6455
6456   int BestHiQuad = -1;
6457   MaxQuad = 1;
6458   for (unsigned i = 0; i < 4; ++i) {
6459     if (HiQuad[i] > MaxQuad) {
6460       BestHiQuad = i;
6461       MaxQuad = HiQuad[i];
6462     }
6463   }
6464
6465   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6466   // of the two input vectors, shuffle them into one input vector so only a
6467   // single pshufb instruction is necessary. If there are more than 2 input
6468   // quads, disable the next transformation since it does not help SSSE3.
6469   bool V1Used = InputQuads[0] || InputQuads[1];
6470   bool V2Used = InputQuads[2] || InputQuads[3];
6471   if (Subtarget->hasSSSE3()) {
6472     if (InputQuads.count() == 2 && V1Used && V2Used) {
6473       BestLoQuad = InputQuads[0] ? 0 : 1;
6474       BestHiQuad = InputQuads[2] ? 2 : 3;
6475     }
6476     if (InputQuads.count() > 2) {
6477       BestLoQuad = -1;
6478       BestHiQuad = -1;
6479     }
6480   }
6481
6482   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6483   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6484   // words from all 4 input quadwords.
6485   SDValue NewV;
6486   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6487     int MaskV[] = {
6488       BestLoQuad < 0 ? 0 : BestLoQuad,
6489       BestHiQuad < 0 ? 1 : BestHiQuad
6490     };
6491     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6492                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6493                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6494     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6495
6496     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6497     // source words for the shuffle, to aid later transformations.
6498     bool AllWordsInNewV = true;
6499     bool InOrder[2] = { true, true };
6500     for (unsigned i = 0; i != 8; ++i) {
6501       int idx = MaskVals[i];
6502       if (idx != (int)i)
6503         InOrder[i/4] = false;
6504       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6505         continue;
6506       AllWordsInNewV = false;
6507       break;
6508     }
6509
6510     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6511     if (AllWordsInNewV) {
6512       for (int i = 0; i != 8; ++i) {
6513         int idx = MaskVals[i];
6514         if (idx < 0)
6515           continue;
6516         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6517         if ((idx != i) && idx < 4)
6518           pshufhw = false;
6519         if ((idx != i) && idx > 3)
6520           pshuflw = false;
6521       }
6522       V1 = NewV;
6523       V2Used = false;
6524       BestLoQuad = 0;
6525       BestHiQuad = 1;
6526     }
6527
6528     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6529     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6530     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6531       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6532       unsigned TargetMask = 0;
6533       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6534                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6535       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6536       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6537                              getShufflePSHUFLWImmediate(SVOp);
6538       V1 = NewV.getOperand(0);
6539       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6540     }
6541   }
6542
6543   // Promote splats to a larger type which usually leads to more efficient code.
6544   // FIXME: Is this true if pshufb is available?
6545   if (SVOp->isSplat())
6546     return PromoteSplat(SVOp, DAG);
6547
6548   // If we have SSSE3, and all words of the result are from 1 input vector,
6549   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6550   // is present, fall back to case 4.
6551   if (Subtarget->hasSSSE3()) {
6552     SmallVector<SDValue,16> pshufbMask;
6553
6554     // If we have elements from both input vectors, set the high bit of the
6555     // shuffle mask element to zero out elements that come from V2 in the V1
6556     // mask, and elements that come from V1 in the V2 mask, so that the two
6557     // results can be OR'd together.
6558     bool TwoInputs = V1Used && V2Used;
6559     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6560     if (!TwoInputs)
6561       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6562
6563     // Calculate the shuffle mask for the second input, shuffle it, and
6564     // OR it with the first shuffled input.
6565     CommuteVectorShuffleMask(MaskVals, 8);
6566     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6567     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6568     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6569   }
6570
6571   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6572   // and update MaskVals with new element order.
6573   std::bitset<8> InOrder;
6574   if (BestLoQuad >= 0) {
6575     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6576     for (int i = 0; i != 4; ++i) {
6577       int idx = MaskVals[i];
6578       if (idx < 0) {
6579         InOrder.set(i);
6580       } else if ((idx / 4) == BestLoQuad) {
6581         MaskV[i] = idx & 3;
6582         InOrder.set(i);
6583       }
6584     }
6585     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6586                                 &MaskV[0]);
6587
6588     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6589       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6590       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6591                                   NewV.getOperand(0),
6592                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6593     }
6594   }
6595
6596   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6597   // and update MaskVals with the new element order.
6598   if (BestHiQuad >= 0) {
6599     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6600     for (unsigned i = 4; i != 8; ++i) {
6601       int idx = MaskVals[i];
6602       if (idx < 0) {
6603         InOrder.set(i);
6604       } else if ((idx / 4) == BestHiQuad) {
6605         MaskV[i] = (idx & 3) + 4;
6606         InOrder.set(i);
6607       }
6608     }
6609     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6610                                 &MaskV[0]);
6611
6612     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6613       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6614       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6615                                   NewV.getOperand(0),
6616                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6617     }
6618   }
6619
6620   // In case BestHi & BestLo were both -1, which means each quadword has a word
6621   // from each of the four input quadwords, calculate the InOrder bitvector now
6622   // before falling through to the insert/extract cleanup.
6623   if (BestLoQuad == -1 && BestHiQuad == -1) {
6624     NewV = V1;
6625     for (int i = 0; i != 8; ++i)
6626       if (MaskVals[i] < 0 || MaskVals[i] == i)
6627         InOrder.set(i);
6628   }
6629
6630   // The other elements are put in the right place using pextrw and pinsrw.
6631   for (unsigned i = 0; i != 8; ++i) {
6632     if (InOrder[i])
6633       continue;
6634     int EltIdx = MaskVals[i];
6635     if (EltIdx < 0)
6636       continue;
6637     SDValue ExtOp = (EltIdx < 8) ?
6638       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6639                   DAG.getIntPtrConstant(EltIdx)) :
6640       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6641                   DAG.getIntPtrConstant(EltIdx - 8));
6642     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6643                        DAG.getIntPtrConstant(i));
6644   }
6645   return NewV;
6646 }
6647
6648 /// \brief v16i16 shuffles
6649 ///
6650 /// FIXME: We only support generation of a single pshufb currently.  We can
6651 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6652 /// well (e.g 2 x pshufb + 1 x por).
6653 static SDValue
6654 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6655   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6656   SDValue V1 = SVOp->getOperand(0);
6657   SDValue V2 = SVOp->getOperand(1);
6658   SDLoc dl(SVOp);
6659
6660   if (V2.getOpcode() != ISD::UNDEF)
6661     return SDValue();
6662
6663   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6664   return getPSHUFB(MaskVals, V1, dl, DAG);
6665 }
6666
6667 // v16i8 shuffles - Prefer shuffles in the following order:
6668 // 1. [ssse3] 1 x pshufb
6669 // 2. [ssse3] 2 x pshufb + 1 x por
6670 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6671 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6672                                         const X86Subtarget* Subtarget,
6673                                         SelectionDAG &DAG) {
6674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6675   SDValue V1 = SVOp->getOperand(0);
6676   SDValue V2 = SVOp->getOperand(1);
6677   SDLoc dl(SVOp);
6678   ArrayRef<int> MaskVals = SVOp->getMask();
6679
6680   // Promote splats to a larger type which usually leads to more efficient code.
6681   // FIXME: Is this true if pshufb is available?
6682   if (SVOp->isSplat())
6683     return PromoteSplat(SVOp, DAG);
6684
6685   // If we have SSSE3, case 1 is generated when all result bytes come from
6686   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6687   // present, fall back to case 3.
6688
6689   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6690   if (Subtarget->hasSSSE3()) {
6691     SmallVector<SDValue,16> pshufbMask;
6692
6693     // If all result elements are from one input vector, then only translate
6694     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6695     //
6696     // Otherwise, we have elements from both input vectors, and must zero out
6697     // elements that come from V2 in the first mask, and V1 in the second mask
6698     // so that we can OR them together.
6699     for (unsigned i = 0; i != 16; ++i) {
6700       int EltIdx = MaskVals[i];
6701       if (EltIdx < 0 || EltIdx >= 16)
6702         EltIdx = 0x80;
6703       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6704     }
6705     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6706                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6707                                  MVT::v16i8, pshufbMask));
6708
6709     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6710     // the 2nd operand if it's undefined or zero.
6711     if (V2.getOpcode() == ISD::UNDEF ||
6712         ISD::isBuildVectorAllZeros(V2.getNode()))
6713       return V1;
6714
6715     // Calculate the shuffle mask for the second input, shuffle it, and
6716     // OR it with the first shuffled input.
6717     pshufbMask.clear();
6718     for (unsigned i = 0; i != 16; ++i) {
6719       int EltIdx = MaskVals[i];
6720       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6721       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6722     }
6723     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6724                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6725                                  MVT::v16i8, pshufbMask));
6726     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6727   }
6728
6729   // No SSSE3 - Calculate in place words and then fix all out of place words
6730   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6731   // the 16 different words that comprise the two doublequadword input vectors.
6732   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6733   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6734   SDValue NewV = V1;
6735   for (int i = 0; i != 8; ++i) {
6736     int Elt0 = MaskVals[i*2];
6737     int Elt1 = MaskVals[i*2+1];
6738
6739     // This word of the result is all undef, skip it.
6740     if (Elt0 < 0 && Elt1 < 0)
6741       continue;
6742
6743     // This word of the result is already in the correct place, skip it.
6744     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6745       continue;
6746
6747     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6748     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6749     SDValue InsElt;
6750
6751     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6752     // using a single extract together, load it and store it.
6753     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6754       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6755                            DAG.getIntPtrConstant(Elt1 / 2));
6756       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6757                         DAG.getIntPtrConstant(i));
6758       continue;
6759     }
6760
6761     // If Elt1 is defined, extract it from the appropriate source.  If the
6762     // source byte is not also odd, shift the extracted word left 8 bits
6763     // otherwise clear the bottom 8 bits if we need to do an or.
6764     if (Elt1 >= 0) {
6765       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6766                            DAG.getIntPtrConstant(Elt1 / 2));
6767       if ((Elt1 & 1) == 0)
6768         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6769                              DAG.getConstant(8,
6770                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6771       else if (Elt0 >= 0)
6772         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6773                              DAG.getConstant(0xFF00, MVT::i16));
6774     }
6775     // If Elt0 is defined, extract it from the appropriate source.  If the
6776     // source byte is not also even, shift the extracted word right 8 bits. If
6777     // Elt1 was also defined, OR the extracted values together before
6778     // inserting them in the result.
6779     if (Elt0 >= 0) {
6780       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6781                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6782       if ((Elt0 & 1) != 0)
6783         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6784                               DAG.getConstant(8,
6785                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6786       else if (Elt1 >= 0)
6787         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6788                              DAG.getConstant(0x00FF, MVT::i16));
6789       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6790                          : InsElt0;
6791     }
6792     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6793                        DAG.getIntPtrConstant(i));
6794   }
6795   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6796 }
6797
6798 // v32i8 shuffles - Translate to VPSHUFB if possible.
6799 static
6800 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6801                                  const X86Subtarget *Subtarget,
6802                                  SelectionDAG &DAG) {
6803   MVT VT = SVOp->getSimpleValueType(0);
6804   SDValue V1 = SVOp->getOperand(0);
6805   SDValue V2 = SVOp->getOperand(1);
6806   SDLoc dl(SVOp);
6807   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6808
6809   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6810   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6811   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6812
6813   // VPSHUFB may be generated if
6814   // (1) one of input vector is undefined or zeroinitializer.
6815   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6816   // And (2) the mask indexes don't cross the 128-bit lane.
6817   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6818       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6819     return SDValue();
6820
6821   if (V1IsAllZero && !V2IsAllZero) {
6822     CommuteVectorShuffleMask(MaskVals, 32);
6823     V1 = V2;
6824   }
6825   return getPSHUFB(MaskVals, V1, dl, DAG);
6826 }
6827
6828 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6829 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6830 /// done when every pair / quad of shuffle mask elements point to elements in
6831 /// the right sequence. e.g.
6832 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6833 static
6834 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6835                                  SelectionDAG &DAG) {
6836   MVT VT = SVOp->getSimpleValueType(0);
6837   SDLoc dl(SVOp);
6838   unsigned NumElems = VT.getVectorNumElements();
6839   MVT NewVT;
6840   unsigned Scale;
6841   switch (VT.SimpleTy) {
6842   default: llvm_unreachable("Unexpected!");
6843   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6844   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6845   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6846   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6847   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6848   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6849   }
6850
6851   SmallVector<int, 8> MaskVec;
6852   for (unsigned i = 0; i != NumElems; i += Scale) {
6853     int StartIdx = -1;
6854     for (unsigned j = 0; j != Scale; ++j) {
6855       int EltIdx = SVOp->getMaskElt(i+j);
6856       if (EltIdx < 0)
6857         continue;
6858       if (StartIdx < 0)
6859         StartIdx = (EltIdx / Scale);
6860       if (EltIdx != (int)(StartIdx*Scale + j))
6861         return SDValue();
6862     }
6863     MaskVec.push_back(StartIdx);
6864   }
6865
6866   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6867   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6868   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6869 }
6870
6871 /// getVZextMovL - Return a zero-extending vector move low node.
6872 ///
6873 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6874                             SDValue SrcOp, SelectionDAG &DAG,
6875                             const X86Subtarget *Subtarget, SDLoc dl) {
6876   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6877     LoadSDNode *LD = nullptr;
6878     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6879       LD = dyn_cast<LoadSDNode>(SrcOp);
6880     if (!LD) {
6881       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6882       // instead.
6883       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6884       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6885           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6886           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6887           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6888         // PR2108
6889         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6890         return DAG.getNode(ISD::BITCAST, dl, VT,
6891                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6892                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6893                                                    OpVT,
6894                                                    SrcOp.getOperand(0)
6895                                                           .getOperand(0))));
6896       }
6897     }
6898   }
6899
6900   return DAG.getNode(ISD::BITCAST, dl, VT,
6901                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6902                                  DAG.getNode(ISD::BITCAST, dl,
6903                                              OpVT, SrcOp)));
6904 }
6905
6906 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6907 /// which could not be matched by any known target speficic shuffle
6908 static SDValue
6909 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6910
6911   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6912   if (NewOp.getNode())
6913     return NewOp;
6914
6915   MVT VT = SVOp->getSimpleValueType(0);
6916
6917   unsigned NumElems = VT.getVectorNumElements();
6918   unsigned NumLaneElems = NumElems / 2;
6919
6920   SDLoc dl(SVOp);
6921   MVT EltVT = VT.getVectorElementType();
6922   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6923   SDValue Output[2];
6924
6925   SmallVector<int, 16> Mask;
6926   for (unsigned l = 0; l < 2; ++l) {
6927     // Build a shuffle mask for the output, discovering on the fly which
6928     // input vectors to use as shuffle operands (recorded in InputUsed).
6929     // If building a suitable shuffle vector proves too hard, then bail
6930     // out with UseBuildVector set.
6931     bool UseBuildVector = false;
6932     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6933     unsigned LaneStart = l * NumLaneElems;
6934     for (unsigned i = 0; i != NumLaneElems; ++i) {
6935       // The mask element.  This indexes into the input.
6936       int Idx = SVOp->getMaskElt(i+LaneStart);
6937       if (Idx < 0) {
6938         // the mask element does not index into any input vector.
6939         Mask.push_back(-1);
6940         continue;
6941       }
6942
6943       // The input vector this mask element indexes into.
6944       int Input = Idx / NumLaneElems;
6945
6946       // Turn the index into an offset from the start of the input vector.
6947       Idx -= Input * NumLaneElems;
6948
6949       // Find or create a shuffle vector operand to hold this input.
6950       unsigned OpNo;
6951       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6952         if (InputUsed[OpNo] == Input)
6953           // This input vector is already an operand.
6954           break;
6955         if (InputUsed[OpNo] < 0) {
6956           // Create a new operand for this input vector.
6957           InputUsed[OpNo] = Input;
6958           break;
6959         }
6960       }
6961
6962       if (OpNo >= array_lengthof(InputUsed)) {
6963         // More than two input vectors used!  Give up on trying to create a
6964         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6965         UseBuildVector = true;
6966         break;
6967       }
6968
6969       // Add the mask index for the new shuffle vector.
6970       Mask.push_back(Idx + OpNo * NumLaneElems);
6971     }
6972
6973     if (UseBuildVector) {
6974       SmallVector<SDValue, 16> SVOps;
6975       for (unsigned i = 0; i != NumLaneElems; ++i) {
6976         // The mask element.  This indexes into the input.
6977         int Idx = SVOp->getMaskElt(i+LaneStart);
6978         if (Idx < 0) {
6979           SVOps.push_back(DAG.getUNDEF(EltVT));
6980           continue;
6981         }
6982
6983         // The input vector this mask element indexes into.
6984         int Input = Idx / NumElems;
6985
6986         // Turn the index into an offset from the start of the input vector.
6987         Idx -= Input * NumElems;
6988
6989         // Extract the vector element by hand.
6990         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6991                                     SVOp->getOperand(Input),
6992                                     DAG.getIntPtrConstant(Idx)));
6993       }
6994
6995       // Construct the output using a BUILD_VECTOR.
6996       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
6997     } else if (InputUsed[0] < 0) {
6998       // No input vectors were used! The result is undefined.
6999       Output[l] = DAG.getUNDEF(NVT);
7000     } else {
7001       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7002                                         (InputUsed[0] % 2) * NumLaneElems,
7003                                         DAG, dl);
7004       // If only one input was used, use an undefined vector for the other.
7005       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7006         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7007                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7008       // At least one input vector was used. Create a new shuffle vector.
7009       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7010     }
7011
7012     Mask.clear();
7013   }
7014
7015   // Concatenate the result back
7016   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7017 }
7018
7019 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7020 /// 4 elements, and match them with several different shuffle types.
7021 static SDValue
7022 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7023   SDValue V1 = SVOp->getOperand(0);
7024   SDValue V2 = SVOp->getOperand(1);
7025   SDLoc dl(SVOp);
7026   MVT VT = SVOp->getSimpleValueType(0);
7027
7028   assert(VT.is128BitVector() && "Unsupported vector size");
7029
7030   std::pair<int, int> Locs[4];
7031   int Mask1[] = { -1, -1, -1, -1 };
7032   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7033
7034   unsigned NumHi = 0;
7035   unsigned NumLo = 0;
7036   for (unsigned i = 0; i != 4; ++i) {
7037     int Idx = PermMask[i];
7038     if (Idx < 0) {
7039       Locs[i] = std::make_pair(-1, -1);
7040     } else {
7041       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7042       if (Idx < 4) {
7043         Locs[i] = std::make_pair(0, NumLo);
7044         Mask1[NumLo] = Idx;
7045         NumLo++;
7046       } else {
7047         Locs[i] = std::make_pair(1, NumHi);
7048         if (2+NumHi < 4)
7049           Mask1[2+NumHi] = Idx;
7050         NumHi++;
7051       }
7052     }
7053   }
7054
7055   if (NumLo <= 2 && NumHi <= 2) {
7056     // If no more than two elements come from either vector. This can be
7057     // implemented with two shuffles. First shuffle gather the elements.
7058     // The second shuffle, which takes the first shuffle as both of its
7059     // vector operands, put the elements into the right order.
7060     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7061
7062     int Mask2[] = { -1, -1, -1, -1 };
7063
7064     for (unsigned i = 0; i != 4; ++i)
7065       if (Locs[i].first != -1) {
7066         unsigned Idx = (i < 2) ? 0 : 4;
7067         Idx += Locs[i].first * 2 + Locs[i].second;
7068         Mask2[i] = Idx;
7069       }
7070
7071     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7072   }
7073
7074   if (NumLo == 3 || NumHi == 3) {
7075     // Otherwise, we must have three elements from one vector, call it X, and
7076     // one element from the other, call it Y.  First, use a shufps to build an
7077     // intermediate vector with the one element from Y and the element from X
7078     // that will be in the same half in the final destination (the indexes don't
7079     // matter). Then, use a shufps to build the final vector, taking the half
7080     // containing the element from Y from the intermediate, and the other half
7081     // from X.
7082     if (NumHi == 3) {
7083       // Normalize it so the 3 elements come from V1.
7084       CommuteVectorShuffleMask(PermMask, 4);
7085       std::swap(V1, V2);
7086     }
7087
7088     // Find the element from V2.
7089     unsigned HiIndex;
7090     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7091       int Val = PermMask[HiIndex];
7092       if (Val < 0)
7093         continue;
7094       if (Val >= 4)
7095         break;
7096     }
7097
7098     Mask1[0] = PermMask[HiIndex];
7099     Mask1[1] = -1;
7100     Mask1[2] = PermMask[HiIndex^1];
7101     Mask1[3] = -1;
7102     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7103
7104     if (HiIndex >= 2) {
7105       Mask1[0] = PermMask[0];
7106       Mask1[1] = PermMask[1];
7107       Mask1[2] = HiIndex & 1 ? 6 : 4;
7108       Mask1[3] = HiIndex & 1 ? 4 : 6;
7109       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7110     }
7111
7112     Mask1[0] = HiIndex & 1 ? 2 : 0;
7113     Mask1[1] = HiIndex & 1 ? 0 : 2;
7114     Mask1[2] = PermMask[2];
7115     Mask1[3] = PermMask[3];
7116     if (Mask1[2] >= 0)
7117       Mask1[2] += 4;
7118     if (Mask1[3] >= 0)
7119       Mask1[3] += 4;
7120     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7121   }
7122
7123   // Break it into (shuffle shuffle_hi, shuffle_lo).
7124   int LoMask[] = { -1, -1, -1, -1 };
7125   int HiMask[] = { -1, -1, -1, -1 };
7126
7127   int *MaskPtr = LoMask;
7128   unsigned MaskIdx = 0;
7129   unsigned LoIdx = 0;
7130   unsigned HiIdx = 2;
7131   for (unsigned i = 0; i != 4; ++i) {
7132     if (i == 2) {
7133       MaskPtr = HiMask;
7134       MaskIdx = 1;
7135       LoIdx = 0;
7136       HiIdx = 2;
7137     }
7138     int Idx = PermMask[i];
7139     if (Idx < 0) {
7140       Locs[i] = std::make_pair(-1, -1);
7141     } else if (Idx < 4) {
7142       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7143       MaskPtr[LoIdx] = Idx;
7144       LoIdx++;
7145     } else {
7146       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7147       MaskPtr[HiIdx] = Idx;
7148       HiIdx++;
7149     }
7150   }
7151
7152   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7153   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7154   int MaskOps[] = { -1, -1, -1, -1 };
7155   for (unsigned i = 0; i != 4; ++i)
7156     if (Locs[i].first != -1)
7157       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7158   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7159 }
7160
7161 static bool MayFoldVectorLoad(SDValue V) {
7162   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7163     V = V.getOperand(0);
7164
7165   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7166     V = V.getOperand(0);
7167   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7168       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7169     // BUILD_VECTOR (load), undef
7170     V = V.getOperand(0);
7171
7172   return MayFoldLoad(V);
7173 }
7174
7175 static
7176 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7177   MVT VT = Op.getSimpleValueType();
7178
7179   // Canonizalize to v2f64.
7180   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7181   return DAG.getNode(ISD::BITCAST, dl, VT,
7182                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7183                                           V1, DAG));
7184 }
7185
7186 static
7187 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7188                         bool HasSSE2) {
7189   SDValue V1 = Op.getOperand(0);
7190   SDValue V2 = Op.getOperand(1);
7191   MVT VT = Op.getSimpleValueType();
7192
7193   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7194
7195   if (HasSSE2 && VT == MVT::v2f64)
7196     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7197
7198   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7199   return DAG.getNode(ISD::BITCAST, dl, VT,
7200                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7201                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7202                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7203 }
7204
7205 static
7206 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7207   SDValue V1 = Op.getOperand(0);
7208   SDValue V2 = Op.getOperand(1);
7209   MVT VT = Op.getSimpleValueType();
7210
7211   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7212          "unsupported shuffle type");
7213
7214   if (V2.getOpcode() == ISD::UNDEF)
7215     V2 = V1;
7216
7217   // v4i32 or v4f32
7218   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7219 }
7220
7221 static
7222 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7223   SDValue V1 = Op.getOperand(0);
7224   SDValue V2 = Op.getOperand(1);
7225   MVT VT = Op.getSimpleValueType();
7226   unsigned NumElems = VT.getVectorNumElements();
7227
7228   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7229   // operand of these instructions is only memory, so check if there's a
7230   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7231   // same masks.
7232   bool CanFoldLoad = false;
7233
7234   // Trivial case, when V2 comes from a load.
7235   if (MayFoldVectorLoad(V2))
7236     CanFoldLoad = true;
7237
7238   // When V1 is a load, it can be folded later into a store in isel, example:
7239   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7240   //    turns into:
7241   //  (MOVLPSmr addr:$src1, VR128:$src2)
7242   // So, recognize this potential and also use MOVLPS or MOVLPD
7243   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7244     CanFoldLoad = true;
7245
7246   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7247   if (CanFoldLoad) {
7248     if (HasSSE2 && NumElems == 2)
7249       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7250
7251     if (NumElems == 4)
7252       // If we don't care about the second element, proceed to use movss.
7253       if (SVOp->getMaskElt(1) != -1)
7254         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7255   }
7256
7257   // movl and movlp will both match v2i64, but v2i64 is never matched by
7258   // movl earlier because we make it strict to avoid messing with the movlp load
7259   // folding logic (see the code above getMOVLP call). Match it here then,
7260   // this is horrible, but will stay like this until we move all shuffle
7261   // matching to x86 specific nodes. Note that for the 1st condition all
7262   // types are matched with movsd.
7263   if (HasSSE2) {
7264     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7265     // as to remove this logic from here, as much as possible
7266     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7267       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7268     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7269   }
7270
7271   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7272
7273   // Invert the operand order and use SHUFPS to match it.
7274   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7275                               getShuffleSHUFImmediate(SVOp), DAG);
7276 }
7277
7278 // It is only safe to call this function if isINSERTPSMask is true for
7279 // this shufflevector mask.
7280 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7281                            SelectionDAG &DAG) {
7282   // Generate an insertps instruction when inserting an f32 from memory onto a
7283   // v4f32 or when copying a member from one v4f32 to another.
7284   // We also use it for transferring i32 from one register to another,
7285   // since it simply copies the same bits.
7286   // If we're transfering an i32 from memory to a specific element in a
7287   // register, we output a generic DAG that will match the PINSRD
7288   // instruction.
7289   // TODO: Optimize for AVX cases too (VINSERTPS)
7290   MVT VT = SVOp->getSimpleValueType(0);
7291   MVT EVT = VT.getVectorElementType();
7292   SDValue V1 = SVOp->getOperand(0);
7293   SDValue V2 = SVOp->getOperand(1);
7294   auto Mask = SVOp->getMask();
7295   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7296          "unsupported vector type for insertps/pinsrd");
7297
7298   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7299                              [](const int &i) { return i < 4; });
7300
7301   SDValue From;
7302   SDValue To;
7303   unsigned DestIndex;
7304   if (FromV1 == 1) {
7305     From = V1;
7306     To = V2;
7307     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7308                              [](const int &i) { return i < 4; }) -
7309                 Mask.begin();
7310   } else {
7311     From = V2;
7312     To = V1;
7313     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7314                              [](const int &i) { return i >= 4; }) -
7315                 Mask.begin();
7316   }
7317
7318   if (MayFoldLoad(From)) {
7319     // Trivial case, when From comes from a load and is only used by the
7320     // shuffle. Make it use insertps from the vector that we need from that
7321     // load.
7322     SDValue Addr = From.getOperand(1);
7323     SDValue NewAddr =
7324         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7325                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7326                                     Addr.getSimpleValueType()));
7327
7328     LoadSDNode *Load = cast<LoadSDNode>(From);
7329     SDValue NewLoad =
7330         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7331                     DAG.getMachineFunction().getMachineMemOperand(
7332                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7333
7334     if (EVT == MVT::f32) {
7335       // Create this as a scalar to vector to match the instruction pattern.
7336       SDValue LoadScalarToVector =
7337           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7338       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7339       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7340                          InsertpsMask);
7341     } else { // EVT == MVT::i32
7342       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7343       // instruction, to match the PINSRD instruction, which loads an i32 to a
7344       // certain vector element.
7345       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7346                          DAG.getConstant(DestIndex, MVT::i32));
7347     }
7348   }
7349
7350   // Vector-element-to-vector
7351   unsigned SrcIndex = Mask[DestIndex] % 4;
7352   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7353   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7354 }
7355
7356 // Reduce a vector shuffle to zext.
7357 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7358                                     SelectionDAG &DAG) {
7359   // PMOVZX is only available from SSE41.
7360   if (!Subtarget->hasSSE41())
7361     return SDValue();
7362
7363   MVT VT = Op.getSimpleValueType();
7364
7365   // Only AVX2 support 256-bit vector integer extending.
7366   if (!Subtarget->hasInt256() && VT.is256BitVector())
7367     return SDValue();
7368
7369   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7370   SDLoc DL(Op);
7371   SDValue V1 = Op.getOperand(0);
7372   SDValue V2 = Op.getOperand(1);
7373   unsigned NumElems = VT.getVectorNumElements();
7374
7375   // Extending is an unary operation and the element type of the source vector
7376   // won't be equal to or larger than i64.
7377   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7378       VT.getVectorElementType() == MVT::i64)
7379     return SDValue();
7380
7381   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7382   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7383   while ((1U << Shift) < NumElems) {
7384     if (SVOp->getMaskElt(1U << Shift) == 1)
7385       break;
7386     Shift += 1;
7387     // The maximal ratio is 8, i.e. from i8 to i64.
7388     if (Shift > 3)
7389       return SDValue();
7390   }
7391
7392   // Check the shuffle mask.
7393   unsigned Mask = (1U << Shift) - 1;
7394   for (unsigned i = 0; i != NumElems; ++i) {
7395     int EltIdx = SVOp->getMaskElt(i);
7396     if ((i & Mask) != 0 && EltIdx != -1)
7397       return SDValue();
7398     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7399       return SDValue();
7400   }
7401
7402   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7403   MVT NeVT = MVT::getIntegerVT(NBits);
7404   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7405
7406   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7407     return SDValue();
7408
7409   // Simplify the operand as it's prepared to be fed into shuffle.
7410   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7411   if (V1.getOpcode() == ISD::BITCAST &&
7412       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7413       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7414       V1.getOperand(0).getOperand(0)
7415         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7416     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7417     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7418     ConstantSDNode *CIdx =
7419       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7420     // If it's foldable, i.e. normal load with single use, we will let code
7421     // selection to fold it. Otherwise, we will short the conversion sequence.
7422     if (CIdx && CIdx->getZExtValue() == 0 &&
7423         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7424       MVT FullVT = V.getSimpleValueType();
7425       MVT V1VT = V1.getSimpleValueType();
7426       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7427         // The "ext_vec_elt" node is wider than the result node.
7428         // In this case we should extract subvector from V.
7429         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7430         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7431         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7432                                         FullVT.getVectorNumElements()/Ratio);
7433         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7434                         DAG.getIntPtrConstant(0));
7435       }
7436       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7437     }
7438   }
7439
7440   return DAG.getNode(ISD::BITCAST, DL, VT,
7441                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7442 }
7443
7444 static SDValue
7445 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7446                        SelectionDAG &DAG) {
7447   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7448   MVT VT = Op.getSimpleValueType();
7449   SDLoc dl(Op);
7450   SDValue V1 = Op.getOperand(0);
7451   SDValue V2 = Op.getOperand(1);
7452
7453   if (isZeroShuffle(SVOp))
7454     return getZeroVector(VT, Subtarget, DAG, dl);
7455
7456   // Handle splat operations
7457   if (SVOp->isSplat()) {
7458     // Use vbroadcast whenever the splat comes from a foldable load
7459     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7460     if (Broadcast.getNode())
7461       return Broadcast;
7462   }
7463
7464   // Check integer expanding shuffles.
7465   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7466   if (NewOp.getNode())
7467     return NewOp;
7468
7469   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7470   // do it!
7471   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7472       VT == MVT::v16i16 || VT == MVT::v32i8) {
7473     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7474     if (NewOp.getNode())
7475       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7476   } else if ((VT == MVT::v4i32 ||
7477              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7478     // FIXME: Figure out a cleaner way to do this.
7479     // Try to make use of movq to zero out the top part.
7480     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7481       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7482       if (NewOp.getNode()) {
7483         MVT NewVT = NewOp.getSimpleValueType();
7484         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7485                                NewVT, true, false))
7486           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7487                               DAG, Subtarget, dl);
7488       }
7489     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7490       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7491       if (NewOp.getNode()) {
7492         MVT NewVT = NewOp.getSimpleValueType();
7493         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7494           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7495                               DAG, Subtarget, dl);
7496       }
7497     }
7498   }
7499   return SDValue();
7500 }
7501
7502 SDValue
7503 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7504   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7505   SDValue V1 = Op.getOperand(0);
7506   SDValue V2 = Op.getOperand(1);
7507   MVT VT = Op.getSimpleValueType();
7508   SDLoc dl(Op);
7509   unsigned NumElems = VT.getVectorNumElements();
7510   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7511   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7512   bool V1IsSplat = false;
7513   bool V2IsSplat = false;
7514   bool HasSSE2 = Subtarget->hasSSE2();
7515   bool HasFp256    = Subtarget->hasFp256();
7516   bool HasInt256   = Subtarget->hasInt256();
7517   MachineFunction &MF = DAG.getMachineFunction();
7518   bool OptForSize = MF.getFunction()->getAttributes().
7519     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7520
7521   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7522
7523   if (V1IsUndef && V2IsUndef)
7524     return DAG.getUNDEF(VT);
7525
7526   // When we create a shuffle node we put the UNDEF node to second operand,
7527   // but in some cases the first operand may be transformed to UNDEF.
7528   // In this case we should just commute the node.
7529   if (V1IsUndef)
7530     return CommuteVectorShuffle(SVOp, DAG);
7531
7532   // Vector shuffle lowering takes 3 steps:
7533   //
7534   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7535   //    narrowing and commutation of operands should be handled.
7536   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7537   //    shuffle nodes.
7538   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7539   //    so the shuffle can be broken into other shuffles and the legalizer can
7540   //    try the lowering again.
7541   //
7542   // The general idea is that no vector_shuffle operation should be left to
7543   // be matched during isel, all of them must be converted to a target specific
7544   // node here.
7545
7546   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7547   // narrowing and commutation of operands should be handled. The actual code
7548   // doesn't include all of those, work in progress...
7549   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7550   if (NewOp.getNode())
7551     return NewOp;
7552
7553   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7554
7555   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7556   // unpckh_undef). Only use pshufd if speed is more important than size.
7557   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7558     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7559   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7560     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7561
7562   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7563       V2IsUndef && MayFoldVectorLoad(V1))
7564     return getMOVDDup(Op, dl, V1, DAG);
7565
7566   if (isMOVHLPS_v_undef_Mask(M, VT))
7567     return getMOVHighToLow(Op, dl, DAG);
7568
7569   // Use to match splats
7570   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7571       (VT == MVT::v2f64 || VT == MVT::v2i64))
7572     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7573
7574   if (isPSHUFDMask(M, VT)) {
7575     // The actual implementation will match the mask in the if above and then
7576     // during isel it can match several different instructions, not only pshufd
7577     // as its name says, sad but true, emulate the behavior for now...
7578     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7579       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7580
7581     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7582
7583     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7584       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7585
7586     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7587       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7588                                   DAG);
7589
7590     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7591                                 TargetMask, DAG);
7592   }
7593
7594   if (isPALIGNRMask(M, VT, Subtarget))
7595     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7596                                 getShufflePALIGNRImmediate(SVOp),
7597                                 DAG);
7598
7599   // Check if this can be converted into a logical shift.
7600   bool isLeft = false;
7601   unsigned ShAmt = 0;
7602   SDValue ShVal;
7603   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7604   if (isShift && ShVal.hasOneUse()) {
7605     // If the shifted value has multiple uses, it may be cheaper to use
7606     // v_set0 + movlhps or movhlps, etc.
7607     MVT EltVT = VT.getVectorElementType();
7608     ShAmt *= EltVT.getSizeInBits();
7609     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7610   }
7611
7612   if (isMOVLMask(M, VT)) {
7613     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7614       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7615     if (!isMOVLPMask(M, VT)) {
7616       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7617         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7618
7619       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7620         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7621     }
7622   }
7623
7624   // FIXME: fold these into legal mask.
7625   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7626     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7627
7628   if (isMOVHLPSMask(M, VT))
7629     return getMOVHighToLow(Op, dl, DAG);
7630
7631   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7632     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7633
7634   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7635     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7636
7637   if (isMOVLPMask(M, VT))
7638     return getMOVLP(Op, dl, DAG, HasSSE2);
7639
7640   if (ShouldXformToMOVHLPS(M, VT) ||
7641       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7642     return CommuteVectorShuffle(SVOp, DAG);
7643
7644   if (isShift) {
7645     // No better options. Use a vshldq / vsrldq.
7646     MVT EltVT = VT.getVectorElementType();
7647     ShAmt *= EltVT.getSizeInBits();
7648     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7649   }
7650
7651   bool Commuted = false;
7652   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7653   // 1,1,1,1 -> v8i16 though.
7654   V1IsSplat = isSplatVector(V1.getNode());
7655   V2IsSplat = isSplatVector(V2.getNode());
7656
7657   // Canonicalize the splat or undef, if present, to be on the RHS.
7658   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7659     CommuteVectorShuffleMask(M, NumElems);
7660     std::swap(V1, V2);
7661     std::swap(V1IsSplat, V2IsSplat);
7662     Commuted = true;
7663   }
7664
7665   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7666     // Shuffling low element of v1 into undef, just return v1.
7667     if (V2IsUndef)
7668       return V1;
7669     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7670     // the instruction selector will not match, so get a canonical MOVL with
7671     // swapped operands to undo the commute.
7672     return getMOVL(DAG, dl, VT, V2, V1);
7673   }
7674
7675   if (isUNPCKLMask(M, VT, HasInt256))
7676     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7677
7678   if (isUNPCKHMask(M, VT, HasInt256))
7679     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7680
7681   if (V2IsSplat) {
7682     // Normalize mask so all entries that point to V2 points to its first
7683     // element then try to match unpck{h|l} again. If match, return a
7684     // new vector_shuffle with the corrected mask.p
7685     SmallVector<int, 8> NewMask(M.begin(), M.end());
7686     NormalizeMask(NewMask, NumElems);
7687     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7688       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7689     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7690       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7691   }
7692
7693   if (Commuted) {
7694     // Commute is back and try unpck* again.
7695     // FIXME: this seems wrong.
7696     CommuteVectorShuffleMask(M, NumElems);
7697     std::swap(V1, V2);
7698     std::swap(V1IsSplat, V2IsSplat);
7699
7700     if (isUNPCKLMask(M, VT, HasInt256))
7701       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7702
7703     if (isUNPCKHMask(M, VT, HasInt256))
7704       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7705   }
7706
7707   // Normalize the node to match x86 shuffle ops if needed
7708   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7709     return CommuteVectorShuffle(SVOp, DAG);
7710
7711   // The checks below are all present in isShuffleMaskLegal, but they are
7712   // inlined here right now to enable us to directly emit target specific
7713   // nodes, and remove one by one until they don't return Op anymore.
7714
7715   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7716       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7717     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7718       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7719   }
7720
7721   if (isPSHUFHWMask(M, VT, HasInt256))
7722     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7723                                 getShufflePSHUFHWImmediate(SVOp),
7724                                 DAG);
7725
7726   if (isPSHUFLWMask(M, VT, HasInt256))
7727     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7728                                 getShufflePSHUFLWImmediate(SVOp),
7729                                 DAG);
7730
7731   if (isSHUFPMask(M, VT))
7732     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7733                                 getShuffleSHUFImmediate(SVOp), DAG);
7734
7735   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7736     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7737   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7738     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7739
7740   //===--------------------------------------------------------------------===//
7741   // Generate target specific nodes for 128 or 256-bit shuffles only
7742   // supported in the AVX instruction set.
7743   //
7744
7745   // Handle VMOVDDUPY permutations
7746   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7747     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7748
7749   // Handle VPERMILPS/D* permutations
7750   if (isVPERMILPMask(M, VT)) {
7751     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7752       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7753                                   getShuffleSHUFImmediate(SVOp), DAG);
7754     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7755                                 getShuffleSHUFImmediate(SVOp), DAG);
7756   }
7757
7758   // Handle VPERM2F128/VPERM2I128 permutations
7759   if (isVPERM2X128Mask(M, VT, HasFp256))
7760     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7761                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7762
7763   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7764   if (BlendOp.getNode())
7765     return BlendOp;
7766
7767   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7768     return getINSERTPS(SVOp, dl, DAG);
7769
7770   unsigned Imm8;
7771   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7772     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7773
7774   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7775       VT.is512BitVector()) {
7776     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7777     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7778     SmallVector<SDValue, 16> permclMask;
7779     for (unsigned i = 0; i != NumElems; ++i) {
7780       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7781     }
7782
7783     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7784     if (V2IsUndef)
7785       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7786       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7787                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7788     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7789                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7790   }
7791
7792   //===--------------------------------------------------------------------===//
7793   // Since no target specific shuffle was selected for this generic one,
7794   // lower it into other known shuffles. FIXME: this isn't true yet, but
7795   // this is the plan.
7796   //
7797
7798   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7799   if (VT == MVT::v8i16) {
7800     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7801     if (NewOp.getNode())
7802       return NewOp;
7803   }
7804
7805   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7806     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7807     if (NewOp.getNode())
7808       return NewOp;
7809   }
7810
7811   if (VT == MVT::v16i8) {
7812     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7813     if (NewOp.getNode())
7814       return NewOp;
7815   }
7816
7817   if (VT == MVT::v32i8) {
7818     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7819     if (NewOp.getNode())
7820       return NewOp;
7821   }
7822
7823   // Handle all 128-bit wide vectors with 4 elements, and match them with
7824   // several different shuffle types.
7825   if (NumElems == 4 && VT.is128BitVector())
7826     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7827
7828   // Handle general 256-bit shuffles
7829   if (VT.is256BitVector())
7830     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7831
7832   return SDValue();
7833 }
7834
7835 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7836   MVT VT = Op.getSimpleValueType();
7837   SDLoc dl(Op);
7838
7839   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7840     return SDValue();
7841
7842   if (VT.getSizeInBits() == 8) {
7843     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7844                                   Op.getOperand(0), Op.getOperand(1));
7845     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7846                                   DAG.getValueType(VT));
7847     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7848   }
7849
7850   if (VT.getSizeInBits() == 16) {
7851     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7852     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7853     if (Idx == 0)
7854       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7855                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7856                                      DAG.getNode(ISD::BITCAST, dl,
7857                                                  MVT::v4i32,
7858                                                  Op.getOperand(0)),
7859                                      Op.getOperand(1)));
7860     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7861                                   Op.getOperand(0), Op.getOperand(1));
7862     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7863                                   DAG.getValueType(VT));
7864     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7865   }
7866
7867   if (VT == MVT::f32) {
7868     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7869     // the result back to FR32 register. It's only worth matching if the
7870     // result has a single use which is a store or a bitcast to i32.  And in
7871     // the case of a store, it's not worth it if the index is a constant 0,
7872     // because a MOVSSmr can be used instead, which is smaller and faster.
7873     if (!Op.hasOneUse())
7874       return SDValue();
7875     SDNode *User = *Op.getNode()->use_begin();
7876     if ((User->getOpcode() != ISD::STORE ||
7877          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7878           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7879         (User->getOpcode() != ISD::BITCAST ||
7880          User->getValueType(0) != MVT::i32))
7881       return SDValue();
7882     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7883                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7884                                               Op.getOperand(0)),
7885                                               Op.getOperand(1));
7886     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7887   }
7888
7889   if (VT == MVT::i32 || VT == MVT::i64) {
7890     // ExtractPS/pextrq works with constant index.
7891     if (isa<ConstantSDNode>(Op.getOperand(1)))
7892       return Op;
7893   }
7894   return SDValue();
7895 }
7896
7897 /// Extract one bit from mask vector, like v16i1 or v8i1.
7898 /// AVX-512 feature.
7899 SDValue
7900 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7901   SDValue Vec = Op.getOperand(0);
7902   SDLoc dl(Vec);
7903   MVT VecVT = Vec.getSimpleValueType();
7904   SDValue Idx = Op.getOperand(1);
7905   MVT EltVT = Op.getSimpleValueType();
7906
7907   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7908
7909   // variable index can't be handled in mask registers,
7910   // extend vector to VR512
7911   if (!isa<ConstantSDNode>(Idx)) {
7912     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7913     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7914     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7915                               ExtVT.getVectorElementType(), Ext, Idx);
7916     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7917   }
7918
7919   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7920   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7921   unsigned MaxSift = rc->getSize()*8 - 1;
7922   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7923                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7924   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7925                     DAG.getConstant(MaxSift, MVT::i8));
7926   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7927                        DAG.getIntPtrConstant(0));
7928 }
7929
7930 SDValue
7931 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7932                                            SelectionDAG &DAG) const {
7933   SDLoc dl(Op);
7934   SDValue Vec = Op.getOperand(0);
7935   MVT VecVT = Vec.getSimpleValueType();
7936   SDValue Idx = Op.getOperand(1);
7937
7938   if (Op.getSimpleValueType() == MVT::i1)
7939     return ExtractBitFromMaskVector(Op, DAG);
7940
7941   if (!isa<ConstantSDNode>(Idx)) {
7942     if (VecVT.is512BitVector() ||
7943         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7944          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7945
7946       MVT MaskEltVT =
7947         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7948       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7949                                     MaskEltVT.getSizeInBits());
7950
7951       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7952       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7953                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7954                                 Idx, DAG.getConstant(0, getPointerTy()));
7955       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7956       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7957                         Perm, DAG.getConstant(0, getPointerTy()));
7958     }
7959     return SDValue();
7960   }
7961
7962   // If this is a 256-bit vector result, first extract the 128-bit vector and
7963   // then extract the element from the 128-bit vector.
7964   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7965
7966     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7967     // Get the 128-bit vector.
7968     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7969     MVT EltVT = VecVT.getVectorElementType();
7970
7971     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7972
7973     //if (IdxVal >= NumElems/2)
7974     //  IdxVal -= NumElems/2;
7975     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7976     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7977                        DAG.getConstant(IdxVal, MVT::i32));
7978   }
7979
7980   assert(VecVT.is128BitVector() && "Unexpected vector length");
7981
7982   if (Subtarget->hasSSE41()) {
7983     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7984     if (Res.getNode())
7985       return Res;
7986   }
7987
7988   MVT VT = Op.getSimpleValueType();
7989   // TODO: handle v16i8.
7990   if (VT.getSizeInBits() == 16) {
7991     SDValue Vec = Op.getOperand(0);
7992     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7993     if (Idx == 0)
7994       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7995                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7996                                      DAG.getNode(ISD::BITCAST, dl,
7997                                                  MVT::v4i32, Vec),
7998                                      Op.getOperand(1)));
7999     // Transform it so it match pextrw which produces a 32-bit result.
8000     MVT EltVT = MVT::i32;
8001     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8002                                   Op.getOperand(0), Op.getOperand(1));
8003     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8004                                   DAG.getValueType(VT));
8005     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8006   }
8007
8008   if (VT.getSizeInBits() == 32) {
8009     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8010     if (Idx == 0)
8011       return Op;
8012
8013     // SHUFPS the element to the lowest double word, then movss.
8014     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8015     MVT VVT = Op.getOperand(0).getSimpleValueType();
8016     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8017                                        DAG.getUNDEF(VVT), Mask);
8018     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8019                        DAG.getIntPtrConstant(0));
8020   }
8021
8022   if (VT.getSizeInBits() == 64) {
8023     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8024     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8025     //        to match extract_elt for f64.
8026     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8027     if (Idx == 0)
8028       return Op;
8029
8030     // UNPCKHPD the element to the lowest double word, then movsd.
8031     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8032     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8033     int Mask[2] = { 1, -1 };
8034     MVT VVT = Op.getOperand(0).getSimpleValueType();
8035     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8036                                        DAG.getUNDEF(VVT), Mask);
8037     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8038                        DAG.getIntPtrConstant(0));
8039   }
8040
8041   return SDValue();
8042 }
8043
8044 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8045   MVT VT = Op.getSimpleValueType();
8046   MVT EltVT = VT.getVectorElementType();
8047   SDLoc dl(Op);
8048
8049   SDValue N0 = Op.getOperand(0);
8050   SDValue N1 = Op.getOperand(1);
8051   SDValue N2 = Op.getOperand(2);
8052
8053   if (!VT.is128BitVector())
8054     return SDValue();
8055
8056   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8057       isa<ConstantSDNode>(N2)) {
8058     unsigned Opc;
8059     if (VT == MVT::v8i16)
8060       Opc = X86ISD::PINSRW;
8061     else if (VT == MVT::v16i8)
8062       Opc = X86ISD::PINSRB;
8063     else
8064       Opc = X86ISD::PINSRB;
8065
8066     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8067     // argument.
8068     if (N1.getValueType() != MVT::i32)
8069       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8070     if (N2.getValueType() != MVT::i32)
8071       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8072     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8073   }
8074
8075   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8076     // Bits [7:6] of the constant are the source select.  This will always be
8077     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8078     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8079     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8080     // Bits [5:4] of the constant are the destination select.  This is the
8081     //  value of the incoming immediate.
8082     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8083     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8084     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8085     // Create this as a scalar to vector..
8086     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8087     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8088   }
8089
8090   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8091     // PINSR* works with constant index.
8092     return Op;
8093   }
8094   return SDValue();
8095 }
8096
8097 /// Insert one bit to mask vector, like v16i1 or v8i1.
8098 /// AVX-512 feature.
8099 SDValue 
8100 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8101   SDLoc dl(Op);
8102   SDValue Vec = Op.getOperand(0);
8103   SDValue Elt = Op.getOperand(1);
8104   SDValue Idx = Op.getOperand(2);
8105   MVT VecVT = Vec.getSimpleValueType();
8106
8107   if (!isa<ConstantSDNode>(Idx)) {
8108     // Non constant index. Extend source and destination,
8109     // insert element and then truncate the result.
8110     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8111     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8112     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8113       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8114       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8115     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8116   }
8117
8118   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8119   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8120   if (Vec.getOpcode() == ISD::UNDEF)
8121     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8122                        DAG.getConstant(IdxVal, MVT::i8));
8123   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8124   unsigned MaxSift = rc->getSize()*8 - 1;
8125   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8126                     DAG.getConstant(MaxSift, MVT::i8));
8127   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8128                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8129   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8130 }
8131 SDValue
8132 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8133   MVT VT = Op.getSimpleValueType();
8134   MVT EltVT = VT.getVectorElementType();
8135   
8136   if (EltVT == MVT::i1)
8137     return InsertBitToMaskVector(Op, DAG);
8138
8139   SDLoc dl(Op);
8140   SDValue N0 = Op.getOperand(0);
8141   SDValue N1 = Op.getOperand(1);
8142   SDValue N2 = Op.getOperand(2);
8143
8144   // If this is a 256-bit vector result, first extract the 128-bit vector,
8145   // insert the element into the extracted half and then place it back.
8146   if (VT.is256BitVector() || VT.is512BitVector()) {
8147     if (!isa<ConstantSDNode>(N2))
8148       return SDValue();
8149
8150     // Get the desired 128-bit vector half.
8151     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8152     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8153
8154     // Insert the element into the desired half.
8155     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8156     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8157
8158     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8159                     DAG.getConstant(IdxIn128, MVT::i32));
8160
8161     // Insert the changed part back to the 256-bit vector
8162     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8163   }
8164
8165   if (Subtarget->hasSSE41())
8166     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8167
8168   if (EltVT == MVT::i8)
8169     return SDValue();
8170
8171   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8172     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8173     // as its second argument.
8174     if (N1.getValueType() != MVT::i32)
8175       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8176     if (N2.getValueType() != MVT::i32)
8177       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8178     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8179   }
8180   return SDValue();
8181 }
8182
8183 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8184   SDLoc dl(Op);
8185   MVT OpVT = Op.getSimpleValueType();
8186
8187   // If this is a 256-bit vector result, first insert into a 128-bit
8188   // vector and then insert into the 256-bit vector.
8189   if (!OpVT.is128BitVector()) {
8190     // Insert into a 128-bit vector.
8191     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8192     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8193                                  OpVT.getVectorNumElements() / SizeFactor);
8194
8195     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8196
8197     // Insert the 128-bit vector.
8198     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8199   }
8200
8201   if (OpVT == MVT::v1i64 &&
8202       Op.getOperand(0).getValueType() == MVT::i64)
8203     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8204
8205   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8206   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8207   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8208                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8209 }
8210
8211 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8212 // a simple subregister reference or explicit instructions to grab
8213 // upper bits of a vector.
8214 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8215                                       SelectionDAG &DAG) {
8216   SDLoc dl(Op);
8217   SDValue In =  Op.getOperand(0);
8218   SDValue Idx = Op.getOperand(1);
8219   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8220   MVT ResVT   = Op.getSimpleValueType();
8221   MVT InVT    = In.getSimpleValueType();
8222
8223   if (Subtarget->hasFp256()) {
8224     if (ResVT.is128BitVector() &&
8225         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8226         isa<ConstantSDNode>(Idx)) {
8227       return Extract128BitVector(In, IdxVal, DAG, dl);
8228     }
8229     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8230         isa<ConstantSDNode>(Idx)) {
8231       return Extract256BitVector(In, IdxVal, DAG, dl);
8232     }
8233   }
8234   return SDValue();
8235 }
8236
8237 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8238 // simple superregister reference or explicit instructions to insert
8239 // the upper bits of a vector.
8240 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8241                                      SelectionDAG &DAG) {
8242   if (Subtarget->hasFp256()) {
8243     SDLoc dl(Op.getNode());
8244     SDValue Vec = Op.getNode()->getOperand(0);
8245     SDValue SubVec = Op.getNode()->getOperand(1);
8246     SDValue Idx = Op.getNode()->getOperand(2);
8247
8248     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8249          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8250         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8251         isa<ConstantSDNode>(Idx)) {
8252       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8253       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8254     }
8255
8256     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8257         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8258         isa<ConstantSDNode>(Idx)) {
8259       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8260       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8261     }
8262   }
8263   return SDValue();
8264 }
8265
8266 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8267 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8268 // one of the above mentioned nodes. It has to be wrapped because otherwise
8269 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8270 // be used to form addressing mode. These wrapped nodes will be selected
8271 // into MOV32ri.
8272 SDValue
8273 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8274   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8275
8276   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8277   // global base reg.
8278   unsigned char OpFlag = 0;
8279   unsigned WrapperKind = X86ISD::Wrapper;
8280   CodeModel::Model M = getTargetMachine().getCodeModel();
8281
8282   if (Subtarget->isPICStyleRIPRel() &&
8283       (M == CodeModel::Small || M == CodeModel::Kernel))
8284     WrapperKind = X86ISD::WrapperRIP;
8285   else if (Subtarget->isPICStyleGOT())
8286     OpFlag = X86II::MO_GOTOFF;
8287   else if (Subtarget->isPICStyleStubPIC())
8288     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8289
8290   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8291                                              CP->getAlignment(),
8292                                              CP->getOffset(), OpFlag);
8293   SDLoc DL(CP);
8294   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8295   // With PIC, the address is actually $g + Offset.
8296   if (OpFlag) {
8297     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8298                          DAG.getNode(X86ISD::GlobalBaseReg,
8299                                      SDLoc(), getPointerTy()),
8300                          Result);
8301   }
8302
8303   return Result;
8304 }
8305
8306 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8307   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8308
8309   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8310   // global base reg.
8311   unsigned char OpFlag = 0;
8312   unsigned WrapperKind = X86ISD::Wrapper;
8313   CodeModel::Model M = getTargetMachine().getCodeModel();
8314
8315   if (Subtarget->isPICStyleRIPRel() &&
8316       (M == CodeModel::Small || M == CodeModel::Kernel))
8317     WrapperKind = X86ISD::WrapperRIP;
8318   else if (Subtarget->isPICStyleGOT())
8319     OpFlag = X86II::MO_GOTOFF;
8320   else if (Subtarget->isPICStyleStubPIC())
8321     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8322
8323   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8324                                           OpFlag);
8325   SDLoc DL(JT);
8326   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8327
8328   // With PIC, the address is actually $g + Offset.
8329   if (OpFlag)
8330     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8331                          DAG.getNode(X86ISD::GlobalBaseReg,
8332                                      SDLoc(), getPointerTy()),
8333                          Result);
8334
8335   return Result;
8336 }
8337
8338 SDValue
8339 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8340   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8341
8342   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8343   // global base reg.
8344   unsigned char OpFlag = 0;
8345   unsigned WrapperKind = X86ISD::Wrapper;
8346   CodeModel::Model M = getTargetMachine().getCodeModel();
8347
8348   if (Subtarget->isPICStyleRIPRel() &&
8349       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8350     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8351       OpFlag = X86II::MO_GOTPCREL;
8352     WrapperKind = X86ISD::WrapperRIP;
8353   } else if (Subtarget->isPICStyleGOT()) {
8354     OpFlag = X86II::MO_GOT;
8355   } else if (Subtarget->isPICStyleStubPIC()) {
8356     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8357   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8358     OpFlag = X86II::MO_DARWIN_NONLAZY;
8359   }
8360
8361   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8362
8363   SDLoc DL(Op);
8364   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8365
8366   // With PIC, the address is actually $g + Offset.
8367   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8368       !Subtarget->is64Bit()) {
8369     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8370                          DAG.getNode(X86ISD::GlobalBaseReg,
8371                                      SDLoc(), getPointerTy()),
8372                          Result);
8373   }
8374
8375   // For symbols that require a load from a stub to get the address, emit the
8376   // load.
8377   if (isGlobalStubReference(OpFlag))
8378     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8379                          MachinePointerInfo::getGOT(), false, false, false, 0);
8380
8381   return Result;
8382 }
8383
8384 SDValue
8385 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8386   // Create the TargetBlockAddressAddress node.
8387   unsigned char OpFlags =
8388     Subtarget->ClassifyBlockAddressReference();
8389   CodeModel::Model M = getTargetMachine().getCodeModel();
8390   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8391   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8392   SDLoc dl(Op);
8393   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8394                                              OpFlags);
8395
8396   if (Subtarget->isPICStyleRIPRel() &&
8397       (M == CodeModel::Small || M == CodeModel::Kernel))
8398     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8399   else
8400     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8401
8402   // With PIC, the address is actually $g + Offset.
8403   if (isGlobalRelativeToPICBase(OpFlags)) {
8404     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8405                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8406                          Result);
8407   }
8408
8409   return Result;
8410 }
8411
8412 SDValue
8413 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8414                                       int64_t Offset, SelectionDAG &DAG) const {
8415   // Create the TargetGlobalAddress node, folding in the constant
8416   // offset if it is legal.
8417   unsigned char OpFlags =
8418     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8419   CodeModel::Model M = getTargetMachine().getCodeModel();
8420   SDValue Result;
8421   if (OpFlags == X86II::MO_NO_FLAG &&
8422       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8423     // A direct static reference to a global.
8424     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8425     Offset = 0;
8426   } else {
8427     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8428   }
8429
8430   if (Subtarget->isPICStyleRIPRel() &&
8431       (M == CodeModel::Small || M == CodeModel::Kernel))
8432     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8433   else
8434     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8435
8436   // With PIC, the address is actually $g + Offset.
8437   if (isGlobalRelativeToPICBase(OpFlags)) {
8438     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8439                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8440                          Result);
8441   }
8442
8443   // For globals that require a load from a stub to get the address, emit the
8444   // load.
8445   if (isGlobalStubReference(OpFlags))
8446     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8447                          MachinePointerInfo::getGOT(), false, false, false, 0);
8448
8449   // If there was a non-zero offset that we didn't fold, create an explicit
8450   // addition for it.
8451   if (Offset != 0)
8452     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8453                          DAG.getConstant(Offset, getPointerTy()));
8454
8455   return Result;
8456 }
8457
8458 SDValue
8459 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8460   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8461   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8462   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8463 }
8464
8465 static SDValue
8466 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8467            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8468            unsigned char OperandFlags, bool LocalDynamic = false) {
8469   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8470   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8471   SDLoc dl(GA);
8472   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8473                                            GA->getValueType(0),
8474                                            GA->getOffset(),
8475                                            OperandFlags);
8476
8477   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8478                                            : X86ISD::TLSADDR;
8479
8480   if (InFlag) {
8481     SDValue Ops[] = { Chain,  TGA, *InFlag };
8482     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8483   } else {
8484     SDValue Ops[]  = { Chain, TGA };
8485     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8486   }
8487
8488   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8489   MFI->setAdjustsStack(true);
8490
8491   SDValue Flag = Chain.getValue(1);
8492   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8493 }
8494
8495 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8496 static SDValue
8497 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8498                                 const EVT PtrVT) {
8499   SDValue InFlag;
8500   SDLoc dl(GA);  // ? function entry point might be better
8501   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8502                                    DAG.getNode(X86ISD::GlobalBaseReg,
8503                                                SDLoc(), PtrVT), InFlag);
8504   InFlag = Chain.getValue(1);
8505
8506   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8507 }
8508
8509 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8510 static SDValue
8511 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8512                                 const EVT PtrVT) {
8513   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8514                     X86::RAX, X86II::MO_TLSGD);
8515 }
8516
8517 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8518                                            SelectionDAG &DAG,
8519                                            const EVT PtrVT,
8520                                            bool is64Bit) {
8521   SDLoc dl(GA);
8522
8523   // Get the start address of the TLS block for this module.
8524   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8525       .getInfo<X86MachineFunctionInfo>();
8526   MFI->incNumLocalDynamicTLSAccesses();
8527
8528   SDValue Base;
8529   if (is64Bit) {
8530     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8531                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8532   } else {
8533     SDValue InFlag;
8534     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8535         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8536     InFlag = Chain.getValue(1);
8537     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8538                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8539   }
8540
8541   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8542   // of Base.
8543
8544   // Build x@dtpoff.
8545   unsigned char OperandFlags = X86II::MO_DTPOFF;
8546   unsigned WrapperKind = X86ISD::Wrapper;
8547   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8548                                            GA->getValueType(0),
8549                                            GA->getOffset(), OperandFlags);
8550   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8551
8552   // Add x@dtpoff with the base.
8553   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8554 }
8555
8556 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8557 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8558                                    const EVT PtrVT, TLSModel::Model model,
8559                                    bool is64Bit, bool isPIC) {
8560   SDLoc dl(GA);
8561
8562   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8563   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8564                                                          is64Bit ? 257 : 256));
8565
8566   SDValue ThreadPointer =
8567       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8568                   MachinePointerInfo(Ptr), false, false, false, 0);
8569
8570   unsigned char OperandFlags = 0;
8571   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8572   // initialexec.
8573   unsigned WrapperKind = X86ISD::Wrapper;
8574   if (model == TLSModel::LocalExec) {
8575     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8576   } else if (model == TLSModel::InitialExec) {
8577     if (is64Bit) {
8578       OperandFlags = X86II::MO_GOTTPOFF;
8579       WrapperKind = X86ISD::WrapperRIP;
8580     } else {
8581       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8582     }
8583   } else {
8584     llvm_unreachable("Unexpected model");
8585   }
8586
8587   // emit "addl x@ntpoff,%eax" (local exec)
8588   // or "addl x@indntpoff,%eax" (initial exec)
8589   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8590   SDValue TGA =
8591       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8592                                  GA->getOffset(), OperandFlags);
8593   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8594
8595   if (model == TLSModel::InitialExec) {
8596     if (isPIC && !is64Bit) {
8597       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8598                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8599                            Offset);
8600     }
8601
8602     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8603                          MachinePointerInfo::getGOT(), false, false, false, 0);
8604   }
8605
8606   // The address of the thread local variable is the add of the thread
8607   // pointer with the offset of the variable.
8608   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8609 }
8610
8611 SDValue
8612 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8613
8614   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8615   const GlobalValue *GV = GA->getGlobal();
8616
8617   if (Subtarget->isTargetELF()) {
8618     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8619
8620     switch (model) {
8621       case TLSModel::GeneralDynamic:
8622         if (Subtarget->is64Bit())
8623           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8624         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8625       case TLSModel::LocalDynamic:
8626         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8627                                            Subtarget->is64Bit());
8628       case TLSModel::InitialExec:
8629       case TLSModel::LocalExec:
8630         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8631                                    Subtarget->is64Bit(),
8632                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8633     }
8634     llvm_unreachable("Unknown TLS model.");
8635   }
8636
8637   if (Subtarget->isTargetDarwin()) {
8638     // Darwin only has one model of TLS.  Lower to that.
8639     unsigned char OpFlag = 0;
8640     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8641                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8642
8643     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8644     // global base reg.
8645     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8646                   !Subtarget->is64Bit();
8647     if (PIC32)
8648       OpFlag = X86II::MO_TLVP_PIC_BASE;
8649     else
8650       OpFlag = X86II::MO_TLVP;
8651     SDLoc DL(Op);
8652     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8653                                                 GA->getValueType(0),
8654                                                 GA->getOffset(), OpFlag);
8655     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8656
8657     // With PIC32, the address is actually $g + Offset.
8658     if (PIC32)
8659       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8660                            DAG.getNode(X86ISD::GlobalBaseReg,
8661                                        SDLoc(), getPointerTy()),
8662                            Offset);
8663
8664     // Lowering the machine isd will make sure everything is in the right
8665     // location.
8666     SDValue Chain = DAG.getEntryNode();
8667     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8668     SDValue Args[] = { Chain, Offset };
8669     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8670
8671     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8672     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8673     MFI->setAdjustsStack(true);
8674
8675     // And our return value (tls address) is in the standard call return value
8676     // location.
8677     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8678     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8679                               Chain.getValue(1));
8680   }
8681
8682   if (Subtarget->isTargetKnownWindowsMSVC() ||
8683       Subtarget->isTargetWindowsGNU()) {
8684     // Just use the implicit TLS architecture
8685     // Need to generate someting similar to:
8686     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8687     //                                  ; from TEB
8688     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8689     //   mov     rcx, qword [rdx+rcx*8]
8690     //   mov     eax, .tls$:tlsvar
8691     //   [rax+rcx] contains the address
8692     // Windows 64bit: gs:0x58
8693     // Windows 32bit: fs:__tls_array
8694
8695     // If GV is an alias then use the aliasee for determining
8696     // thread-localness.
8697     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8698       GV = GA->getAliasedGlobal();
8699     SDLoc dl(GA);
8700     SDValue Chain = DAG.getEntryNode();
8701
8702     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8703     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8704     // use its literal value of 0x2C.
8705     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8706                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8707                                                              256)
8708                                         : Type::getInt32PtrTy(*DAG.getContext(),
8709                                                               257));
8710
8711     SDValue TlsArray =
8712         Subtarget->is64Bit()
8713             ? DAG.getIntPtrConstant(0x58)
8714             : (Subtarget->isTargetWindowsGNU()
8715                    ? DAG.getIntPtrConstant(0x2C)
8716                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8717
8718     SDValue ThreadPointer =
8719         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8720                     MachinePointerInfo(Ptr), false, false, false, 0);
8721
8722     // Load the _tls_index variable
8723     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8724     if (Subtarget->is64Bit())
8725       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8726                            IDX, MachinePointerInfo(), MVT::i32,
8727                            false, false, 0);
8728     else
8729       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8730                         false, false, false, 0);
8731
8732     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8733                                     getPointerTy());
8734     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8735
8736     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8737     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8738                       false, false, false, 0);
8739
8740     // Get the offset of start of .tls section
8741     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8742                                              GA->getValueType(0),
8743                                              GA->getOffset(), X86II::MO_SECREL);
8744     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8745
8746     // The address of the thread local variable is the add of the thread
8747     // pointer with the offset of the variable.
8748     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8749   }
8750
8751   llvm_unreachable("TLS not implemented for this target.");
8752 }
8753
8754 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8755 /// and take a 2 x i32 value to shift plus a shift amount.
8756 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8757   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8758   MVT VT = Op.getSimpleValueType();
8759   unsigned VTBits = VT.getSizeInBits();
8760   SDLoc dl(Op);
8761   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8762   SDValue ShOpLo = Op.getOperand(0);
8763   SDValue ShOpHi = Op.getOperand(1);
8764   SDValue ShAmt  = Op.getOperand(2);
8765   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8766   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8767   // during isel.
8768   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8769                                   DAG.getConstant(VTBits - 1, MVT::i8));
8770   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8771                                      DAG.getConstant(VTBits - 1, MVT::i8))
8772                        : DAG.getConstant(0, VT);
8773
8774   SDValue Tmp2, Tmp3;
8775   if (Op.getOpcode() == ISD::SHL_PARTS) {
8776     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8777     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8778   } else {
8779     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8780     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8781   }
8782
8783   // If the shift amount is larger or equal than the width of a part we can't
8784   // rely on the results of shld/shrd. Insert a test and select the appropriate
8785   // values for large shift amounts.
8786   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8787                                 DAG.getConstant(VTBits, MVT::i8));
8788   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8789                              AndNode, DAG.getConstant(0, MVT::i8));
8790
8791   SDValue Hi, Lo;
8792   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8793   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8794   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8795
8796   if (Op.getOpcode() == ISD::SHL_PARTS) {
8797     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8798     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8799   } else {
8800     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8801     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8802   }
8803
8804   SDValue Ops[2] = { Lo, Hi };
8805   return DAG.getMergeValues(Ops, dl);
8806 }
8807
8808 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8809                                            SelectionDAG &DAG) const {
8810   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8811
8812   if (SrcVT.isVector())
8813     return SDValue();
8814
8815   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8816          "Unknown SINT_TO_FP to lower!");
8817
8818   // These are really Legal; return the operand so the caller accepts it as
8819   // Legal.
8820   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8821     return Op;
8822   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8823       Subtarget->is64Bit()) {
8824     return Op;
8825   }
8826
8827   SDLoc dl(Op);
8828   unsigned Size = SrcVT.getSizeInBits()/8;
8829   MachineFunction &MF = DAG.getMachineFunction();
8830   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8831   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8832   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8833                                StackSlot,
8834                                MachinePointerInfo::getFixedStack(SSFI),
8835                                false, false, 0);
8836   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8837 }
8838
8839 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8840                                      SDValue StackSlot,
8841                                      SelectionDAG &DAG) const {
8842   // Build the FILD
8843   SDLoc DL(Op);
8844   SDVTList Tys;
8845   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8846   if (useSSE)
8847     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8848   else
8849     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8850
8851   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8852
8853   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8854   MachineMemOperand *MMO;
8855   if (FI) {
8856     int SSFI = FI->getIndex();
8857     MMO =
8858       DAG.getMachineFunction()
8859       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8860                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8861   } else {
8862     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8863     StackSlot = StackSlot.getOperand(1);
8864   }
8865   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8866   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8867                                            X86ISD::FILD, DL,
8868                                            Tys, Ops, SrcVT, MMO);
8869
8870   if (useSSE) {
8871     Chain = Result.getValue(1);
8872     SDValue InFlag = Result.getValue(2);
8873
8874     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8875     // shouldn't be necessary except that RFP cannot be live across
8876     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8877     MachineFunction &MF = DAG.getMachineFunction();
8878     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8879     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8880     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8881     Tys = DAG.getVTList(MVT::Other);
8882     SDValue Ops[] = {
8883       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8884     };
8885     MachineMemOperand *MMO =
8886       DAG.getMachineFunction()
8887       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8888                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8889
8890     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8891                                     Ops, Op.getValueType(), MMO);
8892     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8893                          MachinePointerInfo::getFixedStack(SSFI),
8894                          false, false, false, 0);
8895   }
8896
8897   return Result;
8898 }
8899
8900 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8901 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8902                                                SelectionDAG &DAG) const {
8903   // This algorithm is not obvious. Here it is what we're trying to output:
8904   /*
8905      movq       %rax,  %xmm0
8906      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8907      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8908      #ifdef __SSE3__
8909        haddpd   %xmm0, %xmm0
8910      #else
8911        pshufd   $0x4e, %xmm0, %xmm1
8912        addpd    %xmm1, %xmm0
8913      #endif
8914   */
8915
8916   SDLoc dl(Op);
8917   LLVMContext *Context = DAG.getContext();
8918
8919   // Build some magic constants.
8920   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8921   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8922   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8923
8924   SmallVector<Constant*,2> CV1;
8925   CV1.push_back(
8926     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8927                                       APInt(64, 0x4330000000000000ULL))));
8928   CV1.push_back(
8929     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8930                                       APInt(64, 0x4530000000000000ULL))));
8931   Constant *C1 = ConstantVector::get(CV1);
8932   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8933
8934   // Load the 64-bit value into an XMM register.
8935   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8936                             Op.getOperand(0));
8937   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8938                               MachinePointerInfo::getConstantPool(),
8939                               false, false, false, 16);
8940   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8941                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8942                               CLod0);
8943
8944   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8945                               MachinePointerInfo::getConstantPool(),
8946                               false, false, false, 16);
8947   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8948   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8949   SDValue Result;
8950
8951   if (Subtarget->hasSSE3()) {
8952     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8953     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8954   } else {
8955     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8956     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8957                                            S2F, 0x4E, DAG);
8958     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8959                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8960                          Sub);
8961   }
8962
8963   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8964                      DAG.getIntPtrConstant(0));
8965 }
8966
8967 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8968 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8969                                                SelectionDAG &DAG) const {
8970   SDLoc dl(Op);
8971   // FP constant to bias correct the final result.
8972   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8973                                    MVT::f64);
8974
8975   // Load the 32-bit value into an XMM register.
8976   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8977                              Op.getOperand(0));
8978
8979   // Zero out the upper parts of the register.
8980   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8981
8982   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8983                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8984                      DAG.getIntPtrConstant(0));
8985
8986   // Or the load with the bias.
8987   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8988                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8989                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8990                                                    MVT::v2f64, Load)),
8991                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8992                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8993                                                    MVT::v2f64, Bias)));
8994   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8995                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8996                    DAG.getIntPtrConstant(0));
8997
8998   // Subtract the bias.
8999   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9000
9001   // Handle final rounding.
9002   EVT DestVT = Op.getValueType();
9003
9004   if (DestVT.bitsLT(MVT::f64))
9005     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9006                        DAG.getIntPtrConstant(0));
9007   if (DestVT.bitsGT(MVT::f64))
9008     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9009
9010   // Handle final rounding.
9011   return Sub;
9012 }
9013
9014 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9015                                                SelectionDAG &DAG) const {
9016   SDValue N0 = Op.getOperand(0);
9017   MVT SVT = N0.getSimpleValueType();
9018   SDLoc dl(Op);
9019
9020   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9021           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9022          "Custom UINT_TO_FP is not supported!");
9023
9024   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9025   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9026                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9027 }
9028
9029 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9030                                            SelectionDAG &DAG) const {
9031   SDValue N0 = Op.getOperand(0);
9032   SDLoc dl(Op);
9033
9034   if (Op.getValueType().isVector())
9035     return lowerUINT_TO_FP_vec(Op, DAG);
9036
9037   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9038   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9039   // the optimization here.
9040   if (DAG.SignBitIsZero(N0))
9041     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9042
9043   MVT SrcVT = N0.getSimpleValueType();
9044   MVT DstVT = Op.getSimpleValueType();
9045   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9046     return LowerUINT_TO_FP_i64(Op, DAG);
9047   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9048     return LowerUINT_TO_FP_i32(Op, DAG);
9049   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9050     return SDValue();
9051
9052   // Make a 64-bit buffer, and use it to build an FILD.
9053   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9054   if (SrcVT == MVT::i32) {
9055     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9056     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9057                                      getPointerTy(), StackSlot, WordOff);
9058     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9059                                   StackSlot, MachinePointerInfo(),
9060                                   false, false, 0);
9061     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9062                                   OffsetSlot, MachinePointerInfo(),
9063                                   false, false, 0);
9064     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9065     return Fild;
9066   }
9067
9068   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9069   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9070                                StackSlot, MachinePointerInfo(),
9071                                false, false, 0);
9072   // For i64 source, we need to add the appropriate power of 2 if the input
9073   // was negative.  This is the same as the optimization in
9074   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9075   // we must be careful to do the computation in x87 extended precision, not
9076   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9077   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9078   MachineMemOperand *MMO =
9079     DAG.getMachineFunction()
9080     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9081                           MachineMemOperand::MOLoad, 8, 8);
9082
9083   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9084   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9085   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9086                                          MVT::i64, MMO);
9087
9088   APInt FF(32, 0x5F800000ULL);
9089
9090   // Check whether the sign bit is set.
9091   SDValue SignSet = DAG.getSetCC(dl,
9092                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9093                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9094                                  ISD::SETLT);
9095
9096   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9097   SDValue FudgePtr = DAG.getConstantPool(
9098                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9099                                          getPointerTy());
9100
9101   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9102   SDValue Zero = DAG.getIntPtrConstant(0);
9103   SDValue Four = DAG.getIntPtrConstant(4);
9104   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9105                                Zero, Four);
9106   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9107
9108   // Load the value out, extending it from f32 to f80.
9109   // FIXME: Avoid the extend by constructing the right constant pool?
9110   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9111                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9112                                  MVT::f32, false, false, 4);
9113   // Extend everything to 80 bits to force it to be done on x87.
9114   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9115   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9116 }
9117
9118 std::pair<SDValue,SDValue>
9119 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9120                                     bool IsSigned, bool IsReplace) const {
9121   SDLoc DL(Op);
9122
9123   EVT DstTy = Op.getValueType();
9124
9125   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9126     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9127     DstTy = MVT::i64;
9128   }
9129
9130   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9131          DstTy.getSimpleVT() >= MVT::i16 &&
9132          "Unknown FP_TO_INT to lower!");
9133
9134   // These are really Legal.
9135   if (DstTy == MVT::i32 &&
9136       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9137     return std::make_pair(SDValue(), SDValue());
9138   if (Subtarget->is64Bit() &&
9139       DstTy == MVT::i64 &&
9140       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9141     return std::make_pair(SDValue(), SDValue());
9142
9143   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9144   // stack slot, or into the FTOL runtime function.
9145   MachineFunction &MF = DAG.getMachineFunction();
9146   unsigned MemSize = DstTy.getSizeInBits()/8;
9147   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9148   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9149
9150   unsigned Opc;
9151   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9152     Opc = X86ISD::WIN_FTOL;
9153   else
9154     switch (DstTy.getSimpleVT().SimpleTy) {
9155     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9156     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9157     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9158     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9159     }
9160
9161   SDValue Chain = DAG.getEntryNode();
9162   SDValue Value = Op.getOperand(0);
9163   EVT TheVT = Op.getOperand(0).getValueType();
9164   // FIXME This causes a redundant load/store if the SSE-class value is already
9165   // in memory, such as if it is on the callstack.
9166   if (isScalarFPTypeInSSEReg(TheVT)) {
9167     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9168     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9169                          MachinePointerInfo::getFixedStack(SSFI),
9170                          false, false, 0);
9171     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9172     SDValue Ops[] = {
9173       Chain, StackSlot, DAG.getValueType(TheVT)
9174     };
9175
9176     MachineMemOperand *MMO =
9177       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9178                               MachineMemOperand::MOLoad, MemSize, MemSize);
9179     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9180     Chain = Value.getValue(1);
9181     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9182     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9183   }
9184
9185   MachineMemOperand *MMO =
9186     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9187                             MachineMemOperand::MOStore, MemSize, MemSize);
9188
9189   if (Opc != X86ISD::WIN_FTOL) {
9190     // Build the FP_TO_INT*_IN_MEM
9191     SDValue Ops[] = { Chain, Value, StackSlot };
9192     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9193                                            Ops, DstTy, MMO);
9194     return std::make_pair(FIST, StackSlot);
9195   } else {
9196     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9197       DAG.getVTList(MVT::Other, MVT::Glue),
9198       Chain, Value);
9199     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9200       MVT::i32, ftol.getValue(1));
9201     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9202       MVT::i32, eax.getValue(2));
9203     SDValue Ops[] = { eax, edx };
9204     SDValue pair = IsReplace
9205       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9206       : DAG.getMergeValues(Ops, DL);
9207     return std::make_pair(pair, SDValue());
9208   }
9209 }
9210
9211 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9212                               const X86Subtarget *Subtarget) {
9213   MVT VT = Op->getSimpleValueType(0);
9214   SDValue In = Op->getOperand(0);
9215   MVT InVT = In.getSimpleValueType();
9216   SDLoc dl(Op);
9217
9218   // Optimize vectors in AVX mode:
9219   //
9220   //   v8i16 -> v8i32
9221   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9222   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9223   //   Concat upper and lower parts.
9224   //
9225   //   v4i32 -> v4i64
9226   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9227   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9228   //   Concat upper and lower parts.
9229   //
9230
9231   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9232       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9233       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9234     return SDValue();
9235
9236   if (Subtarget->hasInt256())
9237     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9238
9239   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9240   SDValue Undef = DAG.getUNDEF(InVT);
9241   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9242   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9243   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9244
9245   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9246                              VT.getVectorNumElements()/2);
9247
9248   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9249   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9250
9251   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9252 }
9253
9254 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9255                                         SelectionDAG &DAG) {
9256   MVT VT = Op->getSimpleValueType(0);
9257   SDValue In = Op->getOperand(0);
9258   MVT InVT = In.getSimpleValueType();
9259   SDLoc DL(Op);
9260   unsigned int NumElts = VT.getVectorNumElements();
9261   if (NumElts != 8 && NumElts != 16)
9262     return SDValue();
9263
9264   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9265     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9266
9267   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9269   // Now we have only mask extension
9270   assert(InVT.getVectorElementType() == MVT::i1);
9271   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9272   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9273   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9274   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9275   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9276                            MachinePointerInfo::getConstantPool(),
9277                            false, false, false, Alignment);
9278
9279   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9280   if (VT.is512BitVector())
9281     return Brcst;
9282   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9283 }
9284
9285 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9286                                SelectionDAG &DAG) {
9287   if (Subtarget->hasFp256()) {
9288     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9289     if (Res.getNode())
9290       return Res;
9291   }
9292
9293   return SDValue();
9294 }
9295
9296 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9297                                 SelectionDAG &DAG) {
9298   SDLoc DL(Op);
9299   MVT VT = Op.getSimpleValueType();
9300   SDValue In = Op.getOperand(0);
9301   MVT SVT = In.getSimpleValueType();
9302
9303   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9304     return LowerZERO_EXTEND_AVX512(Op, DAG);
9305
9306   if (Subtarget->hasFp256()) {
9307     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9308     if (Res.getNode())
9309       return Res;
9310   }
9311
9312   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9313          VT.getVectorNumElements() != SVT.getVectorNumElements());
9314   return SDValue();
9315 }
9316
9317 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9318   SDLoc DL(Op);
9319   MVT VT = Op.getSimpleValueType();
9320   SDValue In = Op.getOperand(0);
9321   MVT InVT = In.getSimpleValueType();
9322
9323   if (VT == MVT::i1) {
9324     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9325            "Invalid scalar TRUNCATE operation");
9326     if (InVT == MVT::i32)
9327       return SDValue();
9328     if (InVT.getSizeInBits() == 64)
9329       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9330     else if (InVT.getSizeInBits() < 32)
9331       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9332     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9333   }
9334   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9335          "Invalid TRUNCATE operation");
9336
9337   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9338     if (VT.getVectorElementType().getSizeInBits() >=8)
9339       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9340
9341     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9342     unsigned NumElts = InVT.getVectorNumElements();
9343     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9344     if (InVT.getSizeInBits() < 512) {
9345       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9346       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9347       InVT = ExtVT;
9348     }
9349     
9350     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9351     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9352     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9353     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9354     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9355                            MachinePointerInfo::getConstantPool(),
9356                            false, false, false, Alignment);
9357     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9358     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9359     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9360   }
9361
9362   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9363     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9364     if (Subtarget->hasInt256()) {
9365       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9366       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9367       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9368                                 ShufMask);
9369       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9370                          DAG.getIntPtrConstant(0));
9371     }
9372
9373     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9374                                DAG.getIntPtrConstant(0));
9375     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9376                                DAG.getIntPtrConstant(2));
9377     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9378     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9379     static const int ShufMask[] = {0, 2, 4, 6};
9380     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9381   }
9382
9383   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9384     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9385     if (Subtarget->hasInt256()) {
9386       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9387
9388       SmallVector<SDValue,32> pshufbMask;
9389       for (unsigned i = 0; i < 2; ++i) {
9390         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9391         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9392         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9393         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9394         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9395         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9396         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9397         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9398         for (unsigned j = 0; j < 8; ++j)
9399           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9400       }
9401       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9402       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9403       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9404
9405       static const int ShufMask[] = {0,  2,  -1,  -1};
9406       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9407                                 &ShufMask[0]);
9408       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9409                        DAG.getIntPtrConstant(0));
9410       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9411     }
9412
9413     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9414                                DAG.getIntPtrConstant(0));
9415
9416     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9417                                DAG.getIntPtrConstant(4));
9418
9419     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9420     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9421
9422     // The PSHUFB mask:
9423     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9424                                    -1, -1, -1, -1, -1, -1, -1, -1};
9425
9426     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9427     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9428     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9429
9430     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9431     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9432
9433     // The MOVLHPS Mask:
9434     static const int ShufMask2[] = {0, 1, 4, 5};
9435     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9436     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9437   }
9438
9439   // Handle truncation of V256 to V128 using shuffles.
9440   if (!VT.is128BitVector() || !InVT.is256BitVector())
9441     return SDValue();
9442
9443   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9444
9445   unsigned NumElems = VT.getVectorNumElements();
9446   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9447
9448   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9449   // Prepare truncation shuffle mask
9450   for (unsigned i = 0; i != NumElems; ++i)
9451     MaskVec[i] = i * 2;
9452   SDValue V = DAG.getVectorShuffle(NVT, DL,
9453                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9454                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9455   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9456                      DAG.getIntPtrConstant(0));
9457 }
9458
9459 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9460                                            SelectionDAG &DAG) const {
9461   assert(!Op.getSimpleValueType().isVector());
9462
9463   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9464     /*IsSigned=*/ true, /*IsReplace=*/ false);
9465   SDValue FIST = Vals.first, StackSlot = Vals.second;
9466   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9467   if (!FIST.getNode()) return Op;
9468
9469   if (StackSlot.getNode())
9470     // Load the result.
9471     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9472                        FIST, StackSlot, MachinePointerInfo(),
9473                        false, false, false, 0);
9474
9475   // The node is the result.
9476   return FIST;
9477 }
9478
9479 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9480                                            SelectionDAG &DAG) const {
9481   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9482     /*IsSigned=*/ false, /*IsReplace=*/ false);
9483   SDValue FIST = Vals.first, StackSlot = Vals.second;
9484   assert(FIST.getNode() && "Unexpected failure");
9485
9486   if (StackSlot.getNode())
9487     // Load the result.
9488     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9489                        FIST, StackSlot, MachinePointerInfo(),
9490                        false, false, false, 0);
9491
9492   // The node is the result.
9493   return FIST;
9494 }
9495
9496 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9497   SDLoc DL(Op);
9498   MVT VT = Op.getSimpleValueType();
9499   SDValue In = Op.getOperand(0);
9500   MVT SVT = In.getSimpleValueType();
9501
9502   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9503
9504   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9505                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9506                                  In, DAG.getUNDEF(SVT)));
9507 }
9508
9509 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9510   LLVMContext *Context = DAG.getContext();
9511   SDLoc dl(Op);
9512   MVT VT = Op.getSimpleValueType();
9513   MVT EltVT = VT;
9514   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9515   if (VT.isVector()) {
9516     EltVT = VT.getVectorElementType();
9517     NumElts = VT.getVectorNumElements();
9518   }
9519   Constant *C;
9520   if (EltVT == MVT::f64)
9521     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9522                                           APInt(64, ~(1ULL << 63))));
9523   else
9524     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9525                                           APInt(32, ~(1U << 31))));
9526   C = ConstantVector::getSplat(NumElts, C);
9527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9528   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9529   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9530   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9531                              MachinePointerInfo::getConstantPool(),
9532                              false, false, false, Alignment);
9533   if (VT.isVector()) {
9534     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9535     return DAG.getNode(ISD::BITCAST, dl, VT,
9536                        DAG.getNode(ISD::AND, dl, ANDVT,
9537                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9538                                                Op.getOperand(0)),
9539                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9540   }
9541   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9542 }
9543
9544 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9545   LLVMContext *Context = DAG.getContext();
9546   SDLoc dl(Op);
9547   MVT VT = Op.getSimpleValueType();
9548   MVT EltVT = VT;
9549   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9550   if (VT.isVector()) {
9551     EltVT = VT.getVectorElementType();
9552     NumElts = VT.getVectorNumElements();
9553   }
9554   Constant *C;
9555   if (EltVT == MVT::f64)
9556     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9557                                           APInt(64, 1ULL << 63)));
9558   else
9559     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9560                                           APInt(32, 1U << 31)));
9561   C = ConstantVector::getSplat(NumElts, C);
9562   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9563   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9564   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9565   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9566                              MachinePointerInfo::getConstantPool(),
9567                              false, false, false, Alignment);
9568   if (VT.isVector()) {
9569     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9570     return DAG.getNode(ISD::BITCAST, dl, VT,
9571                        DAG.getNode(ISD::XOR, dl, XORVT,
9572                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9573                                                Op.getOperand(0)),
9574                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9575   }
9576
9577   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9578 }
9579
9580 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9582   LLVMContext *Context = DAG.getContext();
9583   SDValue Op0 = Op.getOperand(0);
9584   SDValue Op1 = Op.getOperand(1);
9585   SDLoc dl(Op);
9586   MVT VT = Op.getSimpleValueType();
9587   MVT SrcVT = Op1.getSimpleValueType();
9588
9589   // If second operand is smaller, extend it first.
9590   if (SrcVT.bitsLT(VT)) {
9591     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9592     SrcVT = VT;
9593   }
9594   // And if it is bigger, shrink it first.
9595   if (SrcVT.bitsGT(VT)) {
9596     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9597     SrcVT = VT;
9598   }
9599
9600   // At this point the operands and the result should have the same
9601   // type, and that won't be f80 since that is not custom lowered.
9602
9603   // First get the sign bit of second operand.
9604   SmallVector<Constant*,4> CV;
9605   if (SrcVT == MVT::f64) {
9606     const fltSemantics &Sem = APFloat::IEEEdouble;
9607     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9608     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9609   } else {
9610     const fltSemantics &Sem = APFloat::IEEEsingle;
9611     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9612     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9613     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9614     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9615   }
9616   Constant *C = ConstantVector::get(CV);
9617   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9618   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9619                               MachinePointerInfo::getConstantPool(),
9620                               false, false, false, 16);
9621   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9622
9623   // Shift sign bit right or left if the two operands have different types.
9624   if (SrcVT.bitsGT(VT)) {
9625     // Op0 is MVT::f32, Op1 is MVT::f64.
9626     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9627     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9628                           DAG.getConstant(32, MVT::i32));
9629     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9630     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9631                           DAG.getIntPtrConstant(0));
9632   }
9633
9634   // Clear first operand sign bit.
9635   CV.clear();
9636   if (VT == MVT::f64) {
9637     const fltSemantics &Sem = APFloat::IEEEdouble;
9638     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9639                                                    APInt(64, ~(1ULL << 63)))));
9640     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9641   } else {
9642     const fltSemantics &Sem = APFloat::IEEEsingle;
9643     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9644                                                    APInt(32, ~(1U << 31)))));
9645     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9646     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9647     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9648   }
9649   C = ConstantVector::get(CV);
9650   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9651   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9652                               MachinePointerInfo::getConstantPool(),
9653                               false, false, false, 16);
9654   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9655
9656   // Or the value with the sign bit.
9657   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9658 }
9659
9660 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9661   SDValue N0 = Op.getOperand(0);
9662   SDLoc dl(Op);
9663   MVT VT = Op.getSimpleValueType();
9664
9665   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9666   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9667                                   DAG.getConstant(1, VT));
9668   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9669 }
9670
9671 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9672 //
9673 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9674                                       SelectionDAG &DAG) {
9675   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9676
9677   if (!Subtarget->hasSSE41())
9678     return SDValue();
9679
9680   if (!Op->hasOneUse())
9681     return SDValue();
9682
9683   SDNode *N = Op.getNode();
9684   SDLoc DL(N);
9685
9686   SmallVector<SDValue, 8> Opnds;
9687   DenseMap<SDValue, unsigned> VecInMap;
9688   SmallVector<SDValue, 8> VecIns;
9689   EVT VT = MVT::Other;
9690
9691   // Recognize a special case where a vector is casted into wide integer to
9692   // test all 0s.
9693   Opnds.push_back(N->getOperand(0));
9694   Opnds.push_back(N->getOperand(1));
9695
9696   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9697     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9698     // BFS traverse all OR'd operands.
9699     if (I->getOpcode() == ISD::OR) {
9700       Opnds.push_back(I->getOperand(0));
9701       Opnds.push_back(I->getOperand(1));
9702       // Re-evaluate the number of nodes to be traversed.
9703       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9704       continue;
9705     }
9706
9707     // Quit if a non-EXTRACT_VECTOR_ELT
9708     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9709       return SDValue();
9710
9711     // Quit if without a constant index.
9712     SDValue Idx = I->getOperand(1);
9713     if (!isa<ConstantSDNode>(Idx))
9714       return SDValue();
9715
9716     SDValue ExtractedFromVec = I->getOperand(0);
9717     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9718     if (M == VecInMap.end()) {
9719       VT = ExtractedFromVec.getValueType();
9720       // Quit if not 128/256-bit vector.
9721       if (!VT.is128BitVector() && !VT.is256BitVector())
9722         return SDValue();
9723       // Quit if not the same type.
9724       if (VecInMap.begin() != VecInMap.end() &&
9725           VT != VecInMap.begin()->first.getValueType())
9726         return SDValue();
9727       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9728       VecIns.push_back(ExtractedFromVec);
9729     }
9730     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9731   }
9732
9733   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9734          "Not extracted from 128-/256-bit vector.");
9735
9736   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9737
9738   for (DenseMap<SDValue, unsigned>::const_iterator
9739         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9740     // Quit if not all elements are used.
9741     if (I->second != FullMask)
9742       return SDValue();
9743   }
9744
9745   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9746
9747   // Cast all vectors into TestVT for PTEST.
9748   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9749     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9750
9751   // If more than one full vectors are evaluated, OR them first before PTEST.
9752   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9753     // Each iteration will OR 2 nodes and append the result until there is only
9754     // 1 node left, i.e. the final OR'd value of all vectors.
9755     SDValue LHS = VecIns[Slot];
9756     SDValue RHS = VecIns[Slot + 1];
9757     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9758   }
9759
9760   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9761                      VecIns.back(), VecIns.back());
9762 }
9763
9764 /// \brief return true if \c Op has a use that doesn't just read flags.
9765 static bool hasNonFlagsUse(SDValue Op) {
9766   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9767        ++UI) {
9768     SDNode *User = *UI;
9769     unsigned UOpNo = UI.getOperandNo();
9770     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9771       // Look pass truncate.
9772       UOpNo = User->use_begin().getOperandNo();
9773       User = *User->use_begin();
9774     }
9775
9776     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9777         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9778       return true;
9779   }
9780   return false;
9781 }
9782
9783 /// Emit nodes that will be selected as "test Op0,Op0", or something
9784 /// equivalent.
9785 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9786                                     SelectionDAG &DAG) const {
9787   if (Op.getValueType() == MVT::i1)
9788     // KORTEST instruction should be selected
9789     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9790                        DAG.getConstant(0, Op.getValueType()));
9791
9792   // CF and OF aren't always set the way we want. Determine which
9793   // of these we need.
9794   bool NeedCF = false;
9795   bool NeedOF = false;
9796   switch (X86CC) {
9797   default: break;
9798   case X86::COND_A: case X86::COND_AE:
9799   case X86::COND_B: case X86::COND_BE:
9800     NeedCF = true;
9801     break;
9802   case X86::COND_G: case X86::COND_GE:
9803   case X86::COND_L: case X86::COND_LE:
9804   case X86::COND_O: case X86::COND_NO:
9805     NeedOF = true;
9806     break;
9807   }
9808   // See if we can use the EFLAGS value from the operand instead of
9809   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9810   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9811   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9812     // Emit a CMP with 0, which is the TEST pattern.
9813     //if (Op.getValueType() == MVT::i1)
9814     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9815     //                     DAG.getConstant(0, MVT::i1));
9816     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9817                        DAG.getConstant(0, Op.getValueType()));
9818   }
9819   unsigned Opcode = 0;
9820   unsigned NumOperands = 0;
9821
9822   // Truncate operations may prevent the merge of the SETCC instruction
9823   // and the arithmetic instruction before it. Attempt to truncate the operands
9824   // of the arithmetic instruction and use a reduced bit-width instruction.
9825   bool NeedTruncation = false;
9826   SDValue ArithOp = Op;
9827   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9828     SDValue Arith = Op->getOperand(0);
9829     // Both the trunc and the arithmetic op need to have one user each.
9830     if (Arith->hasOneUse())
9831       switch (Arith.getOpcode()) {
9832         default: break;
9833         case ISD::ADD:
9834         case ISD::SUB:
9835         case ISD::AND:
9836         case ISD::OR:
9837         case ISD::XOR: {
9838           NeedTruncation = true;
9839           ArithOp = Arith;
9840         }
9841       }
9842   }
9843
9844   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9845   // which may be the result of a CAST.  We use the variable 'Op', which is the
9846   // non-casted variable when we check for possible users.
9847   switch (ArithOp.getOpcode()) {
9848   case ISD::ADD:
9849     // Due to an isel shortcoming, be conservative if this add is likely to be
9850     // selected as part of a load-modify-store instruction. When the root node
9851     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9852     // uses of other nodes in the match, such as the ADD in this case. This
9853     // leads to the ADD being left around and reselected, with the result being
9854     // two adds in the output.  Alas, even if none our users are stores, that
9855     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9856     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9857     // climbing the DAG back to the root, and it doesn't seem to be worth the
9858     // effort.
9859     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9860          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9861       if (UI->getOpcode() != ISD::CopyToReg &&
9862           UI->getOpcode() != ISD::SETCC &&
9863           UI->getOpcode() != ISD::STORE)
9864         goto default_case;
9865
9866     if (ConstantSDNode *C =
9867         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9868       // An add of one will be selected as an INC.
9869       if (C->getAPIntValue() == 1) {
9870         Opcode = X86ISD::INC;
9871         NumOperands = 1;
9872         break;
9873       }
9874
9875       // An add of negative one (subtract of one) will be selected as a DEC.
9876       if (C->getAPIntValue().isAllOnesValue()) {
9877         Opcode = X86ISD::DEC;
9878         NumOperands = 1;
9879         break;
9880       }
9881     }
9882
9883     // Otherwise use a regular EFLAGS-setting add.
9884     Opcode = X86ISD::ADD;
9885     NumOperands = 2;
9886     break;
9887   case ISD::SHL:
9888   case ISD::SRL:
9889     // If we have a constant logical shift that's only used in a comparison
9890     // against zero turn it into an equivalent AND. This allows turning it into
9891     // a TEST instruction later.
9892     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9893         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9894       EVT VT = Op.getValueType();
9895       unsigned BitWidth = VT.getSizeInBits();
9896       unsigned ShAmt = Op->getConstantOperandVal(1);
9897       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9898         break;
9899       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9900                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9901                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9902       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9903         break;
9904       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9905                                 DAG.getConstant(Mask, VT));
9906       DAG.ReplaceAllUsesWith(Op, New);
9907       Op = New;
9908     }
9909     break;
9910
9911   case ISD::AND:
9912     // If the primary and result isn't used, don't bother using X86ISD::AND,
9913     // because a TEST instruction will be better.
9914     if (!hasNonFlagsUse(Op))
9915       break;
9916     // FALL THROUGH
9917   case ISD::SUB:
9918   case ISD::OR:
9919   case ISD::XOR:
9920     // Due to the ISEL shortcoming noted above, be conservative if this op is
9921     // likely to be selected as part of a load-modify-store instruction.
9922     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9923            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9924       if (UI->getOpcode() == ISD::STORE)
9925         goto default_case;
9926
9927     // Otherwise use a regular EFLAGS-setting instruction.
9928     switch (ArithOp.getOpcode()) {
9929     default: llvm_unreachable("unexpected operator!");
9930     case ISD::SUB: Opcode = X86ISD::SUB; break;
9931     case ISD::XOR: Opcode = X86ISD::XOR; break;
9932     case ISD::AND: Opcode = X86ISD::AND; break;
9933     case ISD::OR: {
9934       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9935         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9936         if (EFLAGS.getNode())
9937           return EFLAGS;
9938       }
9939       Opcode = X86ISD::OR;
9940       break;
9941     }
9942     }
9943
9944     NumOperands = 2;
9945     break;
9946   case X86ISD::ADD:
9947   case X86ISD::SUB:
9948   case X86ISD::INC:
9949   case X86ISD::DEC:
9950   case X86ISD::OR:
9951   case X86ISD::XOR:
9952   case X86ISD::AND:
9953     return SDValue(Op.getNode(), 1);
9954   default:
9955   default_case:
9956     break;
9957   }
9958
9959   // If we found that truncation is beneficial, perform the truncation and
9960   // update 'Op'.
9961   if (NeedTruncation) {
9962     EVT VT = Op.getValueType();
9963     SDValue WideVal = Op->getOperand(0);
9964     EVT WideVT = WideVal.getValueType();
9965     unsigned ConvertedOp = 0;
9966     // Use a target machine opcode to prevent further DAGCombine
9967     // optimizations that may separate the arithmetic operations
9968     // from the setcc node.
9969     switch (WideVal.getOpcode()) {
9970       default: break;
9971       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9972       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9973       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9974       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9975       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9976     }
9977
9978     if (ConvertedOp) {
9979       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9980       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9981         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9982         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9983         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9984       }
9985     }
9986   }
9987
9988   if (Opcode == 0)
9989     // Emit a CMP with 0, which is the TEST pattern.
9990     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9991                        DAG.getConstant(0, Op.getValueType()));
9992
9993   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9994   SmallVector<SDValue, 4> Ops;
9995   for (unsigned i = 0; i != NumOperands; ++i)
9996     Ops.push_back(Op.getOperand(i));
9997
9998   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
9999   DAG.ReplaceAllUsesWith(Op, New);
10000   return SDValue(New.getNode(), 1);
10001 }
10002
10003 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10004 /// equivalent.
10005 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10006                                    SDLoc dl, SelectionDAG &DAG) const {
10007   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10008     if (C->getAPIntValue() == 0)
10009       return EmitTest(Op0, X86CC, dl, DAG);
10010
10011      if (Op0.getValueType() == MVT::i1)
10012        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10013   }
10014  
10015   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10016        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10017     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10018     // This avoids subregister aliasing issues. Keep the smaller reference 
10019     // if we're optimizing for size, however, as that'll allow better folding 
10020     // of memory operations.
10021     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10022         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10023              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10024         !Subtarget->isAtom()) {
10025       unsigned ExtendOp =
10026           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10027       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10028       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10029     }
10030     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10031     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10032     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10033                               Op0, Op1);
10034     return SDValue(Sub.getNode(), 1);
10035   }
10036   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10037 }
10038
10039 /// Convert a comparison if required by the subtarget.
10040 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10041                                                  SelectionDAG &DAG) const {
10042   // If the subtarget does not support the FUCOMI instruction, floating-point
10043   // comparisons have to be converted.
10044   if (Subtarget->hasCMov() ||
10045       Cmp.getOpcode() != X86ISD::CMP ||
10046       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10047       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10048     return Cmp;
10049
10050   // The instruction selector will select an FUCOM instruction instead of
10051   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10052   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10053   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10054   SDLoc dl(Cmp);
10055   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10056   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10057   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10058                             DAG.getConstant(8, MVT::i8));
10059   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10060   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10061 }
10062
10063 static bool isAllOnes(SDValue V) {
10064   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10065   return C && C->isAllOnesValue();
10066 }
10067
10068 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10069 /// if it's possible.
10070 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10071                                      SDLoc dl, SelectionDAG &DAG) const {
10072   SDValue Op0 = And.getOperand(0);
10073   SDValue Op1 = And.getOperand(1);
10074   if (Op0.getOpcode() == ISD::TRUNCATE)
10075     Op0 = Op0.getOperand(0);
10076   if (Op1.getOpcode() == ISD::TRUNCATE)
10077     Op1 = Op1.getOperand(0);
10078
10079   SDValue LHS, RHS;
10080   if (Op1.getOpcode() == ISD::SHL)
10081     std::swap(Op0, Op1);
10082   if (Op0.getOpcode() == ISD::SHL) {
10083     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10084       if (And00C->getZExtValue() == 1) {
10085         // If we looked past a truncate, check that it's only truncating away
10086         // known zeros.
10087         unsigned BitWidth = Op0.getValueSizeInBits();
10088         unsigned AndBitWidth = And.getValueSizeInBits();
10089         if (BitWidth > AndBitWidth) {
10090           APInt Zeros, Ones;
10091           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10092           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10093             return SDValue();
10094         }
10095         LHS = Op1;
10096         RHS = Op0.getOperand(1);
10097       }
10098   } else if (Op1.getOpcode() == ISD::Constant) {
10099     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10100     uint64_t AndRHSVal = AndRHS->getZExtValue();
10101     SDValue AndLHS = Op0;
10102
10103     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10104       LHS = AndLHS.getOperand(0);
10105       RHS = AndLHS.getOperand(1);
10106     }
10107
10108     // Use BT if the immediate can't be encoded in a TEST instruction.
10109     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10110       LHS = AndLHS;
10111       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10112     }
10113   }
10114
10115   if (LHS.getNode()) {
10116     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10117     // instruction.  Since the shift amount is in-range-or-undefined, we know
10118     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10119     // the encoding for the i16 version is larger than the i32 version.
10120     // Also promote i16 to i32 for performance / code size reason.
10121     if (LHS.getValueType() == MVT::i8 ||
10122         LHS.getValueType() == MVT::i16)
10123       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10124
10125     // If the operand types disagree, extend the shift amount to match.  Since
10126     // BT ignores high bits (like shifts) we can use anyextend.
10127     if (LHS.getValueType() != RHS.getValueType())
10128       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10129
10130     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10131     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10132     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10133                        DAG.getConstant(Cond, MVT::i8), BT);
10134   }
10135
10136   return SDValue();
10137 }
10138
10139 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10140 /// mask CMPs.
10141 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10142                               SDValue &Op1) {
10143   unsigned SSECC;
10144   bool Swap = false;
10145
10146   // SSE Condition code mapping:
10147   //  0 - EQ
10148   //  1 - LT
10149   //  2 - LE
10150   //  3 - UNORD
10151   //  4 - NEQ
10152   //  5 - NLT
10153   //  6 - NLE
10154   //  7 - ORD
10155   switch (SetCCOpcode) {
10156   default: llvm_unreachable("Unexpected SETCC condition");
10157   case ISD::SETOEQ:
10158   case ISD::SETEQ:  SSECC = 0; break;
10159   case ISD::SETOGT:
10160   case ISD::SETGT:  Swap = true; // Fallthrough
10161   case ISD::SETLT:
10162   case ISD::SETOLT: SSECC = 1; break;
10163   case ISD::SETOGE:
10164   case ISD::SETGE:  Swap = true; // Fallthrough
10165   case ISD::SETLE:
10166   case ISD::SETOLE: SSECC = 2; break;
10167   case ISD::SETUO:  SSECC = 3; break;
10168   case ISD::SETUNE:
10169   case ISD::SETNE:  SSECC = 4; break;
10170   case ISD::SETULE: Swap = true; // Fallthrough
10171   case ISD::SETUGE: SSECC = 5; break;
10172   case ISD::SETULT: Swap = true; // Fallthrough
10173   case ISD::SETUGT: SSECC = 6; break;
10174   case ISD::SETO:   SSECC = 7; break;
10175   case ISD::SETUEQ:
10176   case ISD::SETONE: SSECC = 8; break;
10177   }
10178   if (Swap)
10179     std::swap(Op0, Op1);
10180
10181   return SSECC;
10182 }
10183
10184 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10185 // ones, and then concatenate the result back.
10186 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10187   MVT VT = Op.getSimpleValueType();
10188
10189   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10190          "Unsupported value type for operation");
10191
10192   unsigned NumElems = VT.getVectorNumElements();
10193   SDLoc dl(Op);
10194   SDValue CC = Op.getOperand(2);
10195
10196   // Extract the LHS vectors
10197   SDValue LHS = Op.getOperand(0);
10198   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10199   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10200
10201   // Extract the RHS vectors
10202   SDValue RHS = Op.getOperand(1);
10203   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10204   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10205
10206   // Issue the operation on the smaller types and concatenate the result back
10207   MVT EltVT = VT.getVectorElementType();
10208   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10209   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10210                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10211                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10212 }
10213
10214 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10215                                      const X86Subtarget *Subtarget) {
10216   SDValue Op0 = Op.getOperand(0);
10217   SDValue Op1 = Op.getOperand(1);
10218   SDValue CC = Op.getOperand(2);
10219   MVT VT = Op.getSimpleValueType();
10220   SDLoc dl(Op);
10221
10222   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10223          Op.getValueType().getScalarType() == MVT::i1 &&
10224          "Cannot set masked compare for this operation");
10225
10226   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10227   unsigned  Opc = 0;
10228   bool Unsigned = false;
10229   bool Swap = false;
10230   unsigned SSECC;
10231   switch (SetCCOpcode) {
10232   default: llvm_unreachable("Unexpected SETCC condition");
10233   case ISD::SETNE:  SSECC = 4; break;
10234   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10235   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10236   case ISD::SETLT:  Swap = true; //fall-through
10237   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10238   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10239   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10240   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10241   case ISD::SETULE: Unsigned = true; //fall-through
10242   case ISD::SETLE:  SSECC = 2; break;
10243   }
10244
10245   if (Swap)
10246     std::swap(Op0, Op1);
10247   if (Opc)
10248     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10249   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10250   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10251                      DAG.getConstant(SSECC, MVT::i8));
10252 }
10253
10254 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10255 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10256 /// return an empty value.
10257 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10258 {
10259   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10260   if (!BV)
10261     return SDValue();
10262
10263   MVT VT = Op1.getSimpleValueType();
10264   MVT EVT = VT.getVectorElementType();
10265   unsigned n = VT.getVectorNumElements();
10266   SmallVector<SDValue, 8> ULTOp1;
10267
10268   for (unsigned i = 0; i < n; ++i) {
10269     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10270     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10271       return SDValue();
10272
10273     // Avoid underflow.
10274     APInt Val = Elt->getAPIntValue();
10275     if (Val == 0)
10276       return SDValue();
10277
10278     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10279   }
10280
10281   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10282 }
10283
10284 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10285                            SelectionDAG &DAG) {
10286   SDValue Op0 = Op.getOperand(0);
10287   SDValue Op1 = Op.getOperand(1);
10288   SDValue CC = Op.getOperand(2);
10289   MVT VT = Op.getSimpleValueType();
10290   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10291   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10292   SDLoc dl(Op);
10293
10294   if (isFP) {
10295 #ifndef NDEBUG
10296     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10297     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10298 #endif
10299
10300     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10301     unsigned Opc = X86ISD::CMPP;
10302     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10303       assert(VT.getVectorNumElements() <= 16);
10304       Opc = X86ISD::CMPM;
10305     }
10306     // In the two special cases we can't handle, emit two comparisons.
10307     if (SSECC == 8) {
10308       unsigned CC0, CC1;
10309       unsigned CombineOpc;
10310       if (SetCCOpcode == ISD::SETUEQ) {
10311         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10312       } else {
10313         assert(SetCCOpcode == ISD::SETONE);
10314         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10315       }
10316
10317       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10318                                  DAG.getConstant(CC0, MVT::i8));
10319       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10320                                  DAG.getConstant(CC1, MVT::i8));
10321       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10322     }
10323     // Handle all other FP comparisons here.
10324     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10325                        DAG.getConstant(SSECC, MVT::i8));
10326   }
10327
10328   // Break 256-bit integer vector compare into smaller ones.
10329   if (VT.is256BitVector() && !Subtarget->hasInt256())
10330     return Lower256IntVSETCC(Op, DAG);
10331
10332   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10333   EVT OpVT = Op1.getValueType();
10334   if (Subtarget->hasAVX512()) {
10335     if (Op1.getValueType().is512BitVector() ||
10336         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10337       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10338
10339     // In AVX-512 architecture setcc returns mask with i1 elements,
10340     // But there is no compare instruction for i8 and i16 elements.
10341     // We are not talking about 512-bit operands in this case, these
10342     // types are illegal.
10343     if (MaskResult &&
10344         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10345          OpVT.getVectorElementType().getSizeInBits() >= 8))
10346       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10347                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10348   }
10349
10350   // We are handling one of the integer comparisons here.  Since SSE only has
10351   // GT and EQ comparisons for integer, swapping operands and multiple
10352   // operations may be required for some comparisons.
10353   unsigned Opc;
10354   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10355   bool Subus = false;
10356
10357   switch (SetCCOpcode) {
10358   default: llvm_unreachable("Unexpected SETCC condition");
10359   case ISD::SETNE:  Invert = true;
10360   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10361   case ISD::SETLT:  Swap = true;
10362   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10363   case ISD::SETGE:  Swap = true;
10364   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10365                     Invert = true; break;
10366   case ISD::SETULT: Swap = true;
10367   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10368                     FlipSigns = true; break;
10369   case ISD::SETUGE: Swap = true;
10370   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10371                     FlipSigns = true; Invert = true; break;
10372   }
10373
10374   // Special case: Use min/max operations for SETULE/SETUGE
10375   MVT VET = VT.getVectorElementType();
10376   bool hasMinMax =
10377        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10378     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10379
10380   if (hasMinMax) {
10381     switch (SetCCOpcode) {
10382     default: break;
10383     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10384     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10385     }
10386
10387     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10388   }
10389
10390   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10391   if (!MinMax && hasSubus) {
10392     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10393     // Op0 u<= Op1:
10394     //   t = psubus Op0, Op1
10395     //   pcmpeq t, <0..0>
10396     switch (SetCCOpcode) {
10397     default: break;
10398     case ISD::SETULT: {
10399       // If the comparison is against a constant we can turn this into a
10400       // setule.  With psubus, setule does not require a swap.  This is
10401       // beneficial because the constant in the register is no longer
10402       // destructed as the destination so it can be hoisted out of a loop.
10403       // Only do this pre-AVX since vpcmp* is no longer destructive.
10404       if (Subtarget->hasAVX())
10405         break;
10406       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10407       if (ULEOp1.getNode()) {
10408         Op1 = ULEOp1;
10409         Subus = true; Invert = false; Swap = false;
10410       }
10411       break;
10412     }
10413     // Psubus is better than flip-sign because it requires no inversion.
10414     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10415     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10416     }
10417
10418     if (Subus) {
10419       Opc = X86ISD::SUBUS;
10420       FlipSigns = false;
10421     }
10422   }
10423
10424   if (Swap)
10425     std::swap(Op0, Op1);
10426
10427   // Check that the operation in question is available (most are plain SSE2,
10428   // but PCMPGTQ and PCMPEQQ have different requirements).
10429   if (VT == MVT::v2i64) {
10430     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10431       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10432
10433       // First cast everything to the right type.
10434       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10435       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10436
10437       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10438       // bits of the inputs before performing those operations. The lower
10439       // compare is always unsigned.
10440       SDValue SB;
10441       if (FlipSigns) {
10442         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10443       } else {
10444         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10445         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10446         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10447                          Sign, Zero, Sign, Zero);
10448       }
10449       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10450       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10451
10452       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10453       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10454       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10455
10456       // Create masks for only the low parts/high parts of the 64 bit integers.
10457       static const int MaskHi[] = { 1, 1, 3, 3 };
10458       static const int MaskLo[] = { 0, 0, 2, 2 };
10459       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10460       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10461       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10462
10463       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10464       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10465
10466       if (Invert)
10467         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10468
10469       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10470     }
10471
10472     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10473       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10474       // pcmpeqd + pshufd + pand.
10475       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10476
10477       // First cast everything to the right type.
10478       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10479       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10480
10481       // Do the compare.
10482       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10483
10484       // Make sure the lower and upper halves are both all-ones.
10485       static const int Mask[] = { 1, 0, 3, 2 };
10486       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10487       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10488
10489       if (Invert)
10490         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10491
10492       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10493     }
10494   }
10495
10496   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10497   // bits of the inputs before performing those operations.
10498   if (FlipSigns) {
10499     EVT EltVT = VT.getVectorElementType();
10500     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10501     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10502     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10503   }
10504
10505   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10506
10507   // If the logical-not of the result is required, perform that now.
10508   if (Invert)
10509     Result = DAG.getNOT(dl, Result, VT);
10510
10511   if (MinMax)
10512     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10513
10514   if (Subus)
10515     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10516                          getZeroVector(VT, Subtarget, DAG, dl));
10517
10518   return Result;
10519 }
10520
10521 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10522
10523   MVT VT = Op.getSimpleValueType();
10524
10525   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10526
10527   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10528          && "SetCC type must be 8-bit or 1-bit integer");
10529   SDValue Op0 = Op.getOperand(0);
10530   SDValue Op1 = Op.getOperand(1);
10531   SDLoc dl(Op);
10532   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10533
10534   // Optimize to BT if possible.
10535   // Lower (X & (1 << N)) == 0 to BT(X, N).
10536   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10537   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10538   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10539       Op1.getOpcode() == ISD::Constant &&
10540       cast<ConstantSDNode>(Op1)->isNullValue() &&
10541       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10542     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10543     if (NewSetCC.getNode())
10544       return NewSetCC;
10545   }
10546
10547   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10548   // these.
10549   if (Op1.getOpcode() == ISD::Constant &&
10550       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10551        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10552       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10553
10554     // If the input is a setcc, then reuse the input setcc or use a new one with
10555     // the inverted condition.
10556     if (Op0.getOpcode() == X86ISD::SETCC) {
10557       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10558       bool Invert = (CC == ISD::SETNE) ^
10559         cast<ConstantSDNode>(Op1)->isNullValue();
10560       if (!Invert)
10561         return Op0;
10562
10563       CCode = X86::GetOppositeBranchCondition(CCode);
10564       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10565                                   DAG.getConstant(CCode, MVT::i8),
10566                                   Op0.getOperand(1));
10567       if (VT == MVT::i1)
10568         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10569       return SetCC;
10570     }
10571   }
10572   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10573       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10574       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10575
10576     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10577     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10578   }
10579
10580   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10581   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10582   if (X86CC == X86::COND_INVALID)
10583     return SDValue();
10584
10585   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10586   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10587   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10588                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10589   if (VT == MVT::i1)
10590     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10591   return SetCC;
10592 }
10593
10594 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10595 static bool isX86LogicalCmp(SDValue Op) {
10596   unsigned Opc = Op.getNode()->getOpcode();
10597   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10598       Opc == X86ISD::SAHF)
10599     return true;
10600   if (Op.getResNo() == 1 &&
10601       (Opc == X86ISD::ADD ||
10602        Opc == X86ISD::SUB ||
10603        Opc == X86ISD::ADC ||
10604        Opc == X86ISD::SBB ||
10605        Opc == X86ISD::SMUL ||
10606        Opc == X86ISD::UMUL ||
10607        Opc == X86ISD::INC ||
10608        Opc == X86ISD::DEC ||
10609        Opc == X86ISD::OR ||
10610        Opc == X86ISD::XOR ||
10611        Opc == X86ISD::AND))
10612     return true;
10613
10614   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10615     return true;
10616
10617   return false;
10618 }
10619
10620 static bool isZero(SDValue V) {
10621   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10622   return C && C->isNullValue();
10623 }
10624
10625 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10626   if (V.getOpcode() != ISD::TRUNCATE)
10627     return false;
10628
10629   SDValue VOp0 = V.getOperand(0);
10630   unsigned InBits = VOp0.getValueSizeInBits();
10631   unsigned Bits = V.getValueSizeInBits();
10632   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10633 }
10634
10635 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10636   bool addTest = true;
10637   SDValue Cond  = Op.getOperand(0);
10638   SDValue Op1 = Op.getOperand(1);
10639   SDValue Op2 = Op.getOperand(2);
10640   SDLoc DL(Op);
10641   EVT VT = Op1.getValueType();
10642   SDValue CC;
10643
10644   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10645   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10646   // sequence later on.
10647   if (Cond.getOpcode() == ISD::SETCC &&
10648       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10649        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10650       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10651     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10652     int SSECC = translateX86FSETCC(
10653         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10654
10655     if (SSECC != 8) {
10656       if (Subtarget->hasAVX512()) {
10657         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10658                                   DAG.getConstant(SSECC, MVT::i8));
10659         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10660       }
10661       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10662                                 DAG.getConstant(SSECC, MVT::i8));
10663       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10664       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10665       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10666     }
10667   }
10668
10669   if (Cond.getOpcode() == ISD::SETCC) {
10670     SDValue NewCond = LowerSETCC(Cond, DAG);
10671     if (NewCond.getNode())
10672       Cond = NewCond;
10673   }
10674
10675   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10676   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10677   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10678   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10679   if (Cond.getOpcode() == X86ISD::SETCC &&
10680       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10681       isZero(Cond.getOperand(1).getOperand(1))) {
10682     SDValue Cmp = Cond.getOperand(1);
10683
10684     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10685
10686     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10687         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10688       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10689
10690       SDValue CmpOp0 = Cmp.getOperand(0);
10691       // Apply further optimizations for special cases
10692       // (select (x != 0), -1, 0) -> neg & sbb
10693       // (select (x == 0), 0, -1) -> neg & sbb
10694       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10695         if (YC->isNullValue() &&
10696             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10697           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10698           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10699                                     DAG.getConstant(0, CmpOp0.getValueType()),
10700                                     CmpOp0);
10701           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10702                                     DAG.getConstant(X86::COND_B, MVT::i8),
10703                                     SDValue(Neg.getNode(), 1));
10704           return Res;
10705         }
10706
10707       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10708                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10709       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10710
10711       SDValue Res =   // Res = 0 or -1.
10712         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10713                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10714
10715       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10716         Res = DAG.getNOT(DL, Res, Res.getValueType());
10717
10718       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10719       if (!N2C || !N2C->isNullValue())
10720         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10721       return Res;
10722     }
10723   }
10724
10725   // Look past (and (setcc_carry (cmp ...)), 1).
10726   if (Cond.getOpcode() == ISD::AND &&
10727       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10728     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10729     if (C && C->getAPIntValue() == 1)
10730       Cond = Cond.getOperand(0);
10731   }
10732
10733   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10734   // setting operand in place of the X86ISD::SETCC.
10735   unsigned CondOpcode = Cond.getOpcode();
10736   if (CondOpcode == X86ISD::SETCC ||
10737       CondOpcode == X86ISD::SETCC_CARRY) {
10738     CC = Cond.getOperand(0);
10739
10740     SDValue Cmp = Cond.getOperand(1);
10741     unsigned Opc = Cmp.getOpcode();
10742     MVT VT = Op.getSimpleValueType();
10743
10744     bool IllegalFPCMov = false;
10745     if (VT.isFloatingPoint() && !VT.isVector() &&
10746         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10747       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10748
10749     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10750         Opc == X86ISD::BT) { // FIXME
10751       Cond = Cmp;
10752       addTest = false;
10753     }
10754   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10755              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10756              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10757               Cond.getOperand(0).getValueType() != MVT::i8)) {
10758     SDValue LHS = Cond.getOperand(0);
10759     SDValue RHS = Cond.getOperand(1);
10760     unsigned X86Opcode;
10761     unsigned X86Cond;
10762     SDVTList VTs;
10763     switch (CondOpcode) {
10764     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10765     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10766     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10767     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10768     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10769     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10770     default: llvm_unreachable("unexpected overflowing operator");
10771     }
10772     if (CondOpcode == ISD::UMULO)
10773       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10774                           MVT::i32);
10775     else
10776       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10777
10778     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10779
10780     if (CondOpcode == ISD::UMULO)
10781       Cond = X86Op.getValue(2);
10782     else
10783       Cond = X86Op.getValue(1);
10784
10785     CC = DAG.getConstant(X86Cond, MVT::i8);
10786     addTest = false;
10787   }
10788
10789   if (addTest) {
10790     // Look pass the truncate if the high bits are known zero.
10791     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10792         Cond = Cond.getOperand(0);
10793
10794     // We know the result of AND is compared against zero. Try to match
10795     // it to BT.
10796     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10797       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10798       if (NewSetCC.getNode()) {
10799         CC = NewSetCC.getOperand(0);
10800         Cond = NewSetCC.getOperand(1);
10801         addTest = false;
10802       }
10803     }
10804   }
10805
10806   if (addTest) {
10807     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10808     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10809   }
10810
10811   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10812   // a <  b ?  0 : -1 -> RES = setcc_carry
10813   // a >= b ? -1 :  0 -> RES = setcc_carry
10814   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10815   if (Cond.getOpcode() == X86ISD::SUB) {
10816     Cond = ConvertCmpIfNecessary(Cond, DAG);
10817     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10818
10819     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10820         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10821       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10822                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10823       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10824         return DAG.getNOT(DL, Res, Res.getValueType());
10825       return Res;
10826     }
10827   }
10828
10829   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10830   // widen the cmov and push the truncate through. This avoids introducing a new
10831   // branch during isel and doesn't add any extensions.
10832   if (Op.getValueType() == MVT::i8 &&
10833       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10834     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10835     if (T1.getValueType() == T2.getValueType() &&
10836         // Blacklist CopyFromReg to avoid partial register stalls.
10837         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10838       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10839       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10840       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10841     }
10842   }
10843
10844   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10845   // condition is true.
10846   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10847   SDValue Ops[] = { Op2, Op1, CC, Cond };
10848   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10849 }
10850
10851 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10852   MVT VT = Op->getSimpleValueType(0);
10853   SDValue In = Op->getOperand(0);
10854   MVT InVT = In.getSimpleValueType();
10855   SDLoc dl(Op);
10856
10857   unsigned int NumElts = VT.getVectorNumElements();
10858   if (NumElts != 8 && NumElts != 16)
10859     return SDValue();
10860
10861   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10862     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10863
10864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10865   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10866
10867   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10868   Constant *C = ConstantInt::get(*DAG.getContext(),
10869     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10870
10871   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10872   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10873   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10874                           MachinePointerInfo::getConstantPool(),
10875                           false, false, false, Alignment);
10876   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10877   if (VT.is512BitVector())
10878     return Brcst;
10879   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10880 }
10881
10882 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10883                                 SelectionDAG &DAG) {
10884   MVT VT = Op->getSimpleValueType(0);
10885   SDValue In = Op->getOperand(0);
10886   MVT InVT = In.getSimpleValueType();
10887   SDLoc dl(Op);
10888
10889   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10890     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10891
10892   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10893       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10894       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10895     return SDValue();
10896
10897   if (Subtarget->hasInt256())
10898     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10899
10900   // Optimize vectors in AVX mode
10901   // Sign extend  v8i16 to v8i32 and
10902   //              v4i32 to v4i64
10903   //
10904   // Divide input vector into two parts
10905   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10906   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10907   // concat the vectors to original VT
10908
10909   unsigned NumElems = InVT.getVectorNumElements();
10910   SDValue Undef = DAG.getUNDEF(InVT);
10911
10912   SmallVector<int,8> ShufMask1(NumElems, -1);
10913   for (unsigned i = 0; i != NumElems/2; ++i)
10914     ShufMask1[i] = i;
10915
10916   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10917
10918   SmallVector<int,8> ShufMask2(NumElems, -1);
10919   for (unsigned i = 0; i != NumElems/2; ++i)
10920     ShufMask2[i] = i + NumElems/2;
10921
10922   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10923
10924   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10925                                 VT.getVectorNumElements()/2);
10926
10927   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10928   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10929
10930   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10931 }
10932
10933 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10934 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10935 // from the AND / OR.
10936 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10937   Opc = Op.getOpcode();
10938   if (Opc != ISD::OR && Opc != ISD::AND)
10939     return false;
10940   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10941           Op.getOperand(0).hasOneUse() &&
10942           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10943           Op.getOperand(1).hasOneUse());
10944 }
10945
10946 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10947 // 1 and that the SETCC node has a single use.
10948 static bool isXor1OfSetCC(SDValue Op) {
10949   if (Op.getOpcode() != ISD::XOR)
10950     return false;
10951   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10952   if (N1C && N1C->getAPIntValue() == 1) {
10953     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10954       Op.getOperand(0).hasOneUse();
10955   }
10956   return false;
10957 }
10958
10959 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10960   bool addTest = true;
10961   SDValue Chain = Op.getOperand(0);
10962   SDValue Cond  = Op.getOperand(1);
10963   SDValue Dest  = Op.getOperand(2);
10964   SDLoc dl(Op);
10965   SDValue CC;
10966   bool Inverted = false;
10967
10968   if (Cond.getOpcode() == ISD::SETCC) {
10969     // Check for setcc([su]{add,sub,mul}o == 0).
10970     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10971         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10972         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10973         Cond.getOperand(0).getResNo() == 1 &&
10974         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10975          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10976          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10977          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10978          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10979          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10980       Inverted = true;
10981       Cond = Cond.getOperand(0);
10982     } else {
10983       SDValue NewCond = LowerSETCC(Cond, DAG);
10984       if (NewCond.getNode())
10985         Cond = NewCond;
10986     }
10987   }
10988 #if 0
10989   // FIXME: LowerXALUO doesn't handle these!!
10990   else if (Cond.getOpcode() == X86ISD::ADD  ||
10991            Cond.getOpcode() == X86ISD::SUB  ||
10992            Cond.getOpcode() == X86ISD::SMUL ||
10993            Cond.getOpcode() == X86ISD::UMUL)
10994     Cond = LowerXALUO(Cond, DAG);
10995 #endif
10996
10997   // Look pass (and (setcc_carry (cmp ...)), 1).
10998   if (Cond.getOpcode() == ISD::AND &&
10999       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11000     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11001     if (C && C->getAPIntValue() == 1)
11002       Cond = Cond.getOperand(0);
11003   }
11004
11005   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11006   // setting operand in place of the X86ISD::SETCC.
11007   unsigned CondOpcode = Cond.getOpcode();
11008   if (CondOpcode == X86ISD::SETCC ||
11009       CondOpcode == X86ISD::SETCC_CARRY) {
11010     CC = Cond.getOperand(0);
11011
11012     SDValue Cmp = Cond.getOperand(1);
11013     unsigned Opc = Cmp.getOpcode();
11014     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11015     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11016       Cond = Cmp;
11017       addTest = false;
11018     } else {
11019       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11020       default: break;
11021       case X86::COND_O:
11022       case X86::COND_B:
11023         // These can only come from an arithmetic instruction with overflow,
11024         // e.g. SADDO, UADDO.
11025         Cond = Cond.getNode()->getOperand(1);
11026         addTest = false;
11027         break;
11028       }
11029     }
11030   }
11031   CondOpcode = Cond.getOpcode();
11032   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11033       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11034       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11035        Cond.getOperand(0).getValueType() != MVT::i8)) {
11036     SDValue LHS = Cond.getOperand(0);
11037     SDValue RHS = Cond.getOperand(1);
11038     unsigned X86Opcode;
11039     unsigned X86Cond;
11040     SDVTList VTs;
11041     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11042     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11043     // X86ISD::INC).
11044     switch (CondOpcode) {
11045     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11046     case ISD::SADDO:
11047       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11048         if (C->isOne()) {
11049           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11050           break;
11051         }
11052       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11053     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11054     case ISD::SSUBO:
11055       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11056         if (C->isOne()) {
11057           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11058           break;
11059         }
11060       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11061     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11062     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11063     default: llvm_unreachable("unexpected overflowing operator");
11064     }
11065     if (Inverted)
11066       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11067     if (CondOpcode == ISD::UMULO)
11068       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11069                           MVT::i32);
11070     else
11071       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11072
11073     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11074
11075     if (CondOpcode == ISD::UMULO)
11076       Cond = X86Op.getValue(2);
11077     else
11078       Cond = X86Op.getValue(1);
11079
11080     CC = DAG.getConstant(X86Cond, MVT::i8);
11081     addTest = false;
11082   } else {
11083     unsigned CondOpc;
11084     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11085       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11086       if (CondOpc == ISD::OR) {
11087         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11088         // two branches instead of an explicit OR instruction with a
11089         // separate test.
11090         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11091             isX86LogicalCmp(Cmp)) {
11092           CC = Cond.getOperand(0).getOperand(0);
11093           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11094                               Chain, Dest, CC, Cmp);
11095           CC = Cond.getOperand(1).getOperand(0);
11096           Cond = Cmp;
11097           addTest = false;
11098         }
11099       } else { // ISD::AND
11100         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11101         // two branches instead of an explicit AND instruction with a
11102         // separate test. However, we only do this if this block doesn't
11103         // have a fall-through edge, because this requires an explicit
11104         // jmp when the condition is false.
11105         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11106             isX86LogicalCmp(Cmp) &&
11107             Op.getNode()->hasOneUse()) {
11108           X86::CondCode CCode =
11109             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11110           CCode = X86::GetOppositeBranchCondition(CCode);
11111           CC = DAG.getConstant(CCode, MVT::i8);
11112           SDNode *User = *Op.getNode()->use_begin();
11113           // Look for an unconditional branch following this conditional branch.
11114           // We need this because we need to reverse the successors in order
11115           // to implement FCMP_OEQ.
11116           if (User->getOpcode() == ISD::BR) {
11117             SDValue FalseBB = User->getOperand(1);
11118             SDNode *NewBR =
11119               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11120             assert(NewBR == User);
11121             (void)NewBR;
11122             Dest = FalseBB;
11123
11124             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11125                                 Chain, Dest, CC, Cmp);
11126             X86::CondCode CCode =
11127               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11128             CCode = X86::GetOppositeBranchCondition(CCode);
11129             CC = DAG.getConstant(CCode, MVT::i8);
11130             Cond = Cmp;
11131             addTest = false;
11132           }
11133         }
11134       }
11135     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11136       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11137       // It should be transformed during dag combiner except when the condition
11138       // is set by a arithmetics with overflow node.
11139       X86::CondCode CCode =
11140         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11141       CCode = X86::GetOppositeBranchCondition(CCode);
11142       CC = DAG.getConstant(CCode, MVT::i8);
11143       Cond = Cond.getOperand(0).getOperand(1);
11144       addTest = false;
11145     } else if (Cond.getOpcode() == ISD::SETCC &&
11146                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11147       // For FCMP_OEQ, we can emit
11148       // two branches instead of an explicit AND instruction with a
11149       // separate test. However, we only do this if this block doesn't
11150       // have a fall-through edge, because this requires an explicit
11151       // jmp when the condition is false.
11152       if (Op.getNode()->hasOneUse()) {
11153         SDNode *User = *Op.getNode()->use_begin();
11154         // Look for an unconditional branch following this conditional branch.
11155         // We need this because we need to reverse the successors in order
11156         // to implement FCMP_OEQ.
11157         if (User->getOpcode() == ISD::BR) {
11158           SDValue FalseBB = User->getOperand(1);
11159           SDNode *NewBR =
11160             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11161           assert(NewBR == User);
11162           (void)NewBR;
11163           Dest = FalseBB;
11164
11165           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11166                                     Cond.getOperand(0), Cond.getOperand(1));
11167           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11168           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11169           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11170                               Chain, Dest, CC, Cmp);
11171           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11172           Cond = Cmp;
11173           addTest = false;
11174         }
11175       }
11176     } else if (Cond.getOpcode() == ISD::SETCC &&
11177                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11178       // For FCMP_UNE, we can emit
11179       // two branches instead of an explicit AND instruction with a
11180       // separate test. However, we only do this if this block doesn't
11181       // have a fall-through edge, because this requires an explicit
11182       // jmp when the condition is false.
11183       if (Op.getNode()->hasOneUse()) {
11184         SDNode *User = *Op.getNode()->use_begin();
11185         // Look for an unconditional branch following this conditional branch.
11186         // We need this because we need to reverse the successors in order
11187         // to implement FCMP_UNE.
11188         if (User->getOpcode() == ISD::BR) {
11189           SDValue FalseBB = User->getOperand(1);
11190           SDNode *NewBR =
11191             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11192           assert(NewBR == User);
11193           (void)NewBR;
11194
11195           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11196                                     Cond.getOperand(0), Cond.getOperand(1));
11197           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11198           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11199           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11200                               Chain, Dest, CC, Cmp);
11201           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11202           Cond = Cmp;
11203           addTest = false;
11204           Dest = FalseBB;
11205         }
11206       }
11207     }
11208   }
11209
11210   if (addTest) {
11211     // Look pass the truncate if the high bits are known zero.
11212     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11213         Cond = Cond.getOperand(0);
11214
11215     // We know the result of AND is compared against zero. Try to match
11216     // it to BT.
11217     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11218       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11219       if (NewSetCC.getNode()) {
11220         CC = NewSetCC.getOperand(0);
11221         Cond = NewSetCC.getOperand(1);
11222         addTest = false;
11223       }
11224     }
11225   }
11226
11227   if (addTest) {
11228     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11229     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11230   }
11231   Cond = ConvertCmpIfNecessary(Cond, DAG);
11232   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11233                      Chain, Dest, CC, Cond);
11234 }
11235
11236 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11237 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11238 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11239 // that the guard pages used by the OS virtual memory manager are allocated in
11240 // correct sequence.
11241 SDValue
11242 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11243                                            SelectionDAG &DAG) const {
11244   MachineFunction &MF = DAG.getMachineFunction();
11245   bool SplitStack = MF.shouldSplitStack();
11246   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11247                SplitStack;
11248   SDLoc dl(Op);
11249
11250   if (!Lower) {
11251     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11252     SDNode* Node = Op.getNode();
11253
11254     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11255     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11256         " not tell us which reg is the stack pointer!");
11257     EVT VT = Node->getValueType(0);
11258     SDValue Tmp1 = SDValue(Node, 0);
11259     SDValue Tmp2 = SDValue(Node, 1);
11260     SDValue Tmp3 = Node->getOperand(2);
11261     SDValue Chain = Tmp1.getOperand(0);
11262
11263     // Chain the dynamic stack allocation so that it doesn't modify the stack
11264     // pointer when other instructions are using the stack.
11265     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11266         SDLoc(Node));
11267
11268     SDValue Size = Tmp2.getOperand(1);
11269     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11270     Chain = SP.getValue(1);
11271     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11272     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11273     unsigned StackAlign = TFI.getStackAlignment();
11274     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11275     if (Align > StackAlign)
11276       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11277           DAG.getConstant(-(uint64_t)Align, VT));
11278     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11279
11280     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11281         DAG.getIntPtrConstant(0, true), SDValue(),
11282         SDLoc(Node));
11283
11284     SDValue Ops[2] = { Tmp1, Tmp2 };
11285     return DAG.getMergeValues(Ops, dl);
11286   }
11287
11288   // Get the inputs.
11289   SDValue Chain = Op.getOperand(0);
11290   SDValue Size  = Op.getOperand(1);
11291   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11292   EVT VT = Op.getNode()->getValueType(0);
11293
11294   bool Is64Bit = Subtarget->is64Bit();
11295   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11296
11297   if (SplitStack) {
11298     MachineRegisterInfo &MRI = MF.getRegInfo();
11299
11300     if (Is64Bit) {
11301       // The 64 bit implementation of segmented stacks needs to clobber both r10
11302       // r11. This makes it impossible to use it along with nested parameters.
11303       const Function *F = MF.getFunction();
11304
11305       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11306            I != E; ++I)
11307         if (I->hasNestAttr())
11308           report_fatal_error("Cannot use segmented stacks with functions that "
11309                              "have nested arguments.");
11310     }
11311
11312     const TargetRegisterClass *AddrRegClass =
11313       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11314     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11315     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11316     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11317                                 DAG.getRegister(Vreg, SPTy));
11318     SDValue Ops1[2] = { Value, Chain };
11319     return DAG.getMergeValues(Ops1, dl);
11320   } else {
11321     SDValue Flag;
11322     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11323
11324     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11325     Flag = Chain.getValue(1);
11326     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11327
11328     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11329
11330     const X86RegisterInfo *RegInfo =
11331       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11332     unsigned SPReg = RegInfo->getStackRegister();
11333     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11334     Chain = SP.getValue(1);
11335
11336     if (Align) {
11337       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11338                        DAG.getConstant(-(uint64_t)Align, VT));
11339       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11340     }
11341
11342     SDValue Ops1[2] = { SP, Chain };
11343     return DAG.getMergeValues(Ops1, dl);
11344   }
11345 }
11346
11347 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11348   MachineFunction &MF = DAG.getMachineFunction();
11349   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11350
11351   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11352   SDLoc DL(Op);
11353
11354   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11355     // vastart just stores the address of the VarArgsFrameIndex slot into the
11356     // memory location argument.
11357     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11358                                    getPointerTy());
11359     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11360                         MachinePointerInfo(SV), false, false, 0);
11361   }
11362
11363   // __va_list_tag:
11364   //   gp_offset         (0 - 6 * 8)
11365   //   fp_offset         (48 - 48 + 8 * 16)
11366   //   overflow_arg_area (point to parameters coming in memory).
11367   //   reg_save_area
11368   SmallVector<SDValue, 8> MemOps;
11369   SDValue FIN = Op.getOperand(1);
11370   // Store gp_offset
11371   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11372                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11373                                                MVT::i32),
11374                                FIN, MachinePointerInfo(SV), false, false, 0);
11375   MemOps.push_back(Store);
11376
11377   // Store fp_offset
11378   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11379                     FIN, DAG.getIntPtrConstant(4));
11380   Store = DAG.getStore(Op.getOperand(0), DL,
11381                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11382                                        MVT::i32),
11383                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11384   MemOps.push_back(Store);
11385
11386   // Store ptr to overflow_arg_area
11387   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11388                     FIN, DAG.getIntPtrConstant(4));
11389   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11390                                     getPointerTy());
11391   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11392                        MachinePointerInfo(SV, 8),
11393                        false, false, 0);
11394   MemOps.push_back(Store);
11395
11396   // Store ptr to reg_save_area.
11397   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11398                     FIN, DAG.getIntPtrConstant(8));
11399   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11400                                     getPointerTy());
11401   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11402                        MachinePointerInfo(SV, 16), false, false, 0);
11403   MemOps.push_back(Store);
11404   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11405 }
11406
11407 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11408   assert(Subtarget->is64Bit() &&
11409          "LowerVAARG only handles 64-bit va_arg!");
11410   assert((Subtarget->isTargetLinux() ||
11411           Subtarget->isTargetDarwin()) &&
11412           "Unhandled target in LowerVAARG");
11413   assert(Op.getNode()->getNumOperands() == 4);
11414   SDValue Chain = Op.getOperand(0);
11415   SDValue SrcPtr = Op.getOperand(1);
11416   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11417   unsigned Align = Op.getConstantOperandVal(3);
11418   SDLoc dl(Op);
11419
11420   EVT ArgVT = Op.getNode()->getValueType(0);
11421   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11422   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11423   uint8_t ArgMode;
11424
11425   // Decide which area this value should be read from.
11426   // TODO: Implement the AMD64 ABI in its entirety. This simple
11427   // selection mechanism works only for the basic types.
11428   if (ArgVT == MVT::f80) {
11429     llvm_unreachable("va_arg for f80 not yet implemented");
11430   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11431     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11432   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11433     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11434   } else {
11435     llvm_unreachable("Unhandled argument type in LowerVAARG");
11436   }
11437
11438   if (ArgMode == 2) {
11439     // Sanity Check: Make sure using fp_offset makes sense.
11440     assert(!getTargetMachine().Options.UseSoftFloat &&
11441            !(DAG.getMachineFunction()
11442                 .getFunction()->getAttributes()
11443                 .hasAttribute(AttributeSet::FunctionIndex,
11444                               Attribute::NoImplicitFloat)) &&
11445            Subtarget->hasSSE1());
11446   }
11447
11448   // Insert VAARG_64 node into the DAG
11449   // VAARG_64 returns two values: Variable Argument Address, Chain
11450   SmallVector<SDValue, 11> InstOps;
11451   InstOps.push_back(Chain);
11452   InstOps.push_back(SrcPtr);
11453   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11454   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11455   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11456   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11457   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11458                                           VTs, InstOps, MVT::i64,
11459                                           MachinePointerInfo(SV),
11460                                           /*Align=*/0,
11461                                           /*Volatile=*/false,
11462                                           /*ReadMem=*/true,
11463                                           /*WriteMem=*/true);
11464   Chain = VAARG.getValue(1);
11465
11466   // Load the next argument and return it
11467   return DAG.getLoad(ArgVT, dl,
11468                      Chain,
11469                      VAARG,
11470                      MachinePointerInfo(),
11471                      false, false, false, 0);
11472 }
11473
11474 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11475                            SelectionDAG &DAG) {
11476   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11477   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11478   SDValue Chain = Op.getOperand(0);
11479   SDValue DstPtr = Op.getOperand(1);
11480   SDValue SrcPtr = Op.getOperand(2);
11481   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11482   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11483   SDLoc DL(Op);
11484
11485   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11486                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11487                        false,
11488                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11489 }
11490
11491 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11492 // amount is a constant. Takes immediate version of shift as input.
11493 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11494                                           SDValue SrcOp, uint64_t ShiftAmt,
11495                                           SelectionDAG &DAG) {
11496   MVT ElementType = VT.getVectorElementType();
11497
11498   // Check for ShiftAmt >= element width
11499   if (ShiftAmt >= ElementType.getSizeInBits()) {
11500     if (Opc == X86ISD::VSRAI)
11501       ShiftAmt = ElementType.getSizeInBits() - 1;
11502     else
11503       return DAG.getConstant(0, VT);
11504   }
11505
11506   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11507          && "Unknown target vector shift-by-constant node");
11508
11509   // Fold this packed vector shift into a build vector if SrcOp is a
11510   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11511   if (VT == SrcOp.getSimpleValueType() &&
11512       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11513     SmallVector<SDValue, 8> Elts;
11514     unsigned NumElts = SrcOp->getNumOperands();
11515     ConstantSDNode *ND;
11516
11517     switch(Opc) {
11518     default: llvm_unreachable(nullptr);
11519     case X86ISD::VSHLI:
11520       for (unsigned i=0; i!=NumElts; ++i) {
11521         SDValue CurrentOp = SrcOp->getOperand(i);
11522         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11523           Elts.push_back(CurrentOp);
11524           continue;
11525         }
11526         ND = cast<ConstantSDNode>(CurrentOp);
11527         const APInt &C = ND->getAPIntValue();
11528         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11529       }
11530       break;
11531     case X86ISD::VSRLI:
11532       for (unsigned i=0; i!=NumElts; ++i) {
11533         SDValue CurrentOp = SrcOp->getOperand(i);
11534         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11535           Elts.push_back(CurrentOp);
11536           continue;
11537         }
11538         ND = cast<ConstantSDNode>(CurrentOp);
11539         const APInt &C = ND->getAPIntValue();
11540         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11541       }
11542       break;
11543     case X86ISD::VSRAI:
11544       for (unsigned i=0; i!=NumElts; ++i) {
11545         SDValue CurrentOp = SrcOp->getOperand(i);
11546         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11547           Elts.push_back(CurrentOp);
11548           continue;
11549         }
11550         ND = cast<ConstantSDNode>(CurrentOp);
11551         const APInt &C = ND->getAPIntValue();
11552         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11553       }
11554       break;
11555     }
11556
11557     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11558   }
11559
11560   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11561 }
11562
11563 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11564 // may or may not be a constant. Takes immediate version of shift as input.
11565 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11566                                    SDValue SrcOp, SDValue ShAmt,
11567                                    SelectionDAG &DAG) {
11568   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11569
11570   // Catch shift-by-constant.
11571   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11572     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11573                                       CShAmt->getZExtValue(), DAG);
11574
11575   // Change opcode to non-immediate version
11576   switch (Opc) {
11577     default: llvm_unreachable("Unknown target vector shift node");
11578     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11579     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11580     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11581   }
11582
11583   // Need to build a vector containing shift amount
11584   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11585   SDValue ShOps[4];
11586   ShOps[0] = ShAmt;
11587   ShOps[1] = DAG.getConstant(0, MVT::i32);
11588   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11589   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11590
11591   // The return type has to be a 128-bit type with the same element
11592   // type as the input type.
11593   MVT EltVT = VT.getVectorElementType();
11594   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11595
11596   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11597   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11598 }
11599
11600 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11601   SDLoc dl(Op);
11602   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11603   switch (IntNo) {
11604   default: return SDValue();    // Don't custom lower most intrinsics.
11605   // Comparison intrinsics.
11606   case Intrinsic::x86_sse_comieq_ss:
11607   case Intrinsic::x86_sse_comilt_ss:
11608   case Intrinsic::x86_sse_comile_ss:
11609   case Intrinsic::x86_sse_comigt_ss:
11610   case Intrinsic::x86_sse_comige_ss:
11611   case Intrinsic::x86_sse_comineq_ss:
11612   case Intrinsic::x86_sse_ucomieq_ss:
11613   case Intrinsic::x86_sse_ucomilt_ss:
11614   case Intrinsic::x86_sse_ucomile_ss:
11615   case Intrinsic::x86_sse_ucomigt_ss:
11616   case Intrinsic::x86_sse_ucomige_ss:
11617   case Intrinsic::x86_sse_ucomineq_ss:
11618   case Intrinsic::x86_sse2_comieq_sd:
11619   case Intrinsic::x86_sse2_comilt_sd:
11620   case Intrinsic::x86_sse2_comile_sd:
11621   case Intrinsic::x86_sse2_comigt_sd:
11622   case Intrinsic::x86_sse2_comige_sd:
11623   case Intrinsic::x86_sse2_comineq_sd:
11624   case Intrinsic::x86_sse2_ucomieq_sd:
11625   case Intrinsic::x86_sse2_ucomilt_sd:
11626   case Intrinsic::x86_sse2_ucomile_sd:
11627   case Intrinsic::x86_sse2_ucomigt_sd:
11628   case Intrinsic::x86_sse2_ucomige_sd:
11629   case Intrinsic::x86_sse2_ucomineq_sd: {
11630     unsigned Opc;
11631     ISD::CondCode CC;
11632     switch (IntNo) {
11633     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11634     case Intrinsic::x86_sse_comieq_ss:
11635     case Intrinsic::x86_sse2_comieq_sd:
11636       Opc = X86ISD::COMI;
11637       CC = ISD::SETEQ;
11638       break;
11639     case Intrinsic::x86_sse_comilt_ss:
11640     case Intrinsic::x86_sse2_comilt_sd:
11641       Opc = X86ISD::COMI;
11642       CC = ISD::SETLT;
11643       break;
11644     case Intrinsic::x86_sse_comile_ss:
11645     case Intrinsic::x86_sse2_comile_sd:
11646       Opc = X86ISD::COMI;
11647       CC = ISD::SETLE;
11648       break;
11649     case Intrinsic::x86_sse_comigt_ss:
11650     case Intrinsic::x86_sse2_comigt_sd:
11651       Opc = X86ISD::COMI;
11652       CC = ISD::SETGT;
11653       break;
11654     case Intrinsic::x86_sse_comige_ss:
11655     case Intrinsic::x86_sse2_comige_sd:
11656       Opc = X86ISD::COMI;
11657       CC = ISD::SETGE;
11658       break;
11659     case Intrinsic::x86_sse_comineq_ss:
11660     case Intrinsic::x86_sse2_comineq_sd:
11661       Opc = X86ISD::COMI;
11662       CC = ISD::SETNE;
11663       break;
11664     case Intrinsic::x86_sse_ucomieq_ss:
11665     case Intrinsic::x86_sse2_ucomieq_sd:
11666       Opc = X86ISD::UCOMI;
11667       CC = ISD::SETEQ;
11668       break;
11669     case Intrinsic::x86_sse_ucomilt_ss:
11670     case Intrinsic::x86_sse2_ucomilt_sd:
11671       Opc = X86ISD::UCOMI;
11672       CC = ISD::SETLT;
11673       break;
11674     case Intrinsic::x86_sse_ucomile_ss:
11675     case Intrinsic::x86_sse2_ucomile_sd:
11676       Opc = X86ISD::UCOMI;
11677       CC = ISD::SETLE;
11678       break;
11679     case Intrinsic::x86_sse_ucomigt_ss:
11680     case Intrinsic::x86_sse2_ucomigt_sd:
11681       Opc = X86ISD::UCOMI;
11682       CC = ISD::SETGT;
11683       break;
11684     case Intrinsic::x86_sse_ucomige_ss:
11685     case Intrinsic::x86_sse2_ucomige_sd:
11686       Opc = X86ISD::UCOMI;
11687       CC = ISD::SETGE;
11688       break;
11689     case Intrinsic::x86_sse_ucomineq_ss:
11690     case Intrinsic::x86_sse2_ucomineq_sd:
11691       Opc = X86ISD::UCOMI;
11692       CC = ISD::SETNE;
11693       break;
11694     }
11695
11696     SDValue LHS = Op.getOperand(1);
11697     SDValue RHS = Op.getOperand(2);
11698     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11699     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11700     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11701     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11702                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11703     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11704   }
11705
11706   // Arithmetic intrinsics.
11707   case Intrinsic::x86_sse2_pmulu_dq:
11708   case Intrinsic::x86_avx2_pmulu_dq:
11709     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11710                        Op.getOperand(1), Op.getOperand(2));
11711
11712   case Intrinsic::x86_sse41_pmuldq:
11713   case Intrinsic::x86_avx2_pmul_dq:
11714     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11715                        Op.getOperand(1), Op.getOperand(2));
11716
11717   case Intrinsic::x86_sse2_pmulhu_w:
11718   case Intrinsic::x86_avx2_pmulhu_w:
11719     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11720                        Op.getOperand(1), Op.getOperand(2));
11721
11722   case Intrinsic::x86_sse2_pmulh_w:
11723   case Intrinsic::x86_avx2_pmulh_w:
11724     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11725                        Op.getOperand(1), Op.getOperand(2));
11726
11727   // SSE2/AVX2 sub with unsigned saturation intrinsics
11728   case Intrinsic::x86_sse2_psubus_b:
11729   case Intrinsic::x86_sse2_psubus_w:
11730   case Intrinsic::x86_avx2_psubus_b:
11731   case Intrinsic::x86_avx2_psubus_w:
11732     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11733                        Op.getOperand(1), Op.getOperand(2));
11734
11735   // SSE3/AVX horizontal add/sub intrinsics
11736   case Intrinsic::x86_sse3_hadd_ps:
11737   case Intrinsic::x86_sse3_hadd_pd:
11738   case Intrinsic::x86_avx_hadd_ps_256:
11739   case Intrinsic::x86_avx_hadd_pd_256:
11740   case Intrinsic::x86_sse3_hsub_ps:
11741   case Intrinsic::x86_sse3_hsub_pd:
11742   case Intrinsic::x86_avx_hsub_ps_256:
11743   case Intrinsic::x86_avx_hsub_pd_256:
11744   case Intrinsic::x86_ssse3_phadd_w_128:
11745   case Intrinsic::x86_ssse3_phadd_d_128:
11746   case Intrinsic::x86_avx2_phadd_w:
11747   case Intrinsic::x86_avx2_phadd_d:
11748   case Intrinsic::x86_ssse3_phsub_w_128:
11749   case Intrinsic::x86_ssse3_phsub_d_128:
11750   case Intrinsic::x86_avx2_phsub_w:
11751   case Intrinsic::x86_avx2_phsub_d: {
11752     unsigned Opcode;
11753     switch (IntNo) {
11754     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11755     case Intrinsic::x86_sse3_hadd_ps:
11756     case Intrinsic::x86_sse3_hadd_pd:
11757     case Intrinsic::x86_avx_hadd_ps_256:
11758     case Intrinsic::x86_avx_hadd_pd_256:
11759       Opcode = X86ISD::FHADD;
11760       break;
11761     case Intrinsic::x86_sse3_hsub_ps:
11762     case Intrinsic::x86_sse3_hsub_pd:
11763     case Intrinsic::x86_avx_hsub_ps_256:
11764     case Intrinsic::x86_avx_hsub_pd_256:
11765       Opcode = X86ISD::FHSUB;
11766       break;
11767     case Intrinsic::x86_ssse3_phadd_w_128:
11768     case Intrinsic::x86_ssse3_phadd_d_128:
11769     case Intrinsic::x86_avx2_phadd_w:
11770     case Intrinsic::x86_avx2_phadd_d:
11771       Opcode = X86ISD::HADD;
11772       break;
11773     case Intrinsic::x86_ssse3_phsub_w_128:
11774     case Intrinsic::x86_ssse3_phsub_d_128:
11775     case Intrinsic::x86_avx2_phsub_w:
11776     case Intrinsic::x86_avx2_phsub_d:
11777       Opcode = X86ISD::HSUB;
11778       break;
11779     }
11780     return DAG.getNode(Opcode, dl, Op.getValueType(),
11781                        Op.getOperand(1), Op.getOperand(2));
11782   }
11783
11784   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11785   case Intrinsic::x86_sse2_pmaxu_b:
11786   case Intrinsic::x86_sse41_pmaxuw:
11787   case Intrinsic::x86_sse41_pmaxud:
11788   case Intrinsic::x86_avx2_pmaxu_b:
11789   case Intrinsic::x86_avx2_pmaxu_w:
11790   case Intrinsic::x86_avx2_pmaxu_d:
11791   case Intrinsic::x86_sse2_pminu_b:
11792   case Intrinsic::x86_sse41_pminuw:
11793   case Intrinsic::x86_sse41_pminud:
11794   case Intrinsic::x86_avx2_pminu_b:
11795   case Intrinsic::x86_avx2_pminu_w:
11796   case Intrinsic::x86_avx2_pminu_d:
11797   case Intrinsic::x86_sse41_pmaxsb:
11798   case Intrinsic::x86_sse2_pmaxs_w:
11799   case Intrinsic::x86_sse41_pmaxsd:
11800   case Intrinsic::x86_avx2_pmaxs_b:
11801   case Intrinsic::x86_avx2_pmaxs_w:
11802   case Intrinsic::x86_avx2_pmaxs_d:
11803   case Intrinsic::x86_sse41_pminsb:
11804   case Intrinsic::x86_sse2_pmins_w:
11805   case Intrinsic::x86_sse41_pminsd:
11806   case Intrinsic::x86_avx2_pmins_b:
11807   case Intrinsic::x86_avx2_pmins_w:
11808   case Intrinsic::x86_avx2_pmins_d: {
11809     unsigned Opcode;
11810     switch (IntNo) {
11811     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11812     case Intrinsic::x86_sse2_pmaxu_b:
11813     case Intrinsic::x86_sse41_pmaxuw:
11814     case Intrinsic::x86_sse41_pmaxud:
11815     case Intrinsic::x86_avx2_pmaxu_b:
11816     case Intrinsic::x86_avx2_pmaxu_w:
11817     case Intrinsic::x86_avx2_pmaxu_d:
11818       Opcode = X86ISD::UMAX;
11819       break;
11820     case Intrinsic::x86_sse2_pminu_b:
11821     case Intrinsic::x86_sse41_pminuw:
11822     case Intrinsic::x86_sse41_pminud:
11823     case Intrinsic::x86_avx2_pminu_b:
11824     case Intrinsic::x86_avx2_pminu_w:
11825     case Intrinsic::x86_avx2_pminu_d:
11826       Opcode = X86ISD::UMIN;
11827       break;
11828     case Intrinsic::x86_sse41_pmaxsb:
11829     case Intrinsic::x86_sse2_pmaxs_w:
11830     case Intrinsic::x86_sse41_pmaxsd:
11831     case Intrinsic::x86_avx2_pmaxs_b:
11832     case Intrinsic::x86_avx2_pmaxs_w:
11833     case Intrinsic::x86_avx2_pmaxs_d:
11834       Opcode = X86ISD::SMAX;
11835       break;
11836     case Intrinsic::x86_sse41_pminsb:
11837     case Intrinsic::x86_sse2_pmins_w:
11838     case Intrinsic::x86_sse41_pminsd:
11839     case Intrinsic::x86_avx2_pmins_b:
11840     case Intrinsic::x86_avx2_pmins_w:
11841     case Intrinsic::x86_avx2_pmins_d:
11842       Opcode = X86ISD::SMIN;
11843       break;
11844     }
11845     return DAG.getNode(Opcode, dl, Op.getValueType(),
11846                        Op.getOperand(1), Op.getOperand(2));
11847   }
11848
11849   // SSE/SSE2/AVX floating point max/min intrinsics.
11850   case Intrinsic::x86_sse_max_ps:
11851   case Intrinsic::x86_sse2_max_pd:
11852   case Intrinsic::x86_avx_max_ps_256:
11853   case Intrinsic::x86_avx_max_pd_256:
11854   case Intrinsic::x86_sse_min_ps:
11855   case Intrinsic::x86_sse2_min_pd:
11856   case Intrinsic::x86_avx_min_ps_256:
11857   case Intrinsic::x86_avx_min_pd_256: {
11858     unsigned Opcode;
11859     switch (IntNo) {
11860     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11861     case Intrinsic::x86_sse_max_ps:
11862     case Intrinsic::x86_sse2_max_pd:
11863     case Intrinsic::x86_avx_max_ps_256:
11864     case Intrinsic::x86_avx_max_pd_256:
11865       Opcode = X86ISD::FMAX;
11866       break;
11867     case Intrinsic::x86_sse_min_ps:
11868     case Intrinsic::x86_sse2_min_pd:
11869     case Intrinsic::x86_avx_min_ps_256:
11870     case Intrinsic::x86_avx_min_pd_256:
11871       Opcode = X86ISD::FMIN;
11872       break;
11873     }
11874     return DAG.getNode(Opcode, dl, Op.getValueType(),
11875                        Op.getOperand(1), Op.getOperand(2));
11876   }
11877
11878   // AVX2 variable shift intrinsics
11879   case Intrinsic::x86_avx2_psllv_d:
11880   case Intrinsic::x86_avx2_psllv_q:
11881   case Intrinsic::x86_avx2_psllv_d_256:
11882   case Intrinsic::x86_avx2_psllv_q_256:
11883   case Intrinsic::x86_avx2_psrlv_d:
11884   case Intrinsic::x86_avx2_psrlv_q:
11885   case Intrinsic::x86_avx2_psrlv_d_256:
11886   case Intrinsic::x86_avx2_psrlv_q_256:
11887   case Intrinsic::x86_avx2_psrav_d:
11888   case Intrinsic::x86_avx2_psrav_d_256: {
11889     unsigned Opcode;
11890     switch (IntNo) {
11891     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11892     case Intrinsic::x86_avx2_psllv_d:
11893     case Intrinsic::x86_avx2_psllv_q:
11894     case Intrinsic::x86_avx2_psllv_d_256:
11895     case Intrinsic::x86_avx2_psllv_q_256:
11896       Opcode = ISD::SHL;
11897       break;
11898     case Intrinsic::x86_avx2_psrlv_d:
11899     case Intrinsic::x86_avx2_psrlv_q:
11900     case Intrinsic::x86_avx2_psrlv_d_256:
11901     case Intrinsic::x86_avx2_psrlv_q_256:
11902       Opcode = ISD::SRL;
11903       break;
11904     case Intrinsic::x86_avx2_psrav_d:
11905     case Intrinsic::x86_avx2_psrav_d_256:
11906       Opcode = ISD::SRA;
11907       break;
11908     }
11909     return DAG.getNode(Opcode, dl, Op.getValueType(),
11910                        Op.getOperand(1), Op.getOperand(2));
11911   }
11912
11913   case Intrinsic::x86_ssse3_pshuf_b_128:
11914   case Intrinsic::x86_avx2_pshuf_b:
11915     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11916                        Op.getOperand(1), Op.getOperand(2));
11917
11918   case Intrinsic::x86_ssse3_psign_b_128:
11919   case Intrinsic::x86_ssse3_psign_w_128:
11920   case Intrinsic::x86_ssse3_psign_d_128:
11921   case Intrinsic::x86_avx2_psign_b:
11922   case Intrinsic::x86_avx2_psign_w:
11923   case Intrinsic::x86_avx2_psign_d:
11924     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11925                        Op.getOperand(1), Op.getOperand(2));
11926
11927   case Intrinsic::x86_sse41_insertps:
11928     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11929                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11930
11931   case Intrinsic::x86_avx_vperm2f128_ps_256:
11932   case Intrinsic::x86_avx_vperm2f128_pd_256:
11933   case Intrinsic::x86_avx_vperm2f128_si_256:
11934   case Intrinsic::x86_avx2_vperm2i128:
11935     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11936                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11937
11938   case Intrinsic::x86_avx2_permd:
11939   case Intrinsic::x86_avx2_permps:
11940     // Operands intentionally swapped. Mask is last operand to intrinsic,
11941     // but second operand for node/instruction.
11942     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11943                        Op.getOperand(2), Op.getOperand(1));
11944
11945   case Intrinsic::x86_sse_sqrt_ps:
11946   case Intrinsic::x86_sse2_sqrt_pd:
11947   case Intrinsic::x86_avx_sqrt_ps_256:
11948   case Intrinsic::x86_avx_sqrt_pd_256:
11949     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11950
11951   // ptest and testp intrinsics. The intrinsic these come from are designed to
11952   // return an integer value, not just an instruction so lower it to the ptest
11953   // or testp pattern and a setcc for the result.
11954   case Intrinsic::x86_sse41_ptestz:
11955   case Intrinsic::x86_sse41_ptestc:
11956   case Intrinsic::x86_sse41_ptestnzc:
11957   case Intrinsic::x86_avx_ptestz_256:
11958   case Intrinsic::x86_avx_ptestc_256:
11959   case Intrinsic::x86_avx_ptestnzc_256:
11960   case Intrinsic::x86_avx_vtestz_ps:
11961   case Intrinsic::x86_avx_vtestc_ps:
11962   case Intrinsic::x86_avx_vtestnzc_ps:
11963   case Intrinsic::x86_avx_vtestz_pd:
11964   case Intrinsic::x86_avx_vtestc_pd:
11965   case Intrinsic::x86_avx_vtestnzc_pd:
11966   case Intrinsic::x86_avx_vtestz_ps_256:
11967   case Intrinsic::x86_avx_vtestc_ps_256:
11968   case Intrinsic::x86_avx_vtestnzc_ps_256:
11969   case Intrinsic::x86_avx_vtestz_pd_256:
11970   case Intrinsic::x86_avx_vtestc_pd_256:
11971   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11972     bool IsTestPacked = false;
11973     unsigned X86CC;
11974     switch (IntNo) {
11975     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11976     case Intrinsic::x86_avx_vtestz_ps:
11977     case Intrinsic::x86_avx_vtestz_pd:
11978     case Intrinsic::x86_avx_vtestz_ps_256:
11979     case Intrinsic::x86_avx_vtestz_pd_256:
11980       IsTestPacked = true; // Fallthrough
11981     case Intrinsic::x86_sse41_ptestz:
11982     case Intrinsic::x86_avx_ptestz_256:
11983       // ZF = 1
11984       X86CC = X86::COND_E;
11985       break;
11986     case Intrinsic::x86_avx_vtestc_ps:
11987     case Intrinsic::x86_avx_vtestc_pd:
11988     case Intrinsic::x86_avx_vtestc_ps_256:
11989     case Intrinsic::x86_avx_vtestc_pd_256:
11990       IsTestPacked = true; // Fallthrough
11991     case Intrinsic::x86_sse41_ptestc:
11992     case Intrinsic::x86_avx_ptestc_256:
11993       // CF = 1
11994       X86CC = X86::COND_B;
11995       break;
11996     case Intrinsic::x86_avx_vtestnzc_ps:
11997     case Intrinsic::x86_avx_vtestnzc_pd:
11998     case Intrinsic::x86_avx_vtestnzc_ps_256:
11999     case Intrinsic::x86_avx_vtestnzc_pd_256:
12000       IsTestPacked = true; // Fallthrough
12001     case Intrinsic::x86_sse41_ptestnzc:
12002     case Intrinsic::x86_avx_ptestnzc_256:
12003       // ZF and CF = 0
12004       X86CC = X86::COND_A;
12005       break;
12006     }
12007
12008     SDValue LHS = Op.getOperand(1);
12009     SDValue RHS = Op.getOperand(2);
12010     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12011     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12012     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12013     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12014     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12015   }
12016   case Intrinsic::x86_avx512_kortestz_w:
12017   case Intrinsic::x86_avx512_kortestc_w: {
12018     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12019     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12020     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12021     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12022     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12023     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12024     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12025   }
12026
12027   // SSE/AVX shift intrinsics
12028   case Intrinsic::x86_sse2_psll_w:
12029   case Intrinsic::x86_sse2_psll_d:
12030   case Intrinsic::x86_sse2_psll_q:
12031   case Intrinsic::x86_avx2_psll_w:
12032   case Intrinsic::x86_avx2_psll_d:
12033   case Intrinsic::x86_avx2_psll_q:
12034   case Intrinsic::x86_sse2_psrl_w:
12035   case Intrinsic::x86_sse2_psrl_d:
12036   case Intrinsic::x86_sse2_psrl_q:
12037   case Intrinsic::x86_avx2_psrl_w:
12038   case Intrinsic::x86_avx2_psrl_d:
12039   case Intrinsic::x86_avx2_psrl_q:
12040   case Intrinsic::x86_sse2_psra_w:
12041   case Intrinsic::x86_sse2_psra_d:
12042   case Intrinsic::x86_avx2_psra_w:
12043   case Intrinsic::x86_avx2_psra_d: {
12044     unsigned Opcode;
12045     switch (IntNo) {
12046     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12047     case Intrinsic::x86_sse2_psll_w:
12048     case Intrinsic::x86_sse2_psll_d:
12049     case Intrinsic::x86_sse2_psll_q:
12050     case Intrinsic::x86_avx2_psll_w:
12051     case Intrinsic::x86_avx2_psll_d:
12052     case Intrinsic::x86_avx2_psll_q:
12053       Opcode = X86ISD::VSHL;
12054       break;
12055     case Intrinsic::x86_sse2_psrl_w:
12056     case Intrinsic::x86_sse2_psrl_d:
12057     case Intrinsic::x86_sse2_psrl_q:
12058     case Intrinsic::x86_avx2_psrl_w:
12059     case Intrinsic::x86_avx2_psrl_d:
12060     case Intrinsic::x86_avx2_psrl_q:
12061       Opcode = X86ISD::VSRL;
12062       break;
12063     case Intrinsic::x86_sse2_psra_w:
12064     case Intrinsic::x86_sse2_psra_d:
12065     case Intrinsic::x86_avx2_psra_w:
12066     case Intrinsic::x86_avx2_psra_d:
12067       Opcode = X86ISD::VSRA;
12068       break;
12069     }
12070     return DAG.getNode(Opcode, dl, Op.getValueType(),
12071                        Op.getOperand(1), Op.getOperand(2));
12072   }
12073
12074   // SSE/AVX immediate shift intrinsics
12075   case Intrinsic::x86_sse2_pslli_w:
12076   case Intrinsic::x86_sse2_pslli_d:
12077   case Intrinsic::x86_sse2_pslli_q:
12078   case Intrinsic::x86_avx2_pslli_w:
12079   case Intrinsic::x86_avx2_pslli_d:
12080   case Intrinsic::x86_avx2_pslli_q:
12081   case Intrinsic::x86_sse2_psrli_w:
12082   case Intrinsic::x86_sse2_psrli_d:
12083   case Intrinsic::x86_sse2_psrli_q:
12084   case Intrinsic::x86_avx2_psrli_w:
12085   case Intrinsic::x86_avx2_psrli_d:
12086   case Intrinsic::x86_avx2_psrli_q:
12087   case Intrinsic::x86_sse2_psrai_w:
12088   case Intrinsic::x86_sse2_psrai_d:
12089   case Intrinsic::x86_avx2_psrai_w:
12090   case Intrinsic::x86_avx2_psrai_d: {
12091     unsigned Opcode;
12092     switch (IntNo) {
12093     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12094     case Intrinsic::x86_sse2_pslli_w:
12095     case Intrinsic::x86_sse2_pslli_d:
12096     case Intrinsic::x86_sse2_pslli_q:
12097     case Intrinsic::x86_avx2_pslli_w:
12098     case Intrinsic::x86_avx2_pslli_d:
12099     case Intrinsic::x86_avx2_pslli_q:
12100       Opcode = X86ISD::VSHLI;
12101       break;
12102     case Intrinsic::x86_sse2_psrli_w:
12103     case Intrinsic::x86_sse2_psrli_d:
12104     case Intrinsic::x86_sse2_psrli_q:
12105     case Intrinsic::x86_avx2_psrli_w:
12106     case Intrinsic::x86_avx2_psrli_d:
12107     case Intrinsic::x86_avx2_psrli_q:
12108       Opcode = X86ISD::VSRLI;
12109       break;
12110     case Intrinsic::x86_sse2_psrai_w:
12111     case Intrinsic::x86_sse2_psrai_d:
12112     case Intrinsic::x86_avx2_psrai_w:
12113     case Intrinsic::x86_avx2_psrai_d:
12114       Opcode = X86ISD::VSRAI;
12115       break;
12116     }
12117     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12118                                Op.getOperand(1), Op.getOperand(2), DAG);
12119   }
12120
12121   case Intrinsic::x86_sse42_pcmpistria128:
12122   case Intrinsic::x86_sse42_pcmpestria128:
12123   case Intrinsic::x86_sse42_pcmpistric128:
12124   case Intrinsic::x86_sse42_pcmpestric128:
12125   case Intrinsic::x86_sse42_pcmpistrio128:
12126   case Intrinsic::x86_sse42_pcmpestrio128:
12127   case Intrinsic::x86_sse42_pcmpistris128:
12128   case Intrinsic::x86_sse42_pcmpestris128:
12129   case Intrinsic::x86_sse42_pcmpistriz128:
12130   case Intrinsic::x86_sse42_pcmpestriz128: {
12131     unsigned Opcode;
12132     unsigned X86CC;
12133     switch (IntNo) {
12134     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12135     case Intrinsic::x86_sse42_pcmpistria128:
12136       Opcode = X86ISD::PCMPISTRI;
12137       X86CC = X86::COND_A;
12138       break;
12139     case Intrinsic::x86_sse42_pcmpestria128:
12140       Opcode = X86ISD::PCMPESTRI;
12141       X86CC = X86::COND_A;
12142       break;
12143     case Intrinsic::x86_sse42_pcmpistric128:
12144       Opcode = X86ISD::PCMPISTRI;
12145       X86CC = X86::COND_B;
12146       break;
12147     case Intrinsic::x86_sse42_pcmpestric128:
12148       Opcode = X86ISD::PCMPESTRI;
12149       X86CC = X86::COND_B;
12150       break;
12151     case Intrinsic::x86_sse42_pcmpistrio128:
12152       Opcode = X86ISD::PCMPISTRI;
12153       X86CC = X86::COND_O;
12154       break;
12155     case Intrinsic::x86_sse42_pcmpestrio128:
12156       Opcode = X86ISD::PCMPESTRI;
12157       X86CC = X86::COND_O;
12158       break;
12159     case Intrinsic::x86_sse42_pcmpistris128:
12160       Opcode = X86ISD::PCMPISTRI;
12161       X86CC = X86::COND_S;
12162       break;
12163     case Intrinsic::x86_sse42_pcmpestris128:
12164       Opcode = X86ISD::PCMPESTRI;
12165       X86CC = X86::COND_S;
12166       break;
12167     case Intrinsic::x86_sse42_pcmpistriz128:
12168       Opcode = X86ISD::PCMPISTRI;
12169       X86CC = X86::COND_E;
12170       break;
12171     case Intrinsic::x86_sse42_pcmpestriz128:
12172       Opcode = X86ISD::PCMPESTRI;
12173       X86CC = X86::COND_E;
12174       break;
12175     }
12176     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12177     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12178     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12179     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12180                                 DAG.getConstant(X86CC, MVT::i8),
12181                                 SDValue(PCMP.getNode(), 1));
12182     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12183   }
12184
12185   case Intrinsic::x86_sse42_pcmpistri128:
12186   case Intrinsic::x86_sse42_pcmpestri128: {
12187     unsigned Opcode;
12188     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12189       Opcode = X86ISD::PCMPISTRI;
12190     else
12191       Opcode = X86ISD::PCMPESTRI;
12192
12193     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12194     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12195     return DAG.getNode(Opcode, dl, VTs, NewOps);
12196   }
12197   case Intrinsic::x86_fma_vfmadd_ps:
12198   case Intrinsic::x86_fma_vfmadd_pd:
12199   case Intrinsic::x86_fma_vfmsub_ps:
12200   case Intrinsic::x86_fma_vfmsub_pd:
12201   case Intrinsic::x86_fma_vfnmadd_ps:
12202   case Intrinsic::x86_fma_vfnmadd_pd:
12203   case Intrinsic::x86_fma_vfnmsub_ps:
12204   case Intrinsic::x86_fma_vfnmsub_pd:
12205   case Intrinsic::x86_fma_vfmaddsub_ps:
12206   case Intrinsic::x86_fma_vfmaddsub_pd:
12207   case Intrinsic::x86_fma_vfmsubadd_ps:
12208   case Intrinsic::x86_fma_vfmsubadd_pd:
12209   case Intrinsic::x86_fma_vfmadd_ps_256:
12210   case Intrinsic::x86_fma_vfmadd_pd_256:
12211   case Intrinsic::x86_fma_vfmsub_ps_256:
12212   case Intrinsic::x86_fma_vfmsub_pd_256:
12213   case Intrinsic::x86_fma_vfnmadd_ps_256:
12214   case Intrinsic::x86_fma_vfnmadd_pd_256:
12215   case Intrinsic::x86_fma_vfnmsub_ps_256:
12216   case Intrinsic::x86_fma_vfnmsub_pd_256:
12217   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12218   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12219   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12220   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12221   case Intrinsic::x86_fma_vfmadd_ps_512:
12222   case Intrinsic::x86_fma_vfmadd_pd_512:
12223   case Intrinsic::x86_fma_vfmsub_ps_512:
12224   case Intrinsic::x86_fma_vfmsub_pd_512:
12225   case Intrinsic::x86_fma_vfnmadd_ps_512:
12226   case Intrinsic::x86_fma_vfnmadd_pd_512:
12227   case Intrinsic::x86_fma_vfnmsub_ps_512:
12228   case Intrinsic::x86_fma_vfnmsub_pd_512:
12229   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12230   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12231   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12232   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12233     unsigned Opc;
12234     switch (IntNo) {
12235     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12236     case Intrinsic::x86_fma_vfmadd_ps:
12237     case Intrinsic::x86_fma_vfmadd_pd:
12238     case Intrinsic::x86_fma_vfmadd_ps_256:
12239     case Intrinsic::x86_fma_vfmadd_pd_256:
12240     case Intrinsic::x86_fma_vfmadd_ps_512:
12241     case Intrinsic::x86_fma_vfmadd_pd_512:
12242       Opc = X86ISD::FMADD;
12243       break;
12244     case Intrinsic::x86_fma_vfmsub_ps:
12245     case Intrinsic::x86_fma_vfmsub_pd:
12246     case Intrinsic::x86_fma_vfmsub_ps_256:
12247     case Intrinsic::x86_fma_vfmsub_pd_256:
12248     case Intrinsic::x86_fma_vfmsub_ps_512:
12249     case Intrinsic::x86_fma_vfmsub_pd_512:
12250       Opc = X86ISD::FMSUB;
12251       break;
12252     case Intrinsic::x86_fma_vfnmadd_ps:
12253     case Intrinsic::x86_fma_vfnmadd_pd:
12254     case Intrinsic::x86_fma_vfnmadd_ps_256:
12255     case Intrinsic::x86_fma_vfnmadd_pd_256:
12256     case Intrinsic::x86_fma_vfnmadd_ps_512:
12257     case Intrinsic::x86_fma_vfnmadd_pd_512:
12258       Opc = X86ISD::FNMADD;
12259       break;
12260     case Intrinsic::x86_fma_vfnmsub_ps:
12261     case Intrinsic::x86_fma_vfnmsub_pd:
12262     case Intrinsic::x86_fma_vfnmsub_ps_256:
12263     case Intrinsic::x86_fma_vfnmsub_pd_256:
12264     case Intrinsic::x86_fma_vfnmsub_ps_512:
12265     case Intrinsic::x86_fma_vfnmsub_pd_512:
12266       Opc = X86ISD::FNMSUB;
12267       break;
12268     case Intrinsic::x86_fma_vfmaddsub_ps:
12269     case Intrinsic::x86_fma_vfmaddsub_pd:
12270     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12271     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12272     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12273     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12274       Opc = X86ISD::FMADDSUB;
12275       break;
12276     case Intrinsic::x86_fma_vfmsubadd_ps:
12277     case Intrinsic::x86_fma_vfmsubadd_pd:
12278     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12279     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12280     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12281     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12282       Opc = X86ISD::FMSUBADD;
12283       break;
12284     }
12285
12286     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12287                        Op.getOperand(2), Op.getOperand(3));
12288   }
12289   }
12290 }
12291
12292 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12293                              SDValue Base, SDValue Index,
12294                              SDValue ScaleOp, SDValue Chain,
12295                              const X86Subtarget * Subtarget) {
12296   SDLoc dl(Op);
12297   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12298   assert(C && "Invalid scale type");
12299   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12300   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12301   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12302                              Index.getSimpleValueType().getVectorNumElements());
12303   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12304   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12305   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12306   SDValue Segment = DAG.getRegister(0, MVT::i32);
12307   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12308   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12309   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12310   return DAG.getMergeValues(RetOps, dl);
12311 }
12312
12313 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12314                               SDValue Src, SDValue Mask, SDValue Base,
12315                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12316                               const X86Subtarget * Subtarget) {
12317   SDLoc dl(Op);
12318   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12319   assert(C && "Invalid scale type");
12320   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12321   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12322                              Index.getSimpleValueType().getVectorNumElements());
12323   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12324   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12325   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12326   SDValue Segment = DAG.getRegister(0, MVT::i32);
12327   if (Src.getOpcode() == ISD::UNDEF)
12328     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12329   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12330   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12331   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12332   return DAG.getMergeValues(RetOps, dl);
12333 }
12334
12335 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12336                               SDValue Src, SDValue Base, SDValue Index,
12337                               SDValue ScaleOp, SDValue Chain) {
12338   SDLoc dl(Op);
12339   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12340   assert(C && "Invalid scale type");
12341   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12342   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12343   SDValue Segment = DAG.getRegister(0, MVT::i32);
12344   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12345                              Index.getSimpleValueType().getVectorNumElements());
12346   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12347   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12348   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12349   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12350   return SDValue(Res, 1);
12351 }
12352
12353 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12354                                SDValue Src, SDValue Mask, SDValue Base,
12355                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12356   SDLoc dl(Op);
12357   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12358   assert(C && "Invalid scale type");
12359   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12360   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12361   SDValue Segment = DAG.getRegister(0, MVT::i32);
12362   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12363                              Index.getSimpleValueType().getVectorNumElements());
12364   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12365   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12366   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12367   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12368   return SDValue(Res, 1);
12369 }
12370
12371 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12372 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12373 // also used to custom lower READCYCLECOUNTER nodes.
12374 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12375                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12376                               SmallVectorImpl<SDValue> &Results) {
12377   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12378   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12379   SDValue LO, HI;
12380
12381   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12382   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12383   // and the EAX register is loaded with the low-order 32 bits.
12384   if (Subtarget->is64Bit()) {
12385     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12386     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12387                             LO.getValue(2));
12388   } else {
12389     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12390     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12391                             LO.getValue(2));
12392   }
12393   SDValue Chain = HI.getValue(1);
12394
12395   if (Opcode == X86ISD::RDTSCP_DAG) {
12396     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12397
12398     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12399     // the ECX register. Add 'ecx' explicitly to the chain.
12400     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12401                                      HI.getValue(2));
12402     // Explicitly store the content of ECX at the location passed in input
12403     // to the 'rdtscp' intrinsic.
12404     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12405                          MachinePointerInfo(), false, false, 0);
12406   }
12407
12408   if (Subtarget->is64Bit()) {
12409     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12410     // the EAX register is loaded with the low-order 32 bits.
12411     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12412                               DAG.getConstant(32, MVT::i8));
12413     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12414     Results.push_back(Chain);
12415     return;
12416   }
12417
12418   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12419   SDValue Ops[] = { LO, HI };
12420   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12421   Results.push_back(Pair);
12422   Results.push_back(Chain);
12423 }
12424
12425 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12426                                      SelectionDAG &DAG) {
12427   SmallVector<SDValue, 2> Results;
12428   SDLoc DL(Op);
12429   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12430                           Results);
12431   return DAG.getMergeValues(Results, DL);
12432 }
12433
12434 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12435                                       SelectionDAG &DAG) {
12436   SDLoc dl(Op);
12437   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12438   switch (IntNo) {
12439   default: return SDValue();    // Don't custom lower most intrinsics.
12440
12441   // RDRAND/RDSEED intrinsics.
12442   case Intrinsic::x86_rdrand_16:
12443   case Intrinsic::x86_rdrand_32:
12444   case Intrinsic::x86_rdrand_64:
12445   case Intrinsic::x86_rdseed_16:
12446   case Intrinsic::x86_rdseed_32:
12447   case Intrinsic::x86_rdseed_64: {
12448     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12449                        IntNo == Intrinsic::x86_rdseed_32 ||
12450                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12451                                                             X86ISD::RDRAND;
12452     // Emit the node with the right value type.
12453     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12454     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12455
12456     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12457     // Otherwise return the value from Rand, which is always 0, casted to i32.
12458     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12459                       DAG.getConstant(1, Op->getValueType(1)),
12460                       DAG.getConstant(X86::COND_B, MVT::i32),
12461                       SDValue(Result.getNode(), 1) };
12462     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12463                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12464                                   Ops);
12465
12466     // Return { result, isValid, chain }.
12467     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12468                        SDValue(Result.getNode(), 2));
12469   }
12470   //int_gather(index, base, scale);
12471   case Intrinsic::x86_avx512_gather_qpd_512:
12472   case Intrinsic::x86_avx512_gather_qps_512:
12473   case Intrinsic::x86_avx512_gather_dpd_512:
12474   case Intrinsic::x86_avx512_gather_qpi_512:
12475   case Intrinsic::x86_avx512_gather_qpq_512:
12476   case Intrinsic::x86_avx512_gather_dpq_512:
12477   case Intrinsic::x86_avx512_gather_dps_512:
12478   case Intrinsic::x86_avx512_gather_dpi_512: {
12479     unsigned Opc;
12480     switch (IntNo) {
12481     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12482     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12483     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12484     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12485     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12486     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12487     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12488     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12489     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12490     }
12491     SDValue Chain = Op.getOperand(0);
12492     SDValue Index = Op.getOperand(2);
12493     SDValue Base  = Op.getOperand(3);
12494     SDValue Scale = Op.getOperand(4);
12495     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12496   }
12497   //int_gather_mask(v1, mask, index, base, scale);
12498   case Intrinsic::x86_avx512_gather_qps_mask_512:
12499   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12500   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12501   case Intrinsic::x86_avx512_gather_dps_mask_512:
12502   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12503   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12504   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12505   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12506     unsigned Opc;
12507     switch (IntNo) {
12508     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12509     case Intrinsic::x86_avx512_gather_qps_mask_512:
12510       Opc = X86::VGATHERQPSZrm; break;
12511     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12512       Opc = X86::VGATHERQPDZrm; break;
12513     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12514       Opc = X86::VGATHERDPDZrm; break;
12515     case Intrinsic::x86_avx512_gather_dps_mask_512:
12516       Opc = X86::VGATHERDPSZrm; break;
12517     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12518       Opc = X86::VPGATHERQDZrm; break;
12519     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12520       Opc = X86::VPGATHERQQZrm; break;
12521     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12522       Opc = X86::VPGATHERDDZrm; break;
12523     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12524       Opc = X86::VPGATHERDQZrm; break;
12525     }
12526     SDValue Chain = Op.getOperand(0);
12527     SDValue Src   = Op.getOperand(2);
12528     SDValue Mask  = Op.getOperand(3);
12529     SDValue Index = Op.getOperand(4);
12530     SDValue Base  = Op.getOperand(5);
12531     SDValue Scale = Op.getOperand(6);
12532     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12533                           Subtarget);
12534   }
12535   //int_scatter(base, index, v1, scale);
12536   case Intrinsic::x86_avx512_scatter_qpd_512:
12537   case Intrinsic::x86_avx512_scatter_qps_512:
12538   case Intrinsic::x86_avx512_scatter_dpd_512:
12539   case Intrinsic::x86_avx512_scatter_qpi_512:
12540   case Intrinsic::x86_avx512_scatter_qpq_512:
12541   case Intrinsic::x86_avx512_scatter_dpq_512:
12542   case Intrinsic::x86_avx512_scatter_dps_512:
12543   case Intrinsic::x86_avx512_scatter_dpi_512: {
12544     unsigned Opc;
12545     switch (IntNo) {
12546     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12547     case Intrinsic::x86_avx512_scatter_qpd_512:
12548       Opc = X86::VSCATTERQPDZmr; break;
12549     case Intrinsic::x86_avx512_scatter_qps_512:
12550       Opc = X86::VSCATTERQPSZmr; break;
12551     case Intrinsic::x86_avx512_scatter_dpd_512:
12552       Opc = X86::VSCATTERDPDZmr; break;
12553     case Intrinsic::x86_avx512_scatter_dps_512:
12554       Opc = X86::VSCATTERDPSZmr; break;
12555     case Intrinsic::x86_avx512_scatter_qpi_512:
12556       Opc = X86::VPSCATTERQDZmr; break;
12557     case Intrinsic::x86_avx512_scatter_qpq_512:
12558       Opc = X86::VPSCATTERQQZmr; break;
12559     case Intrinsic::x86_avx512_scatter_dpq_512:
12560       Opc = X86::VPSCATTERDQZmr; break;
12561     case Intrinsic::x86_avx512_scatter_dpi_512:
12562       Opc = X86::VPSCATTERDDZmr; break;
12563     }
12564     SDValue Chain = Op.getOperand(0);
12565     SDValue Base  = Op.getOperand(2);
12566     SDValue Index = Op.getOperand(3);
12567     SDValue Src   = Op.getOperand(4);
12568     SDValue Scale = Op.getOperand(5);
12569     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12570   }
12571   //int_scatter_mask(base, mask, index, v1, scale);
12572   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12573   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12574   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12575   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12576   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12577   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12578   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12579   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12580     unsigned Opc;
12581     switch (IntNo) {
12582     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12583     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12584       Opc = X86::VSCATTERQPDZmr; break;
12585     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12586       Opc = X86::VSCATTERQPSZmr; break;
12587     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12588       Opc = X86::VSCATTERDPDZmr; break;
12589     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12590       Opc = X86::VSCATTERDPSZmr; break;
12591     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12592       Opc = X86::VPSCATTERQDZmr; break;
12593     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12594       Opc = X86::VPSCATTERQQZmr; break;
12595     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12596       Opc = X86::VPSCATTERDQZmr; break;
12597     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12598       Opc = X86::VPSCATTERDDZmr; break;
12599     }
12600     SDValue Chain = Op.getOperand(0);
12601     SDValue Base  = Op.getOperand(2);
12602     SDValue Mask  = Op.getOperand(3);
12603     SDValue Index = Op.getOperand(4);
12604     SDValue Src   = Op.getOperand(5);
12605     SDValue Scale = Op.getOperand(6);
12606     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12607   }
12608   // Read Time Stamp Counter (RDTSC).
12609   case Intrinsic::x86_rdtsc:
12610   // Read Time Stamp Counter and Processor ID (RDTSCP).
12611   case Intrinsic::x86_rdtscp: {
12612     unsigned Opc;
12613     switch (IntNo) {
12614     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12615     case Intrinsic::x86_rdtsc:
12616       Opc = X86ISD::RDTSC_DAG; break;
12617     case Intrinsic::x86_rdtscp:
12618       Opc = X86ISD::RDTSCP_DAG; break;
12619     }
12620     SmallVector<SDValue, 2> Results;
12621     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12622     return DAG.getMergeValues(Results, dl);
12623   }
12624   // XTEST intrinsics.
12625   case Intrinsic::x86_xtest: {
12626     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12627     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12628     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12629                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12630                                 InTrans);
12631     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12632     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12633                        Ret, SDValue(InTrans.getNode(), 1));
12634   }
12635   }
12636 }
12637
12638 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12639                                            SelectionDAG &DAG) const {
12640   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12641   MFI->setReturnAddressIsTaken(true);
12642
12643   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12644     return SDValue();
12645
12646   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12647   SDLoc dl(Op);
12648   EVT PtrVT = getPointerTy();
12649
12650   if (Depth > 0) {
12651     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12652     const X86RegisterInfo *RegInfo =
12653       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12654     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12655     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12656                        DAG.getNode(ISD::ADD, dl, PtrVT,
12657                                    FrameAddr, Offset),
12658                        MachinePointerInfo(), false, false, false, 0);
12659   }
12660
12661   // Just load the return address.
12662   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12663   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12664                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12665 }
12666
12667 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12668   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12669   MFI->setFrameAddressIsTaken(true);
12670
12671   EVT VT = Op.getValueType();
12672   SDLoc dl(Op);  // FIXME probably not meaningful
12673   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12674   const X86RegisterInfo *RegInfo =
12675     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12676   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12677   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12678           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12679          "Invalid Frame Register!");
12680   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12681   while (Depth--)
12682     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12683                             MachinePointerInfo(),
12684                             false, false, false, 0);
12685   return FrameAddr;
12686 }
12687
12688 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12689                                                      SelectionDAG &DAG) const {
12690   const X86RegisterInfo *RegInfo =
12691     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12692   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12693 }
12694
12695 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12696   SDValue Chain     = Op.getOperand(0);
12697   SDValue Offset    = Op.getOperand(1);
12698   SDValue Handler   = Op.getOperand(2);
12699   SDLoc dl      (Op);
12700
12701   EVT PtrVT = getPointerTy();
12702   const X86RegisterInfo *RegInfo =
12703     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12704   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12705   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12706           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12707          "Invalid Frame Register!");
12708   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12709   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12710
12711   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12712                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12713   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12714   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12715                        false, false, 0);
12716   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12717
12718   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12719                      DAG.getRegister(StoreAddrReg, PtrVT));
12720 }
12721
12722 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12723                                                SelectionDAG &DAG) const {
12724   SDLoc DL(Op);
12725   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12726                      DAG.getVTList(MVT::i32, MVT::Other),
12727                      Op.getOperand(0), Op.getOperand(1));
12728 }
12729
12730 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12731                                                 SelectionDAG &DAG) const {
12732   SDLoc DL(Op);
12733   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12734                      Op.getOperand(0), Op.getOperand(1));
12735 }
12736
12737 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12738   return Op.getOperand(0);
12739 }
12740
12741 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12742                                                 SelectionDAG &DAG) const {
12743   SDValue Root = Op.getOperand(0);
12744   SDValue Trmp = Op.getOperand(1); // trampoline
12745   SDValue FPtr = Op.getOperand(2); // nested function
12746   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12747   SDLoc dl (Op);
12748
12749   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12750   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12751
12752   if (Subtarget->is64Bit()) {
12753     SDValue OutChains[6];
12754
12755     // Large code-model.
12756     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12757     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12758
12759     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12760     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12761
12762     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12763
12764     // Load the pointer to the nested function into R11.
12765     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12766     SDValue Addr = Trmp;
12767     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12768                                 Addr, MachinePointerInfo(TrmpAddr),
12769                                 false, false, 0);
12770
12771     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12772                        DAG.getConstant(2, MVT::i64));
12773     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12774                                 MachinePointerInfo(TrmpAddr, 2),
12775                                 false, false, 2);
12776
12777     // Load the 'nest' parameter value into R10.
12778     // R10 is specified in X86CallingConv.td
12779     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12780     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12781                        DAG.getConstant(10, MVT::i64));
12782     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12783                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12784                                 false, false, 0);
12785
12786     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12787                        DAG.getConstant(12, MVT::i64));
12788     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12789                                 MachinePointerInfo(TrmpAddr, 12),
12790                                 false, false, 2);
12791
12792     // Jump to the nested function.
12793     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12794     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12795                        DAG.getConstant(20, MVT::i64));
12796     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12797                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12798                                 false, false, 0);
12799
12800     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12801     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12802                        DAG.getConstant(22, MVT::i64));
12803     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12804                                 MachinePointerInfo(TrmpAddr, 22),
12805                                 false, false, 0);
12806
12807     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12808   } else {
12809     const Function *Func =
12810       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12811     CallingConv::ID CC = Func->getCallingConv();
12812     unsigned NestReg;
12813
12814     switch (CC) {
12815     default:
12816       llvm_unreachable("Unsupported calling convention");
12817     case CallingConv::C:
12818     case CallingConv::X86_StdCall: {
12819       // Pass 'nest' parameter in ECX.
12820       // Must be kept in sync with X86CallingConv.td
12821       NestReg = X86::ECX;
12822
12823       // Check that ECX wasn't needed by an 'inreg' parameter.
12824       FunctionType *FTy = Func->getFunctionType();
12825       const AttributeSet &Attrs = Func->getAttributes();
12826
12827       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12828         unsigned InRegCount = 0;
12829         unsigned Idx = 1;
12830
12831         for (FunctionType::param_iterator I = FTy->param_begin(),
12832              E = FTy->param_end(); I != E; ++I, ++Idx)
12833           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12834             // FIXME: should only count parameters that are lowered to integers.
12835             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12836
12837         if (InRegCount > 2) {
12838           report_fatal_error("Nest register in use - reduce number of inreg"
12839                              " parameters!");
12840         }
12841       }
12842       break;
12843     }
12844     case CallingConv::X86_FastCall:
12845     case CallingConv::X86_ThisCall:
12846     case CallingConv::Fast:
12847       // Pass 'nest' parameter in EAX.
12848       // Must be kept in sync with X86CallingConv.td
12849       NestReg = X86::EAX;
12850       break;
12851     }
12852
12853     SDValue OutChains[4];
12854     SDValue Addr, Disp;
12855
12856     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12857                        DAG.getConstant(10, MVT::i32));
12858     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12859
12860     // This is storing the opcode for MOV32ri.
12861     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12862     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12863     OutChains[0] = DAG.getStore(Root, dl,
12864                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12865                                 Trmp, MachinePointerInfo(TrmpAddr),
12866                                 false, false, 0);
12867
12868     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12869                        DAG.getConstant(1, MVT::i32));
12870     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12871                                 MachinePointerInfo(TrmpAddr, 1),
12872                                 false, false, 1);
12873
12874     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12875     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12876                        DAG.getConstant(5, MVT::i32));
12877     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12878                                 MachinePointerInfo(TrmpAddr, 5),
12879                                 false, false, 1);
12880
12881     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12882                        DAG.getConstant(6, MVT::i32));
12883     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12884                                 MachinePointerInfo(TrmpAddr, 6),
12885                                 false, false, 1);
12886
12887     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12888   }
12889 }
12890
12891 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12892                                             SelectionDAG &DAG) const {
12893   /*
12894    The rounding mode is in bits 11:10 of FPSR, and has the following
12895    settings:
12896      00 Round to nearest
12897      01 Round to -inf
12898      10 Round to +inf
12899      11 Round to 0
12900
12901   FLT_ROUNDS, on the other hand, expects the following:
12902     -1 Undefined
12903      0 Round to 0
12904      1 Round to nearest
12905      2 Round to +inf
12906      3 Round to -inf
12907
12908   To perform the conversion, we do:
12909     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12910   */
12911
12912   MachineFunction &MF = DAG.getMachineFunction();
12913   const TargetMachine &TM = MF.getTarget();
12914   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12915   unsigned StackAlignment = TFI.getStackAlignment();
12916   MVT VT = Op.getSimpleValueType();
12917   SDLoc DL(Op);
12918
12919   // Save FP Control Word to stack slot
12920   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12921   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12922
12923   MachineMemOperand *MMO =
12924    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12925                            MachineMemOperand::MOStore, 2, 2);
12926
12927   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12928   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12929                                           DAG.getVTList(MVT::Other),
12930                                           Ops, MVT::i16, MMO);
12931
12932   // Load FP Control Word from stack slot
12933   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12934                             MachinePointerInfo(), false, false, false, 0);
12935
12936   // Transform as necessary
12937   SDValue CWD1 =
12938     DAG.getNode(ISD::SRL, DL, MVT::i16,
12939                 DAG.getNode(ISD::AND, DL, MVT::i16,
12940                             CWD, DAG.getConstant(0x800, MVT::i16)),
12941                 DAG.getConstant(11, MVT::i8));
12942   SDValue CWD2 =
12943     DAG.getNode(ISD::SRL, DL, MVT::i16,
12944                 DAG.getNode(ISD::AND, DL, MVT::i16,
12945                             CWD, DAG.getConstant(0x400, MVT::i16)),
12946                 DAG.getConstant(9, MVT::i8));
12947
12948   SDValue RetVal =
12949     DAG.getNode(ISD::AND, DL, MVT::i16,
12950                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12951                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12952                             DAG.getConstant(1, MVT::i16)),
12953                 DAG.getConstant(3, MVT::i16));
12954
12955   return DAG.getNode((VT.getSizeInBits() < 16 ?
12956                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12957 }
12958
12959 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12960   MVT VT = Op.getSimpleValueType();
12961   EVT OpVT = VT;
12962   unsigned NumBits = VT.getSizeInBits();
12963   SDLoc dl(Op);
12964
12965   Op = Op.getOperand(0);
12966   if (VT == MVT::i8) {
12967     // Zero extend to i32 since there is not an i8 bsr.
12968     OpVT = MVT::i32;
12969     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12970   }
12971
12972   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12973   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12974   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12975
12976   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12977   SDValue Ops[] = {
12978     Op,
12979     DAG.getConstant(NumBits+NumBits-1, OpVT),
12980     DAG.getConstant(X86::COND_E, MVT::i8),
12981     Op.getValue(1)
12982   };
12983   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
12984
12985   // Finally xor with NumBits-1.
12986   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12987
12988   if (VT == MVT::i8)
12989     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12990   return Op;
12991 }
12992
12993 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12994   MVT VT = Op.getSimpleValueType();
12995   EVT OpVT = VT;
12996   unsigned NumBits = VT.getSizeInBits();
12997   SDLoc dl(Op);
12998
12999   Op = Op.getOperand(0);
13000   if (VT == MVT::i8) {
13001     // Zero extend to i32 since there is not an i8 bsr.
13002     OpVT = MVT::i32;
13003     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13004   }
13005
13006   // Issue a bsr (scan bits in reverse).
13007   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13008   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13009
13010   // And xor with NumBits-1.
13011   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13012
13013   if (VT == MVT::i8)
13014     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13015   return Op;
13016 }
13017
13018 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13019   MVT VT = Op.getSimpleValueType();
13020   unsigned NumBits = VT.getSizeInBits();
13021   SDLoc dl(Op);
13022   Op = Op.getOperand(0);
13023
13024   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13025   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13026   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13027
13028   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13029   SDValue Ops[] = {
13030     Op,
13031     DAG.getConstant(NumBits, VT),
13032     DAG.getConstant(X86::COND_E, MVT::i8),
13033     Op.getValue(1)
13034   };
13035   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13036 }
13037
13038 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13039 // ones, and then concatenate the result back.
13040 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13041   MVT VT = Op.getSimpleValueType();
13042
13043   assert(VT.is256BitVector() && VT.isInteger() &&
13044          "Unsupported value type for operation");
13045
13046   unsigned NumElems = VT.getVectorNumElements();
13047   SDLoc dl(Op);
13048
13049   // Extract the LHS vectors
13050   SDValue LHS = Op.getOperand(0);
13051   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13052   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13053
13054   // Extract the RHS vectors
13055   SDValue RHS = Op.getOperand(1);
13056   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13057   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13058
13059   MVT EltVT = VT.getVectorElementType();
13060   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13061
13062   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13063                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13064                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13065 }
13066
13067 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13068   assert(Op.getSimpleValueType().is256BitVector() &&
13069          Op.getSimpleValueType().isInteger() &&
13070          "Only handle AVX 256-bit vector integer operation");
13071   return Lower256IntArith(Op, DAG);
13072 }
13073
13074 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13075   assert(Op.getSimpleValueType().is256BitVector() &&
13076          Op.getSimpleValueType().isInteger() &&
13077          "Only handle AVX 256-bit vector integer operation");
13078   return Lower256IntArith(Op, DAG);
13079 }
13080
13081 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13082                         SelectionDAG &DAG) {
13083   SDLoc dl(Op);
13084   MVT VT = Op.getSimpleValueType();
13085
13086   // Decompose 256-bit ops into smaller 128-bit ops.
13087   if (VT.is256BitVector() && !Subtarget->hasInt256())
13088     return Lower256IntArith(Op, DAG);
13089
13090   SDValue A = Op.getOperand(0);
13091   SDValue B = Op.getOperand(1);
13092
13093   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13094   if (VT == MVT::v4i32) {
13095     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13096            "Should not custom lower when pmuldq is available!");
13097
13098     // Extract the odd parts.
13099     static const int UnpackMask[] = { 1, -1, 3, -1 };
13100     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13101     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13102
13103     // Multiply the even parts.
13104     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13105     // Now multiply odd parts.
13106     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13107
13108     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13109     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13110
13111     // Merge the two vectors back together with a shuffle. This expands into 2
13112     // shuffles.
13113     static const int ShufMask[] = { 0, 4, 2, 6 };
13114     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13115   }
13116
13117   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13118          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13119
13120   //  Ahi = psrlqi(a, 32);
13121   //  Bhi = psrlqi(b, 32);
13122   //
13123   //  AloBlo = pmuludq(a, b);
13124   //  AloBhi = pmuludq(a, Bhi);
13125   //  AhiBlo = pmuludq(Ahi, b);
13126
13127   //  AloBhi = psllqi(AloBhi, 32);
13128   //  AhiBlo = psllqi(AhiBlo, 32);
13129   //  return AloBlo + AloBhi + AhiBlo;
13130
13131   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13132   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13133
13134   // Bit cast to 32-bit vectors for MULUDQ
13135   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13136                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13137   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13138   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13139   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13140   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13141
13142   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13143   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13144   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13145
13146   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13147   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13148
13149   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13150   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13151 }
13152
13153 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13154                              SelectionDAG &DAG) {
13155   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13156   EVT VT = Op0.getValueType();
13157   SDLoc dl(Op);
13158
13159   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13160          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13161
13162   // Get the high parts.
13163   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13164   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13165   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13166
13167   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13168   // ints.
13169   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13170   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13171   unsigned Opcode =
13172       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13173   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13174                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13175   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13176                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13177
13178   // Shuffle it back into the right order.
13179   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13180   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13181   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13182   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13183
13184   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13185   // unsigned multiply.
13186   if (IsSigned && !Subtarget->hasSSE41()) {
13187     SDValue ShAmt =
13188         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13189     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13190                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13191     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13192                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13193
13194     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13195     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13196   }
13197
13198   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13199 }
13200
13201 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13202                                          const X86Subtarget *Subtarget) {
13203   MVT VT = Op.getSimpleValueType();
13204   SDLoc dl(Op);
13205   SDValue R = Op.getOperand(0);
13206   SDValue Amt = Op.getOperand(1);
13207
13208   // Optimize shl/srl/sra with constant shift amount.
13209   if (isSplatVector(Amt.getNode())) {
13210     SDValue SclrAmt = Amt->getOperand(0);
13211     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13212       uint64_t ShiftAmt = C->getZExtValue();
13213
13214       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13215           (Subtarget->hasInt256() &&
13216            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13217           (Subtarget->hasAVX512() &&
13218            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13219         if (Op.getOpcode() == ISD::SHL)
13220           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13221                                             DAG);
13222         if (Op.getOpcode() == ISD::SRL)
13223           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13224                                             DAG);
13225         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13226           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13227                                             DAG);
13228       }
13229
13230       if (VT == MVT::v16i8) {
13231         if (Op.getOpcode() == ISD::SHL) {
13232           // Make a large shift.
13233           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13234                                                    MVT::v8i16, R, ShiftAmt,
13235                                                    DAG);
13236           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13237           // Zero out the rightmost bits.
13238           SmallVector<SDValue, 16> V(16,
13239                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13240                                                      MVT::i8));
13241           return DAG.getNode(ISD::AND, dl, VT, SHL,
13242                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13243         }
13244         if (Op.getOpcode() == ISD::SRL) {
13245           // Make a large shift.
13246           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13247                                                    MVT::v8i16, R, ShiftAmt,
13248                                                    DAG);
13249           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13250           // Zero out the leftmost bits.
13251           SmallVector<SDValue, 16> V(16,
13252                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13253                                                      MVT::i8));
13254           return DAG.getNode(ISD::AND, dl, VT, SRL,
13255                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13256         }
13257         if (Op.getOpcode() == ISD::SRA) {
13258           if (ShiftAmt == 7) {
13259             // R s>> 7  ===  R s< 0
13260             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13261             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13262           }
13263
13264           // R s>> a === ((R u>> a) ^ m) - m
13265           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13266           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13267                                                          MVT::i8));
13268           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13269           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13270           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13271           return Res;
13272         }
13273         llvm_unreachable("Unknown shift opcode.");
13274       }
13275
13276       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13277         if (Op.getOpcode() == ISD::SHL) {
13278           // Make a large shift.
13279           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13280                                                    MVT::v16i16, R, ShiftAmt,
13281                                                    DAG);
13282           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13283           // Zero out the rightmost bits.
13284           SmallVector<SDValue, 32> V(32,
13285                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13286                                                      MVT::i8));
13287           return DAG.getNode(ISD::AND, dl, VT, SHL,
13288                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13289         }
13290         if (Op.getOpcode() == ISD::SRL) {
13291           // Make a large shift.
13292           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13293                                                    MVT::v16i16, R, ShiftAmt,
13294                                                    DAG);
13295           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13296           // Zero out the leftmost bits.
13297           SmallVector<SDValue, 32> V(32,
13298                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13299                                                      MVT::i8));
13300           return DAG.getNode(ISD::AND, dl, VT, SRL,
13301                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13302         }
13303         if (Op.getOpcode() == ISD::SRA) {
13304           if (ShiftAmt == 7) {
13305             // R s>> 7  ===  R s< 0
13306             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13307             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13308           }
13309
13310           // R s>> a === ((R u>> a) ^ m) - m
13311           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13312           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13313                                                          MVT::i8));
13314           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13315           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13316           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13317           return Res;
13318         }
13319         llvm_unreachable("Unknown shift opcode.");
13320       }
13321     }
13322   }
13323
13324   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13325   if (!Subtarget->is64Bit() &&
13326       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13327       Amt.getOpcode() == ISD::BITCAST &&
13328       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13329     Amt = Amt.getOperand(0);
13330     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13331                      VT.getVectorNumElements();
13332     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13333     uint64_t ShiftAmt = 0;
13334     for (unsigned i = 0; i != Ratio; ++i) {
13335       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13336       if (!C)
13337         return SDValue();
13338       // 6 == Log2(64)
13339       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13340     }
13341     // Check remaining shift amounts.
13342     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13343       uint64_t ShAmt = 0;
13344       for (unsigned j = 0; j != Ratio; ++j) {
13345         ConstantSDNode *C =
13346           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13347         if (!C)
13348           return SDValue();
13349         // 6 == Log2(64)
13350         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13351       }
13352       if (ShAmt != ShiftAmt)
13353         return SDValue();
13354     }
13355     switch (Op.getOpcode()) {
13356     default:
13357       llvm_unreachable("Unknown shift opcode!");
13358     case ISD::SHL:
13359       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13360                                         DAG);
13361     case ISD::SRL:
13362       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13363                                         DAG);
13364     case ISD::SRA:
13365       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13366                                         DAG);
13367     }
13368   }
13369
13370   return SDValue();
13371 }
13372
13373 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13374                                         const X86Subtarget* Subtarget) {
13375   MVT VT = Op.getSimpleValueType();
13376   SDLoc dl(Op);
13377   SDValue R = Op.getOperand(0);
13378   SDValue Amt = Op.getOperand(1);
13379
13380   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13381       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13382       (Subtarget->hasInt256() &&
13383        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13384         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13385        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13386     SDValue BaseShAmt;
13387     EVT EltVT = VT.getVectorElementType();
13388
13389     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13390       unsigned NumElts = VT.getVectorNumElements();
13391       unsigned i, j;
13392       for (i = 0; i != NumElts; ++i) {
13393         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13394           continue;
13395         break;
13396       }
13397       for (j = i; j != NumElts; ++j) {
13398         SDValue Arg = Amt.getOperand(j);
13399         if (Arg.getOpcode() == ISD::UNDEF) continue;
13400         if (Arg != Amt.getOperand(i))
13401           break;
13402       }
13403       if (i != NumElts && j == NumElts)
13404         BaseShAmt = Amt.getOperand(i);
13405     } else {
13406       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13407         Amt = Amt.getOperand(0);
13408       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13409                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13410         SDValue InVec = Amt.getOperand(0);
13411         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13412           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13413           unsigned i = 0;
13414           for (; i != NumElts; ++i) {
13415             SDValue Arg = InVec.getOperand(i);
13416             if (Arg.getOpcode() == ISD::UNDEF) continue;
13417             BaseShAmt = Arg;
13418             break;
13419           }
13420         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13421            if (ConstantSDNode *C =
13422                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13423              unsigned SplatIdx =
13424                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13425              if (C->getZExtValue() == SplatIdx)
13426                BaseShAmt = InVec.getOperand(1);
13427            }
13428         }
13429         if (!BaseShAmt.getNode())
13430           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13431                                   DAG.getIntPtrConstant(0));
13432       }
13433     }
13434
13435     if (BaseShAmt.getNode()) {
13436       if (EltVT.bitsGT(MVT::i32))
13437         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13438       else if (EltVT.bitsLT(MVT::i32))
13439         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13440
13441       switch (Op.getOpcode()) {
13442       default:
13443         llvm_unreachable("Unknown shift opcode!");
13444       case ISD::SHL:
13445         switch (VT.SimpleTy) {
13446         default: return SDValue();
13447         case MVT::v2i64:
13448         case MVT::v4i32:
13449         case MVT::v8i16:
13450         case MVT::v4i64:
13451         case MVT::v8i32:
13452         case MVT::v16i16:
13453         case MVT::v16i32:
13454         case MVT::v8i64:
13455           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13456         }
13457       case ISD::SRA:
13458         switch (VT.SimpleTy) {
13459         default: return SDValue();
13460         case MVT::v4i32:
13461         case MVT::v8i16:
13462         case MVT::v8i32:
13463         case MVT::v16i16:
13464         case MVT::v16i32:
13465         case MVT::v8i64:
13466           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13467         }
13468       case ISD::SRL:
13469         switch (VT.SimpleTy) {
13470         default: return SDValue();
13471         case MVT::v2i64:
13472         case MVT::v4i32:
13473         case MVT::v8i16:
13474         case MVT::v4i64:
13475         case MVT::v8i32:
13476         case MVT::v16i16:
13477         case MVT::v16i32:
13478         case MVT::v8i64:
13479           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13480         }
13481       }
13482     }
13483   }
13484
13485   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13486   if (!Subtarget->is64Bit() &&
13487       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13488       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13489       Amt.getOpcode() == ISD::BITCAST &&
13490       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13491     Amt = Amt.getOperand(0);
13492     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13493                      VT.getVectorNumElements();
13494     std::vector<SDValue> Vals(Ratio);
13495     for (unsigned i = 0; i != Ratio; ++i)
13496       Vals[i] = Amt.getOperand(i);
13497     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13498       for (unsigned j = 0; j != Ratio; ++j)
13499         if (Vals[j] != Amt.getOperand(i + j))
13500           return SDValue();
13501     }
13502     switch (Op.getOpcode()) {
13503     default:
13504       llvm_unreachable("Unknown shift opcode!");
13505     case ISD::SHL:
13506       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13507     case ISD::SRL:
13508       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13509     case ISD::SRA:
13510       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13511     }
13512   }
13513
13514   return SDValue();
13515 }
13516
13517 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13518                           SelectionDAG &DAG) {
13519
13520   MVT VT = Op.getSimpleValueType();
13521   SDLoc dl(Op);
13522   SDValue R = Op.getOperand(0);
13523   SDValue Amt = Op.getOperand(1);
13524   SDValue V;
13525
13526   if (!Subtarget->hasSSE2())
13527     return SDValue();
13528
13529   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13530   if (V.getNode())
13531     return V;
13532
13533   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13534   if (V.getNode())
13535       return V;
13536
13537   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13538     return Op;
13539   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13540   if (Subtarget->hasInt256()) {
13541     if (Op.getOpcode() == ISD::SRL &&
13542         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13543          VT == MVT::v4i64 || VT == MVT::v8i32))
13544       return Op;
13545     if (Op.getOpcode() == ISD::SHL &&
13546         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13547          VT == MVT::v4i64 || VT == MVT::v8i32))
13548       return Op;
13549     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13550       return Op;
13551   }
13552
13553   // If possible, lower this packed shift into a vector multiply instead of
13554   // expanding it into a sequence of scalar shifts.
13555   // Do this only if the vector shift count is a constant build_vector.
13556   if (Op.getOpcode() == ISD::SHL && 
13557       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13558        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13559       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13560     SmallVector<SDValue, 8> Elts;
13561     EVT SVT = VT.getScalarType();
13562     unsigned SVTBits = SVT.getSizeInBits();
13563     const APInt &One = APInt(SVTBits, 1);
13564     unsigned NumElems = VT.getVectorNumElements();
13565
13566     for (unsigned i=0; i !=NumElems; ++i) {
13567       SDValue Op = Amt->getOperand(i);
13568       if (Op->getOpcode() == ISD::UNDEF) {
13569         Elts.push_back(Op);
13570         continue;
13571       }
13572
13573       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13574       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13575       uint64_t ShAmt = C.getZExtValue();
13576       if (ShAmt >= SVTBits) {
13577         Elts.push_back(DAG.getUNDEF(SVT));
13578         continue;
13579       }
13580       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13581     }
13582     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13583     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13584   }
13585
13586   // Lower SHL with variable shift amount.
13587   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13588     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13589
13590     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13591     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13592     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13593     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13594   }
13595
13596   // If possible, lower this shift as a sequence of two shifts by
13597   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13598   // Example:
13599   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13600   //
13601   // Could be rewritten as:
13602   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13603   //
13604   // The advantage is that the two shifts from the example would be
13605   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13606   // the vector shift into four scalar shifts plus four pairs of vector
13607   // insert/extract.
13608   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13609       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13610     unsigned TargetOpcode = X86ISD::MOVSS;
13611     bool CanBeSimplified;
13612     // The splat value for the first packed shift (the 'X' from the example).
13613     SDValue Amt1 = Amt->getOperand(0);
13614     // The splat value for the second packed shift (the 'Y' from the example).
13615     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13616                                         Amt->getOperand(2);
13617
13618     // See if it is possible to replace this node with a sequence of
13619     // two shifts followed by a MOVSS/MOVSD
13620     if (VT == MVT::v4i32) {
13621       // Check if it is legal to use a MOVSS.
13622       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13623                         Amt2 == Amt->getOperand(3);
13624       if (!CanBeSimplified) {
13625         // Otherwise, check if we can still simplify this node using a MOVSD.
13626         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13627                           Amt->getOperand(2) == Amt->getOperand(3);
13628         TargetOpcode = X86ISD::MOVSD;
13629         Amt2 = Amt->getOperand(2);
13630       }
13631     } else {
13632       // Do similar checks for the case where the machine value type
13633       // is MVT::v8i16.
13634       CanBeSimplified = Amt1 == Amt->getOperand(1);
13635       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13636         CanBeSimplified = Amt2 == Amt->getOperand(i);
13637
13638       if (!CanBeSimplified) {
13639         TargetOpcode = X86ISD::MOVSD;
13640         CanBeSimplified = true;
13641         Amt2 = Amt->getOperand(4);
13642         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13643           CanBeSimplified = Amt1 == Amt->getOperand(i);
13644         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13645           CanBeSimplified = Amt2 == Amt->getOperand(j);
13646       }
13647     }
13648     
13649     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13650         isa<ConstantSDNode>(Amt2)) {
13651       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13652       EVT CastVT = MVT::v4i32;
13653       SDValue Splat1 = 
13654         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13655       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13656       SDValue Splat2 = 
13657         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13658       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13659       if (TargetOpcode == X86ISD::MOVSD)
13660         CastVT = MVT::v2i64;
13661       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13662       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13663       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13664                                             BitCast1, DAG);
13665       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13666     }
13667   }
13668
13669   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13670     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13671
13672     // a = a << 5;
13673     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13674     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13675
13676     // Turn 'a' into a mask suitable for VSELECT
13677     SDValue VSelM = DAG.getConstant(0x80, VT);
13678     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13679     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13680
13681     SDValue CM1 = DAG.getConstant(0x0f, VT);
13682     SDValue CM2 = DAG.getConstant(0x3f, VT);
13683
13684     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13685     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13686     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13687     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13688     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13689
13690     // a += a
13691     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13692     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13693     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13694
13695     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13696     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13697     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13698     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13699     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13700
13701     // a += a
13702     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13703     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13704     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13705
13706     // return VSELECT(r, r+r, a);
13707     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13708                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13709     return R;
13710   }
13711
13712   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13713   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13714   // solution better.
13715   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13716     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13717     unsigned ExtOpc =
13718         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13719     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13720     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13721     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13722                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13723     }
13724
13725   // Decompose 256-bit shifts into smaller 128-bit shifts.
13726   if (VT.is256BitVector()) {
13727     unsigned NumElems = VT.getVectorNumElements();
13728     MVT EltVT = VT.getVectorElementType();
13729     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13730
13731     // Extract the two vectors
13732     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13733     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13734
13735     // Recreate the shift amount vectors
13736     SDValue Amt1, Amt2;
13737     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13738       // Constant shift amount
13739       SmallVector<SDValue, 4> Amt1Csts;
13740       SmallVector<SDValue, 4> Amt2Csts;
13741       for (unsigned i = 0; i != NumElems/2; ++i)
13742         Amt1Csts.push_back(Amt->getOperand(i));
13743       for (unsigned i = NumElems/2; i != NumElems; ++i)
13744         Amt2Csts.push_back(Amt->getOperand(i));
13745
13746       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13747       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13748     } else {
13749       // Variable shift amount
13750       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13751       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13752     }
13753
13754     // Issue new vector shifts for the smaller types
13755     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13756     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13757
13758     // Concatenate the result back
13759     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13760   }
13761
13762   return SDValue();
13763 }
13764
13765 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13766   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13767   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13768   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13769   // has only one use.
13770   SDNode *N = Op.getNode();
13771   SDValue LHS = N->getOperand(0);
13772   SDValue RHS = N->getOperand(1);
13773   unsigned BaseOp = 0;
13774   unsigned Cond = 0;
13775   SDLoc DL(Op);
13776   switch (Op.getOpcode()) {
13777   default: llvm_unreachable("Unknown ovf instruction!");
13778   case ISD::SADDO:
13779     // A subtract of one will be selected as a INC. Note that INC doesn't
13780     // set CF, so we can't do this for UADDO.
13781     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13782       if (C->isOne()) {
13783         BaseOp = X86ISD::INC;
13784         Cond = X86::COND_O;
13785         break;
13786       }
13787     BaseOp = X86ISD::ADD;
13788     Cond = X86::COND_O;
13789     break;
13790   case ISD::UADDO:
13791     BaseOp = X86ISD::ADD;
13792     Cond = X86::COND_B;
13793     break;
13794   case ISD::SSUBO:
13795     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13796     // set CF, so we can't do this for USUBO.
13797     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13798       if (C->isOne()) {
13799         BaseOp = X86ISD::DEC;
13800         Cond = X86::COND_O;
13801         break;
13802       }
13803     BaseOp = X86ISD::SUB;
13804     Cond = X86::COND_O;
13805     break;
13806   case ISD::USUBO:
13807     BaseOp = X86ISD::SUB;
13808     Cond = X86::COND_B;
13809     break;
13810   case ISD::SMULO:
13811     BaseOp = X86ISD::SMUL;
13812     Cond = X86::COND_O;
13813     break;
13814   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13815     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13816                                  MVT::i32);
13817     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13818
13819     SDValue SetCC =
13820       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13821                   DAG.getConstant(X86::COND_O, MVT::i32),
13822                   SDValue(Sum.getNode(), 2));
13823
13824     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13825   }
13826   }
13827
13828   // Also sets EFLAGS.
13829   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13830   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13831
13832   SDValue SetCC =
13833     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13834                 DAG.getConstant(Cond, MVT::i32),
13835                 SDValue(Sum.getNode(), 1));
13836
13837   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13838 }
13839
13840 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13841                                                   SelectionDAG &DAG) const {
13842   SDLoc dl(Op);
13843   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13844   MVT VT = Op.getSimpleValueType();
13845
13846   if (!Subtarget->hasSSE2() || !VT.isVector())
13847     return SDValue();
13848
13849   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13850                       ExtraVT.getScalarType().getSizeInBits();
13851
13852   switch (VT.SimpleTy) {
13853     default: return SDValue();
13854     case MVT::v8i32:
13855     case MVT::v16i16:
13856       if (!Subtarget->hasFp256())
13857         return SDValue();
13858       if (!Subtarget->hasInt256()) {
13859         // needs to be split
13860         unsigned NumElems = VT.getVectorNumElements();
13861
13862         // Extract the LHS vectors
13863         SDValue LHS = Op.getOperand(0);
13864         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13865         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13866
13867         MVT EltVT = VT.getVectorElementType();
13868         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13869
13870         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13871         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13872         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13873                                    ExtraNumElems/2);
13874         SDValue Extra = DAG.getValueType(ExtraVT);
13875
13876         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13877         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13878
13879         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13880       }
13881       // fall through
13882     case MVT::v4i32:
13883     case MVT::v8i16: {
13884       SDValue Op0 = Op.getOperand(0);
13885       SDValue Op00 = Op0.getOperand(0);
13886       SDValue Tmp1;
13887       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13888       if (Op0.getOpcode() == ISD::BITCAST &&
13889           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13890         // (sext (vzext x)) -> (vsext x)
13891         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13892         if (Tmp1.getNode()) {
13893           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13894           // This folding is only valid when the in-reg type is a vector of i8,
13895           // i16, or i32.
13896           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13897               ExtraEltVT == MVT::i32) {
13898             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13899             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13900                    "This optimization is invalid without a VZEXT.");
13901             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13902           }
13903           Op0 = Tmp1;
13904         }
13905       }
13906
13907       // If the above didn't work, then just use Shift-Left + Shift-Right.
13908       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13909                                         DAG);
13910       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13911                                         DAG);
13912     }
13913   }
13914 }
13915
13916 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13917                                  SelectionDAG &DAG) {
13918   SDLoc dl(Op);
13919   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13920     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13921   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13922     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13923
13924   // The only fence that needs an instruction is a sequentially-consistent
13925   // cross-thread fence.
13926   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13927     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13928     // no-sse2). There isn't any reason to disable it if the target processor
13929     // supports it.
13930     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13931       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13932
13933     SDValue Chain = Op.getOperand(0);
13934     SDValue Zero = DAG.getConstant(0, MVT::i32);
13935     SDValue Ops[] = {
13936       DAG.getRegister(X86::ESP, MVT::i32), // Base
13937       DAG.getTargetConstant(1, MVT::i8),   // Scale
13938       DAG.getRegister(0, MVT::i32),        // Index
13939       DAG.getTargetConstant(0, MVT::i32),  // Disp
13940       DAG.getRegister(0, MVT::i32),        // Segment.
13941       Zero,
13942       Chain
13943     };
13944     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13945     return SDValue(Res, 0);
13946   }
13947
13948   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13949   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13950 }
13951
13952 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13953                              SelectionDAG &DAG) {
13954   MVT T = Op.getSimpleValueType();
13955   SDLoc DL(Op);
13956   unsigned Reg = 0;
13957   unsigned size = 0;
13958   switch(T.SimpleTy) {
13959   default: llvm_unreachable("Invalid value type!");
13960   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13961   case MVT::i16: Reg = X86::AX;  size = 2; break;
13962   case MVT::i32: Reg = X86::EAX; size = 4; break;
13963   case MVT::i64:
13964     assert(Subtarget->is64Bit() && "Node not type legal!");
13965     Reg = X86::RAX; size = 8;
13966     break;
13967   }
13968   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13969                                     Op.getOperand(2), SDValue());
13970   SDValue Ops[] = { cpIn.getValue(0),
13971                     Op.getOperand(1),
13972                     Op.getOperand(3),
13973                     DAG.getTargetConstant(size, MVT::i8),
13974                     cpIn.getValue(1) };
13975   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13976   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13977   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13978                                            Ops, T, MMO);
13979   SDValue cpOut =
13980     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13981   return cpOut;
13982 }
13983
13984 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13985                             SelectionDAG &DAG) {
13986   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13987   MVT DstVT = Op.getSimpleValueType();
13988   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13989          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13990   assert((DstVT == MVT::i64 ||
13991           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13992          "Unexpected custom BITCAST");
13993   // i64 <=> MMX conversions are Legal.
13994   if (SrcVT==MVT::i64 && DstVT.isVector())
13995     return Op;
13996   if (DstVT==MVT::i64 && SrcVT.isVector())
13997     return Op;
13998   // MMX <=> MMX conversions are Legal.
13999   if (SrcVT.isVector() && DstVT.isVector())
14000     return Op;
14001   // All other conversions need to be expanded.
14002   return SDValue();
14003 }
14004
14005 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14006   SDNode *Node = Op.getNode();
14007   SDLoc dl(Node);
14008   EVT T = Node->getValueType(0);
14009   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14010                               DAG.getConstant(0, T), Node->getOperand(2));
14011   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14012                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14013                        Node->getOperand(0),
14014                        Node->getOperand(1), negOp,
14015                        cast<AtomicSDNode>(Node)->getMemOperand(),
14016                        cast<AtomicSDNode>(Node)->getOrdering(),
14017                        cast<AtomicSDNode>(Node)->getSynchScope());
14018 }
14019
14020 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14021   SDNode *Node = Op.getNode();
14022   SDLoc dl(Node);
14023   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14024
14025   // Convert seq_cst store -> xchg
14026   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14027   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14028   //        (The only way to get a 16-byte store is cmpxchg16b)
14029   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14030   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14031       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14032     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14033                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14034                                  Node->getOperand(0),
14035                                  Node->getOperand(1), Node->getOperand(2),
14036                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14037                                  cast<AtomicSDNode>(Node)->getOrdering(),
14038                                  cast<AtomicSDNode>(Node)->getSynchScope());
14039     return Swap.getValue(1);
14040   }
14041   // Other atomic stores have a simple pattern.
14042   return Op;
14043 }
14044
14045 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14046   EVT VT = Op.getNode()->getSimpleValueType(0);
14047
14048   // Let legalize expand this if it isn't a legal type yet.
14049   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14050     return SDValue();
14051
14052   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14053
14054   unsigned Opc;
14055   bool ExtraOp = false;
14056   switch (Op.getOpcode()) {
14057   default: llvm_unreachable("Invalid code");
14058   case ISD::ADDC: Opc = X86ISD::ADD; break;
14059   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14060   case ISD::SUBC: Opc = X86ISD::SUB; break;
14061   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14062   }
14063
14064   if (!ExtraOp)
14065     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14066                        Op.getOperand(1));
14067   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14068                      Op.getOperand(1), Op.getOperand(2));
14069 }
14070
14071 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14072                             SelectionDAG &DAG) {
14073   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14074
14075   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14076   // which returns the values as { float, float } (in XMM0) or
14077   // { double, double } (which is returned in XMM0, XMM1).
14078   SDLoc dl(Op);
14079   SDValue Arg = Op.getOperand(0);
14080   EVT ArgVT = Arg.getValueType();
14081   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14082
14083   TargetLowering::ArgListTy Args;
14084   TargetLowering::ArgListEntry Entry;
14085
14086   Entry.Node = Arg;
14087   Entry.Ty = ArgTy;
14088   Entry.isSExt = false;
14089   Entry.isZExt = false;
14090   Args.push_back(Entry);
14091
14092   bool isF64 = ArgVT == MVT::f64;
14093   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14094   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14095   // the results are returned via SRet in memory.
14096   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14098   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14099
14100   Type *RetTy = isF64
14101     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14102     : (Type*)VectorType::get(ArgTy, 4);
14103   TargetLowering::
14104     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14105                          false, false, false, false, 0,
14106                          CallingConv::C, /*isTaillCall=*/false,
14107                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14108                          Callee, Args, DAG, dl);
14109   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14110
14111   if (isF64)
14112     // Returned in xmm0 and xmm1.
14113     return CallResult.first;
14114
14115   // Returned in bits 0:31 and 32:64 xmm0.
14116   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14117                                CallResult.first, DAG.getIntPtrConstant(0));
14118   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14119                                CallResult.first, DAG.getIntPtrConstant(1));
14120   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14121   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14122 }
14123
14124 /// LowerOperation - Provide custom lowering hooks for some operations.
14125 ///
14126 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14127   switch (Op.getOpcode()) {
14128   default: llvm_unreachable("Should not custom lower this!");
14129   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14130   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14131   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14132   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14133   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14134   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14135   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14136   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14137   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14138   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14139   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14140   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14141   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14142   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14143   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14144   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14145   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14146   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14147   case ISD::SHL_PARTS:
14148   case ISD::SRA_PARTS:
14149   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14150   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14151   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14152   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14153   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14154   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14155   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14156   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14157   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14158   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14159   case ISD::FABS:               return LowerFABS(Op, DAG);
14160   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14161   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14162   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14163   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14164   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14165   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14166   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14167   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14168   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14169   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14170   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14171   case ISD::INTRINSIC_VOID:
14172   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14173   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14174   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14175   case ISD::FRAME_TO_ARGS_OFFSET:
14176                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14177   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14178   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14179   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14180   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14181   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14182   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14183   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14184   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14185   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14186   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14187   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14188   case ISD::UMUL_LOHI:
14189   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14190   case ISD::SRA:
14191   case ISD::SRL:
14192   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14193   case ISD::SADDO:
14194   case ISD::UADDO:
14195   case ISD::SSUBO:
14196   case ISD::USUBO:
14197   case ISD::SMULO:
14198   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14199   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14200   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14201   case ISD::ADDC:
14202   case ISD::ADDE:
14203   case ISD::SUBC:
14204   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14205   case ISD::ADD:                return LowerADD(Op, DAG);
14206   case ISD::SUB:                return LowerSUB(Op, DAG);
14207   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14208   }
14209 }
14210
14211 static void ReplaceATOMIC_LOAD(SDNode *Node,
14212                                   SmallVectorImpl<SDValue> &Results,
14213                                   SelectionDAG &DAG) {
14214   SDLoc dl(Node);
14215   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14216
14217   // Convert wide load -> cmpxchg8b/cmpxchg16b
14218   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14219   //        (The only way to get a 16-byte load is cmpxchg16b)
14220   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14221   SDValue Zero = DAG.getConstant(0, VT);
14222   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14223                                Node->getOperand(0),
14224                                Node->getOperand(1), Zero, Zero,
14225                                cast<AtomicSDNode>(Node)->getMemOperand(),
14226                                cast<AtomicSDNode>(Node)->getOrdering(),
14227                                cast<AtomicSDNode>(Node)->getOrdering(),
14228                                cast<AtomicSDNode>(Node)->getSynchScope());
14229   Results.push_back(Swap.getValue(0));
14230   Results.push_back(Swap.getValue(1));
14231 }
14232
14233 static void
14234 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14235                         SelectionDAG &DAG, unsigned NewOp) {
14236   SDLoc dl(Node);
14237   assert (Node->getValueType(0) == MVT::i64 &&
14238           "Only know how to expand i64 atomics");
14239
14240   SDValue Chain = Node->getOperand(0);
14241   SDValue In1 = Node->getOperand(1);
14242   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14243                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14244   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14245                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14246   SDValue Ops[] = { Chain, In1, In2L, In2H };
14247   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14248   SDValue Result =
14249     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14250                             cast<MemSDNode>(Node)->getMemOperand());
14251   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14252   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14253   Results.push_back(Result.getValue(2));
14254 }
14255
14256 /// ReplaceNodeResults - Replace a node with an illegal result type
14257 /// with a new node built out of custom code.
14258 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14259                                            SmallVectorImpl<SDValue>&Results,
14260                                            SelectionDAG &DAG) const {
14261   SDLoc dl(N);
14262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14263   switch (N->getOpcode()) {
14264   default:
14265     llvm_unreachable("Do not know how to custom type legalize this operation!");
14266   case ISD::SIGN_EXTEND_INREG:
14267   case ISD::ADDC:
14268   case ISD::ADDE:
14269   case ISD::SUBC:
14270   case ISD::SUBE:
14271     // We don't want to expand or promote these.
14272     return;
14273   case ISD::FP_TO_SINT:
14274   case ISD::FP_TO_UINT: {
14275     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14276
14277     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14278       return;
14279
14280     std::pair<SDValue,SDValue> Vals =
14281         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14282     SDValue FIST = Vals.first, StackSlot = Vals.second;
14283     if (FIST.getNode()) {
14284       EVT VT = N->getValueType(0);
14285       // Return a load from the stack slot.
14286       if (StackSlot.getNode())
14287         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14288                                       MachinePointerInfo(),
14289                                       false, false, false, 0));
14290       else
14291         Results.push_back(FIST);
14292     }
14293     return;
14294   }
14295   case ISD::UINT_TO_FP: {
14296     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14297     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14298         N->getValueType(0) != MVT::v2f32)
14299       return;
14300     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14301                                  N->getOperand(0));
14302     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14303                                      MVT::f64);
14304     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14305     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14306                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14307     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14308     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14309     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14310     return;
14311   }
14312   case ISD::FP_ROUND: {
14313     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14314         return;
14315     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14316     Results.push_back(V);
14317     return;
14318   }
14319   case ISD::INTRINSIC_W_CHAIN: {
14320     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14321     switch (IntNo) {
14322     default : llvm_unreachable("Do not know how to custom type "
14323                                "legalize this intrinsic operation!");
14324     case Intrinsic::x86_rdtsc:
14325       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14326                                      Results);
14327     case Intrinsic::x86_rdtscp:
14328       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14329                                      Results);
14330     }
14331   }
14332   case ISD::READCYCLECOUNTER: {
14333     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14334                                    Results);
14335   }
14336   case ISD::ATOMIC_CMP_SWAP: {
14337     EVT T = N->getValueType(0);
14338     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14339     bool Regs64bit = T == MVT::i128;
14340     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14341     SDValue cpInL, cpInH;
14342     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14343                         DAG.getConstant(0, HalfT));
14344     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14345                         DAG.getConstant(1, HalfT));
14346     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14347                              Regs64bit ? X86::RAX : X86::EAX,
14348                              cpInL, SDValue());
14349     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14350                              Regs64bit ? X86::RDX : X86::EDX,
14351                              cpInH, cpInL.getValue(1));
14352     SDValue swapInL, swapInH;
14353     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14354                           DAG.getConstant(0, HalfT));
14355     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14356                           DAG.getConstant(1, HalfT));
14357     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14358                                Regs64bit ? X86::RBX : X86::EBX,
14359                                swapInL, cpInH.getValue(1));
14360     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14361                                Regs64bit ? X86::RCX : X86::ECX,
14362                                swapInH, swapInL.getValue(1));
14363     SDValue Ops[] = { swapInH.getValue(0),
14364                       N->getOperand(1),
14365                       swapInH.getValue(1) };
14366     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14367     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14368     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14369                                   X86ISD::LCMPXCHG8_DAG;
14370     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14371     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14372                                         Regs64bit ? X86::RAX : X86::EAX,
14373                                         HalfT, Result.getValue(1));
14374     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14375                                         Regs64bit ? X86::RDX : X86::EDX,
14376                                         HalfT, cpOutL.getValue(2));
14377     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14378     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14379     Results.push_back(cpOutH.getValue(1));
14380     return;
14381   }
14382   case ISD::ATOMIC_LOAD_ADD:
14383   case ISD::ATOMIC_LOAD_AND:
14384   case ISD::ATOMIC_LOAD_NAND:
14385   case ISD::ATOMIC_LOAD_OR:
14386   case ISD::ATOMIC_LOAD_SUB:
14387   case ISD::ATOMIC_LOAD_XOR:
14388   case ISD::ATOMIC_LOAD_MAX:
14389   case ISD::ATOMIC_LOAD_MIN:
14390   case ISD::ATOMIC_LOAD_UMAX:
14391   case ISD::ATOMIC_LOAD_UMIN:
14392   case ISD::ATOMIC_SWAP: {
14393     unsigned Opc;
14394     switch (N->getOpcode()) {
14395     default: llvm_unreachable("Unexpected opcode");
14396     case ISD::ATOMIC_LOAD_ADD:
14397       Opc = X86ISD::ATOMADD64_DAG;
14398       break;
14399     case ISD::ATOMIC_LOAD_AND:
14400       Opc = X86ISD::ATOMAND64_DAG;
14401       break;
14402     case ISD::ATOMIC_LOAD_NAND:
14403       Opc = X86ISD::ATOMNAND64_DAG;
14404       break;
14405     case ISD::ATOMIC_LOAD_OR:
14406       Opc = X86ISD::ATOMOR64_DAG;
14407       break;
14408     case ISD::ATOMIC_LOAD_SUB:
14409       Opc = X86ISD::ATOMSUB64_DAG;
14410       break;
14411     case ISD::ATOMIC_LOAD_XOR:
14412       Opc = X86ISD::ATOMXOR64_DAG;
14413       break;
14414     case ISD::ATOMIC_LOAD_MAX:
14415       Opc = X86ISD::ATOMMAX64_DAG;
14416       break;
14417     case ISD::ATOMIC_LOAD_MIN:
14418       Opc = X86ISD::ATOMMIN64_DAG;
14419       break;
14420     case ISD::ATOMIC_LOAD_UMAX:
14421       Opc = X86ISD::ATOMUMAX64_DAG;
14422       break;
14423     case ISD::ATOMIC_LOAD_UMIN:
14424       Opc = X86ISD::ATOMUMIN64_DAG;
14425       break;
14426     case ISD::ATOMIC_SWAP:
14427       Opc = X86ISD::ATOMSWAP64_DAG;
14428       break;
14429     }
14430     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14431     return;
14432   }
14433   case ISD::ATOMIC_LOAD:
14434     ReplaceATOMIC_LOAD(N, Results, DAG);
14435   }
14436 }
14437
14438 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14439   switch (Opcode) {
14440   default: return nullptr;
14441   case X86ISD::BSF:                return "X86ISD::BSF";
14442   case X86ISD::BSR:                return "X86ISD::BSR";
14443   case X86ISD::SHLD:               return "X86ISD::SHLD";
14444   case X86ISD::SHRD:               return "X86ISD::SHRD";
14445   case X86ISD::FAND:               return "X86ISD::FAND";
14446   case X86ISD::FANDN:              return "X86ISD::FANDN";
14447   case X86ISD::FOR:                return "X86ISD::FOR";
14448   case X86ISD::FXOR:               return "X86ISD::FXOR";
14449   case X86ISD::FSRL:               return "X86ISD::FSRL";
14450   case X86ISD::FILD:               return "X86ISD::FILD";
14451   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14452   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14453   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14454   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14455   case X86ISD::FLD:                return "X86ISD::FLD";
14456   case X86ISD::FST:                return "X86ISD::FST";
14457   case X86ISD::CALL:               return "X86ISD::CALL";
14458   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14459   case X86ISD::BT:                 return "X86ISD::BT";
14460   case X86ISD::CMP:                return "X86ISD::CMP";
14461   case X86ISD::COMI:               return "X86ISD::COMI";
14462   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14463   case X86ISD::CMPM:               return "X86ISD::CMPM";
14464   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14465   case X86ISD::SETCC:              return "X86ISD::SETCC";
14466   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14467   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14468   case X86ISD::CMOV:               return "X86ISD::CMOV";
14469   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14470   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14471   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14472   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14473   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14474   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14475   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14476   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14477   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14478   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14479   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14480   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14481   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14482   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14483   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14484   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14485   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14486   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14487   case X86ISD::HADD:               return "X86ISD::HADD";
14488   case X86ISD::HSUB:               return "X86ISD::HSUB";
14489   case X86ISD::FHADD:              return "X86ISD::FHADD";
14490   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14491   case X86ISD::UMAX:               return "X86ISD::UMAX";
14492   case X86ISD::UMIN:               return "X86ISD::UMIN";
14493   case X86ISD::SMAX:               return "X86ISD::SMAX";
14494   case X86ISD::SMIN:               return "X86ISD::SMIN";
14495   case X86ISD::FMAX:               return "X86ISD::FMAX";
14496   case X86ISD::FMIN:               return "X86ISD::FMIN";
14497   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14498   case X86ISD::FMINC:              return "X86ISD::FMINC";
14499   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14500   case X86ISD::FRCP:               return "X86ISD::FRCP";
14501   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14502   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14503   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14504   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14505   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14506   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14507   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14508   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14509   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14510   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14511   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14512   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14513   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14514   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14515   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14516   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14517   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14518   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14519   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14520   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14521   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14522   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14523   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14524   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14525   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14526   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14527   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14528   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14529   case X86ISD::VSHL:               return "X86ISD::VSHL";
14530   case X86ISD::VSRL:               return "X86ISD::VSRL";
14531   case X86ISD::VSRA:               return "X86ISD::VSRA";
14532   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14533   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14534   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14535   case X86ISD::CMPP:               return "X86ISD::CMPP";
14536   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14537   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14538   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14539   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14540   case X86ISD::ADD:                return "X86ISD::ADD";
14541   case X86ISD::SUB:                return "X86ISD::SUB";
14542   case X86ISD::ADC:                return "X86ISD::ADC";
14543   case X86ISD::SBB:                return "X86ISD::SBB";
14544   case X86ISD::SMUL:               return "X86ISD::SMUL";
14545   case X86ISD::UMUL:               return "X86ISD::UMUL";
14546   case X86ISD::INC:                return "X86ISD::INC";
14547   case X86ISD::DEC:                return "X86ISD::DEC";
14548   case X86ISD::OR:                 return "X86ISD::OR";
14549   case X86ISD::XOR:                return "X86ISD::XOR";
14550   case X86ISD::AND:                return "X86ISD::AND";
14551   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14552   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14553   case X86ISD::PTEST:              return "X86ISD::PTEST";
14554   case X86ISD::TESTP:              return "X86ISD::TESTP";
14555   case X86ISD::TESTM:              return "X86ISD::TESTM";
14556   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14557   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14558   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14559   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14560   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14561   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14562   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14563   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14564   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14565   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14566   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14567   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14568   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14569   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14570   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14571   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14572   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14573   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14574   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14575   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14576   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14577   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14578   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14579   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14580   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14581   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14582   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14583   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14584   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14585   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14586   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14587   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14588   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14589   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14590   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14591   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14592   case X86ISD::SAHF:               return "X86ISD::SAHF";
14593   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14594   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14595   case X86ISD::FMADD:              return "X86ISD::FMADD";
14596   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14597   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14598   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14599   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14600   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14601   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14602   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14603   case X86ISD::XTEST:              return "X86ISD::XTEST";
14604   }
14605 }
14606
14607 // isLegalAddressingMode - Return true if the addressing mode represented
14608 // by AM is legal for this target, for a load/store of the specified type.
14609 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14610                                               Type *Ty) const {
14611   // X86 supports extremely general addressing modes.
14612   CodeModel::Model M = getTargetMachine().getCodeModel();
14613   Reloc::Model R = getTargetMachine().getRelocationModel();
14614
14615   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14616   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14617     return false;
14618
14619   if (AM.BaseGV) {
14620     unsigned GVFlags =
14621       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14622
14623     // If a reference to this global requires an extra load, we can't fold it.
14624     if (isGlobalStubReference(GVFlags))
14625       return false;
14626
14627     // If BaseGV requires a register for the PIC base, we cannot also have a
14628     // BaseReg specified.
14629     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14630       return false;
14631
14632     // If lower 4G is not available, then we must use rip-relative addressing.
14633     if ((M != CodeModel::Small || R != Reloc::Static) &&
14634         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14635       return false;
14636   }
14637
14638   switch (AM.Scale) {
14639   case 0:
14640   case 1:
14641   case 2:
14642   case 4:
14643   case 8:
14644     // These scales always work.
14645     break;
14646   case 3:
14647   case 5:
14648   case 9:
14649     // These scales are formed with basereg+scalereg.  Only accept if there is
14650     // no basereg yet.
14651     if (AM.HasBaseReg)
14652       return false;
14653     break;
14654   default:  // Other stuff never works.
14655     return false;
14656   }
14657
14658   return true;
14659 }
14660
14661 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14662   unsigned Bits = Ty->getScalarSizeInBits();
14663
14664   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14665   // particularly cheaper than those without.
14666   if (Bits == 8)
14667     return false;
14668
14669   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14670   // variable shifts just as cheap as scalar ones.
14671   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14672     return false;
14673
14674   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14675   // fully general vector.
14676   return true;
14677 }
14678
14679 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14680   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14681     return false;
14682   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14683   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14684   return NumBits1 > NumBits2;
14685 }
14686
14687 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14688   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14689     return false;
14690
14691   if (!isTypeLegal(EVT::getEVT(Ty1)))
14692     return false;
14693
14694   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14695
14696   // Assuming the caller doesn't have a zeroext or signext return parameter,
14697   // truncation all the way down to i1 is valid.
14698   return true;
14699 }
14700
14701 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14702   return isInt<32>(Imm);
14703 }
14704
14705 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14706   // Can also use sub to handle negated immediates.
14707   return isInt<32>(Imm);
14708 }
14709
14710 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14711   if (!VT1.isInteger() || !VT2.isInteger())
14712     return false;
14713   unsigned NumBits1 = VT1.getSizeInBits();
14714   unsigned NumBits2 = VT2.getSizeInBits();
14715   return NumBits1 > NumBits2;
14716 }
14717
14718 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14719   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14720   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14721 }
14722
14723 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14724   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14725   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14726 }
14727
14728 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14729   EVT VT1 = Val.getValueType();
14730   if (isZExtFree(VT1, VT2))
14731     return true;
14732
14733   if (Val.getOpcode() != ISD::LOAD)
14734     return false;
14735
14736   if (!VT1.isSimple() || !VT1.isInteger() ||
14737       !VT2.isSimple() || !VT2.isInteger())
14738     return false;
14739
14740   switch (VT1.getSimpleVT().SimpleTy) {
14741   default: break;
14742   case MVT::i8:
14743   case MVT::i16:
14744   case MVT::i32:
14745     // X86 has 8, 16, and 32-bit zero-extending loads.
14746     return true;
14747   }
14748
14749   return false;
14750 }
14751
14752 bool
14753 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14754   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14755     return false;
14756
14757   VT = VT.getScalarType();
14758
14759   if (!VT.isSimple())
14760     return false;
14761
14762   switch (VT.getSimpleVT().SimpleTy) {
14763   case MVT::f32:
14764   case MVT::f64:
14765     return true;
14766   default:
14767     break;
14768   }
14769
14770   return false;
14771 }
14772
14773 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14774   // i16 instructions are longer (0x66 prefix) and potentially slower.
14775   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14776 }
14777
14778 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14779 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14780 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14781 /// are assumed to be legal.
14782 bool
14783 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14784                                       EVT VT) const {
14785   if (!VT.isSimple())
14786     return false;
14787
14788   MVT SVT = VT.getSimpleVT();
14789
14790   // Very little shuffling can be done for 64-bit vectors right now.
14791   if (VT.getSizeInBits() == 64)
14792     return false;
14793
14794   // FIXME: pshufb, blends, shifts.
14795   return (SVT.getVectorNumElements() == 2 ||
14796           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14797           isMOVLMask(M, SVT) ||
14798           isSHUFPMask(M, SVT) ||
14799           isPSHUFDMask(M, SVT) ||
14800           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14801           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14802           isPALIGNRMask(M, SVT, Subtarget) ||
14803           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14804           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14805           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14806           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14807 }
14808
14809 bool
14810 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14811                                           EVT VT) const {
14812   if (!VT.isSimple())
14813     return false;
14814
14815   MVT SVT = VT.getSimpleVT();
14816   unsigned NumElts = SVT.getVectorNumElements();
14817   // FIXME: This collection of masks seems suspect.
14818   if (NumElts == 2)
14819     return true;
14820   if (NumElts == 4 && SVT.is128BitVector()) {
14821     return (isMOVLMask(Mask, SVT)  ||
14822             isCommutedMOVLMask(Mask, SVT, true) ||
14823             isSHUFPMask(Mask, SVT) ||
14824             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14825   }
14826   return false;
14827 }
14828
14829 //===----------------------------------------------------------------------===//
14830 //                           X86 Scheduler Hooks
14831 //===----------------------------------------------------------------------===//
14832
14833 /// Utility function to emit xbegin specifying the start of an RTM region.
14834 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14835                                      const TargetInstrInfo *TII) {
14836   DebugLoc DL = MI->getDebugLoc();
14837
14838   const BasicBlock *BB = MBB->getBasicBlock();
14839   MachineFunction::iterator I = MBB;
14840   ++I;
14841
14842   // For the v = xbegin(), we generate
14843   //
14844   // thisMBB:
14845   //  xbegin sinkMBB
14846   //
14847   // mainMBB:
14848   //  eax = -1
14849   //
14850   // sinkMBB:
14851   //  v = eax
14852
14853   MachineBasicBlock *thisMBB = MBB;
14854   MachineFunction *MF = MBB->getParent();
14855   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14856   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14857   MF->insert(I, mainMBB);
14858   MF->insert(I, sinkMBB);
14859
14860   // Transfer the remainder of BB and its successor edges to sinkMBB.
14861   sinkMBB->splice(sinkMBB->begin(), MBB,
14862                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14863   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14864
14865   // thisMBB:
14866   //  xbegin sinkMBB
14867   //  # fallthrough to mainMBB
14868   //  # abortion to sinkMBB
14869   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14870   thisMBB->addSuccessor(mainMBB);
14871   thisMBB->addSuccessor(sinkMBB);
14872
14873   // mainMBB:
14874   //  EAX = -1
14875   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14876   mainMBB->addSuccessor(sinkMBB);
14877
14878   // sinkMBB:
14879   // EAX is live into the sinkMBB
14880   sinkMBB->addLiveIn(X86::EAX);
14881   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14882           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14883     .addReg(X86::EAX);
14884
14885   MI->eraseFromParent();
14886   return sinkMBB;
14887 }
14888
14889 // Get CMPXCHG opcode for the specified data type.
14890 static unsigned getCmpXChgOpcode(EVT VT) {
14891   switch (VT.getSimpleVT().SimpleTy) {
14892   case MVT::i8:  return X86::LCMPXCHG8;
14893   case MVT::i16: return X86::LCMPXCHG16;
14894   case MVT::i32: return X86::LCMPXCHG32;
14895   case MVT::i64: return X86::LCMPXCHG64;
14896   default:
14897     break;
14898   }
14899   llvm_unreachable("Invalid operand size!");
14900 }
14901
14902 // Get LOAD opcode for the specified data type.
14903 static unsigned getLoadOpcode(EVT VT) {
14904   switch (VT.getSimpleVT().SimpleTy) {
14905   case MVT::i8:  return X86::MOV8rm;
14906   case MVT::i16: return X86::MOV16rm;
14907   case MVT::i32: return X86::MOV32rm;
14908   case MVT::i64: return X86::MOV64rm;
14909   default:
14910     break;
14911   }
14912   llvm_unreachable("Invalid operand size!");
14913 }
14914
14915 // Get opcode of the non-atomic one from the specified atomic instruction.
14916 static unsigned getNonAtomicOpcode(unsigned Opc) {
14917   switch (Opc) {
14918   case X86::ATOMAND8:  return X86::AND8rr;
14919   case X86::ATOMAND16: return X86::AND16rr;
14920   case X86::ATOMAND32: return X86::AND32rr;
14921   case X86::ATOMAND64: return X86::AND64rr;
14922   case X86::ATOMOR8:   return X86::OR8rr;
14923   case X86::ATOMOR16:  return X86::OR16rr;
14924   case X86::ATOMOR32:  return X86::OR32rr;
14925   case X86::ATOMOR64:  return X86::OR64rr;
14926   case X86::ATOMXOR8:  return X86::XOR8rr;
14927   case X86::ATOMXOR16: return X86::XOR16rr;
14928   case X86::ATOMXOR32: return X86::XOR32rr;
14929   case X86::ATOMXOR64: return X86::XOR64rr;
14930   }
14931   llvm_unreachable("Unhandled atomic-load-op opcode!");
14932 }
14933
14934 // Get opcode of the non-atomic one from the specified atomic instruction with
14935 // extra opcode.
14936 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14937                                                unsigned &ExtraOpc) {
14938   switch (Opc) {
14939   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14940   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14941   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14942   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14943   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14944   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14945   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14946   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14947   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14948   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14949   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14950   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14951   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14952   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14953   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14954   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14955   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14956   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14957   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14958   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14959   }
14960   llvm_unreachable("Unhandled atomic-load-op opcode!");
14961 }
14962
14963 // Get opcode of the non-atomic one from the specified atomic instruction for
14964 // 64-bit data type on 32-bit target.
14965 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14966   switch (Opc) {
14967   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14968   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14969   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14970   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14971   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14972   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14973   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14974   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14975   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14976   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14977   }
14978   llvm_unreachable("Unhandled atomic-load-op opcode!");
14979 }
14980
14981 // Get opcode of the non-atomic one from the specified atomic instruction for
14982 // 64-bit data type on 32-bit target with extra opcode.
14983 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14984                                                    unsigned &HiOpc,
14985                                                    unsigned &ExtraOpc) {
14986   switch (Opc) {
14987   case X86::ATOMNAND6432:
14988     ExtraOpc = X86::NOT32r;
14989     HiOpc = X86::AND32rr;
14990     return X86::AND32rr;
14991   }
14992   llvm_unreachable("Unhandled atomic-load-op opcode!");
14993 }
14994
14995 // Get pseudo CMOV opcode from the specified data type.
14996 static unsigned getPseudoCMOVOpc(EVT VT) {
14997   switch (VT.getSimpleVT().SimpleTy) {
14998   case MVT::i8:  return X86::CMOV_GR8;
14999   case MVT::i16: return X86::CMOV_GR16;
15000   case MVT::i32: return X86::CMOV_GR32;
15001   default:
15002     break;
15003   }
15004   llvm_unreachable("Unknown CMOV opcode!");
15005 }
15006
15007 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15008 // They will be translated into a spin-loop or compare-exchange loop from
15009 //
15010 //    ...
15011 //    dst = atomic-fetch-op MI.addr, MI.val
15012 //    ...
15013 //
15014 // to
15015 //
15016 //    ...
15017 //    t1 = LOAD MI.addr
15018 // loop:
15019 //    t4 = phi(t1, t3 / loop)
15020 //    t2 = OP MI.val, t4
15021 //    EAX = t4
15022 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15023 //    t3 = EAX
15024 //    JNE loop
15025 // sink:
15026 //    dst = t3
15027 //    ...
15028 MachineBasicBlock *
15029 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15030                                        MachineBasicBlock *MBB) const {
15031   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15032   DebugLoc DL = MI->getDebugLoc();
15033
15034   MachineFunction *MF = MBB->getParent();
15035   MachineRegisterInfo &MRI = MF->getRegInfo();
15036
15037   const BasicBlock *BB = MBB->getBasicBlock();
15038   MachineFunction::iterator I = MBB;
15039   ++I;
15040
15041   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15042          "Unexpected number of operands");
15043
15044   assert(MI->hasOneMemOperand() &&
15045          "Expected atomic-load-op to have one memoperand");
15046
15047   // Memory Reference
15048   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15049   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15050
15051   unsigned DstReg, SrcReg;
15052   unsigned MemOpndSlot;
15053
15054   unsigned CurOp = 0;
15055
15056   DstReg = MI->getOperand(CurOp++).getReg();
15057   MemOpndSlot = CurOp;
15058   CurOp += X86::AddrNumOperands;
15059   SrcReg = MI->getOperand(CurOp++).getReg();
15060
15061   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15062   MVT::SimpleValueType VT = *RC->vt_begin();
15063   unsigned t1 = MRI.createVirtualRegister(RC);
15064   unsigned t2 = MRI.createVirtualRegister(RC);
15065   unsigned t3 = MRI.createVirtualRegister(RC);
15066   unsigned t4 = MRI.createVirtualRegister(RC);
15067   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15068
15069   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15070   unsigned LOADOpc = getLoadOpcode(VT);
15071
15072   // For the atomic load-arith operator, we generate
15073   //
15074   //  thisMBB:
15075   //    t1 = LOAD [MI.addr]
15076   //  mainMBB:
15077   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15078   //    t1 = OP MI.val, EAX
15079   //    EAX = t4
15080   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15081   //    t3 = EAX
15082   //    JNE mainMBB
15083   //  sinkMBB:
15084   //    dst = t3
15085
15086   MachineBasicBlock *thisMBB = MBB;
15087   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15088   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15089   MF->insert(I, mainMBB);
15090   MF->insert(I, sinkMBB);
15091
15092   MachineInstrBuilder MIB;
15093
15094   // Transfer the remainder of BB and its successor edges to sinkMBB.
15095   sinkMBB->splice(sinkMBB->begin(), MBB,
15096                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15097   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15098
15099   // thisMBB:
15100   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15101   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15102     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15103     if (NewMO.isReg())
15104       NewMO.setIsKill(false);
15105     MIB.addOperand(NewMO);
15106   }
15107   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15108     unsigned flags = (*MMOI)->getFlags();
15109     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15110     MachineMemOperand *MMO =
15111       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15112                                (*MMOI)->getSize(),
15113                                (*MMOI)->getBaseAlignment(),
15114                                (*MMOI)->getTBAAInfo(),
15115                                (*MMOI)->getRanges());
15116     MIB.addMemOperand(MMO);
15117   }
15118
15119   thisMBB->addSuccessor(mainMBB);
15120
15121   // mainMBB:
15122   MachineBasicBlock *origMainMBB = mainMBB;
15123
15124   // Add a PHI.
15125   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15126                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15127
15128   unsigned Opc = MI->getOpcode();
15129   switch (Opc) {
15130   default:
15131     llvm_unreachable("Unhandled atomic-load-op opcode!");
15132   case X86::ATOMAND8:
15133   case X86::ATOMAND16:
15134   case X86::ATOMAND32:
15135   case X86::ATOMAND64:
15136   case X86::ATOMOR8:
15137   case X86::ATOMOR16:
15138   case X86::ATOMOR32:
15139   case X86::ATOMOR64:
15140   case X86::ATOMXOR8:
15141   case X86::ATOMXOR16:
15142   case X86::ATOMXOR32:
15143   case X86::ATOMXOR64: {
15144     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15145     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15146       .addReg(t4);
15147     break;
15148   }
15149   case X86::ATOMNAND8:
15150   case X86::ATOMNAND16:
15151   case X86::ATOMNAND32:
15152   case X86::ATOMNAND64: {
15153     unsigned Tmp = MRI.createVirtualRegister(RC);
15154     unsigned NOTOpc;
15155     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15156     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15157       .addReg(t4);
15158     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15159     break;
15160   }
15161   case X86::ATOMMAX8:
15162   case X86::ATOMMAX16:
15163   case X86::ATOMMAX32:
15164   case X86::ATOMMAX64:
15165   case X86::ATOMMIN8:
15166   case X86::ATOMMIN16:
15167   case X86::ATOMMIN32:
15168   case X86::ATOMMIN64:
15169   case X86::ATOMUMAX8:
15170   case X86::ATOMUMAX16:
15171   case X86::ATOMUMAX32:
15172   case X86::ATOMUMAX64:
15173   case X86::ATOMUMIN8:
15174   case X86::ATOMUMIN16:
15175   case X86::ATOMUMIN32:
15176   case X86::ATOMUMIN64: {
15177     unsigned CMPOpc;
15178     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15179
15180     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15181       .addReg(SrcReg)
15182       .addReg(t4);
15183
15184     if (Subtarget->hasCMov()) {
15185       if (VT != MVT::i8) {
15186         // Native support
15187         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15188           .addReg(SrcReg)
15189           .addReg(t4);
15190       } else {
15191         // Promote i8 to i32 to use CMOV32
15192         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15193         const TargetRegisterClass *RC32 =
15194           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15195         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15196         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15197         unsigned Tmp = MRI.createVirtualRegister(RC32);
15198
15199         unsigned Undef = MRI.createVirtualRegister(RC32);
15200         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15201
15202         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15203           .addReg(Undef)
15204           .addReg(SrcReg)
15205           .addImm(X86::sub_8bit);
15206         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15207           .addReg(Undef)
15208           .addReg(t4)
15209           .addImm(X86::sub_8bit);
15210
15211         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15212           .addReg(SrcReg32)
15213           .addReg(AccReg32);
15214
15215         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15216           .addReg(Tmp, 0, X86::sub_8bit);
15217       }
15218     } else {
15219       // Use pseudo select and lower them.
15220       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15221              "Invalid atomic-load-op transformation!");
15222       unsigned SelOpc = getPseudoCMOVOpc(VT);
15223       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15224       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15225       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15226               .addReg(SrcReg).addReg(t4)
15227               .addImm(CC);
15228       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15229       // Replace the original PHI node as mainMBB is changed after CMOV
15230       // lowering.
15231       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15232         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15233       Phi->eraseFromParent();
15234     }
15235     break;
15236   }
15237   }
15238
15239   // Copy PhyReg back from virtual register.
15240   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15241     .addReg(t4);
15242
15243   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15244   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15245     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15246     if (NewMO.isReg())
15247       NewMO.setIsKill(false);
15248     MIB.addOperand(NewMO);
15249   }
15250   MIB.addReg(t2);
15251   MIB.setMemRefs(MMOBegin, MMOEnd);
15252
15253   // Copy PhyReg back to virtual register.
15254   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15255     .addReg(PhyReg);
15256
15257   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15258
15259   mainMBB->addSuccessor(origMainMBB);
15260   mainMBB->addSuccessor(sinkMBB);
15261
15262   // sinkMBB:
15263   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15264           TII->get(TargetOpcode::COPY), DstReg)
15265     .addReg(t3);
15266
15267   MI->eraseFromParent();
15268   return sinkMBB;
15269 }
15270
15271 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15272 // instructions. They will be translated into a spin-loop or compare-exchange
15273 // loop from
15274 //
15275 //    ...
15276 //    dst = atomic-fetch-op MI.addr, MI.val
15277 //    ...
15278 //
15279 // to
15280 //
15281 //    ...
15282 //    t1L = LOAD [MI.addr + 0]
15283 //    t1H = LOAD [MI.addr + 4]
15284 // loop:
15285 //    t4L = phi(t1L, t3L / loop)
15286 //    t4H = phi(t1H, t3H / loop)
15287 //    t2L = OP MI.val.lo, t4L
15288 //    t2H = OP MI.val.hi, t4H
15289 //    EAX = t4L
15290 //    EDX = t4H
15291 //    EBX = t2L
15292 //    ECX = t2H
15293 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15294 //    t3L = EAX
15295 //    t3H = EDX
15296 //    JNE loop
15297 // sink:
15298 //    dstL = t3L
15299 //    dstH = t3H
15300 //    ...
15301 MachineBasicBlock *
15302 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15303                                            MachineBasicBlock *MBB) const {
15304   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15305   DebugLoc DL = MI->getDebugLoc();
15306
15307   MachineFunction *MF = MBB->getParent();
15308   MachineRegisterInfo &MRI = MF->getRegInfo();
15309
15310   const BasicBlock *BB = MBB->getBasicBlock();
15311   MachineFunction::iterator I = MBB;
15312   ++I;
15313
15314   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15315          "Unexpected number of operands");
15316
15317   assert(MI->hasOneMemOperand() &&
15318          "Expected atomic-load-op32 to have one memoperand");
15319
15320   // Memory Reference
15321   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15322   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15323
15324   unsigned DstLoReg, DstHiReg;
15325   unsigned SrcLoReg, SrcHiReg;
15326   unsigned MemOpndSlot;
15327
15328   unsigned CurOp = 0;
15329
15330   DstLoReg = MI->getOperand(CurOp++).getReg();
15331   DstHiReg = MI->getOperand(CurOp++).getReg();
15332   MemOpndSlot = CurOp;
15333   CurOp += X86::AddrNumOperands;
15334   SrcLoReg = MI->getOperand(CurOp++).getReg();
15335   SrcHiReg = MI->getOperand(CurOp++).getReg();
15336
15337   const TargetRegisterClass *RC = &X86::GR32RegClass;
15338   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15339
15340   unsigned t1L = MRI.createVirtualRegister(RC);
15341   unsigned t1H = MRI.createVirtualRegister(RC);
15342   unsigned t2L = MRI.createVirtualRegister(RC);
15343   unsigned t2H = MRI.createVirtualRegister(RC);
15344   unsigned t3L = MRI.createVirtualRegister(RC);
15345   unsigned t3H = MRI.createVirtualRegister(RC);
15346   unsigned t4L = MRI.createVirtualRegister(RC);
15347   unsigned t4H = MRI.createVirtualRegister(RC);
15348
15349   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15350   unsigned LOADOpc = X86::MOV32rm;
15351
15352   // For the atomic load-arith operator, we generate
15353   //
15354   //  thisMBB:
15355   //    t1L = LOAD [MI.addr + 0]
15356   //    t1H = LOAD [MI.addr + 4]
15357   //  mainMBB:
15358   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15359   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15360   //    t2L = OP MI.val.lo, t4L
15361   //    t2H = OP MI.val.hi, t4H
15362   //    EBX = t2L
15363   //    ECX = t2H
15364   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15365   //    t3L = EAX
15366   //    t3H = EDX
15367   //    JNE loop
15368   //  sinkMBB:
15369   //    dstL = t3L
15370   //    dstH = t3H
15371
15372   MachineBasicBlock *thisMBB = MBB;
15373   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15374   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15375   MF->insert(I, mainMBB);
15376   MF->insert(I, sinkMBB);
15377
15378   MachineInstrBuilder MIB;
15379
15380   // Transfer the remainder of BB and its successor edges to sinkMBB.
15381   sinkMBB->splice(sinkMBB->begin(), MBB,
15382                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15383   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15384
15385   // thisMBB:
15386   // Lo
15387   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15388   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15389     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15390     if (NewMO.isReg())
15391       NewMO.setIsKill(false);
15392     MIB.addOperand(NewMO);
15393   }
15394   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15395     unsigned flags = (*MMOI)->getFlags();
15396     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15397     MachineMemOperand *MMO =
15398       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15399                                (*MMOI)->getSize(),
15400                                (*MMOI)->getBaseAlignment(),
15401                                (*MMOI)->getTBAAInfo(),
15402                                (*MMOI)->getRanges());
15403     MIB.addMemOperand(MMO);
15404   };
15405   MachineInstr *LowMI = MIB;
15406
15407   // Hi
15408   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15409   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15410     if (i == X86::AddrDisp) {
15411       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15412     } else {
15413       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15414       if (NewMO.isReg())
15415         NewMO.setIsKill(false);
15416       MIB.addOperand(NewMO);
15417     }
15418   }
15419   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15420
15421   thisMBB->addSuccessor(mainMBB);
15422
15423   // mainMBB:
15424   MachineBasicBlock *origMainMBB = mainMBB;
15425
15426   // Add PHIs.
15427   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15428                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15429   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15430                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15431
15432   unsigned Opc = MI->getOpcode();
15433   switch (Opc) {
15434   default:
15435     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15436   case X86::ATOMAND6432:
15437   case X86::ATOMOR6432:
15438   case X86::ATOMXOR6432:
15439   case X86::ATOMADD6432:
15440   case X86::ATOMSUB6432: {
15441     unsigned HiOpc;
15442     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15443     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15444       .addReg(SrcLoReg);
15445     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15446       .addReg(SrcHiReg);
15447     break;
15448   }
15449   case X86::ATOMNAND6432: {
15450     unsigned HiOpc, NOTOpc;
15451     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15452     unsigned TmpL = MRI.createVirtualRegister(RC);
15453     unsigned TmpH = MRI.createVirtualRegister(RC);
15454     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15455       .addReg(t4L);
15456     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15457       .addReg(t4H);
15458     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15459     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15460     break;
15461   }
15462   case X86::ATOMMAX6432:
15463   case X86::ATOMMIN6432:
15464   case X86::ATOMUMAX6432:
15465   case X86::ATOMUMIN6432: {
15466     unsigned HiOpc;
15467     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15468     unsigned cL = MRI.createVirtualRegister(RC8);
15469     unsigned cH = MRI.createVirtualRegister(RC8);
15470     unsigned cL32 = MRI.createVirtualRegister(RC);
15471     unsigned cH32 = MRI.createVirtualRegister(RC);
15472     unsigned cc = MRI.createVirtualRegister(RC);
15473     // cl := cmp src_lo, lo
15474     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15475       .addReg(SrcLoReg).addReg(t4L);
15476     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15477     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15478     // ch := cmp src_hi, hi
15479     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15480       .addReg(SrcHiReg).addReg(t4H);
15481     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15482     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15483     // cc := if (src_hi == hi) ? cl : ch;
15484     if (Subtarget->hasCMov()) {
15485       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15486         .addReg(cH32).addReg(cL32);
15487     } else {
15488       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15489               .addReg(cH32).addReg(cL32)
15490               .addImm(X86::COND_E);
15491       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15492     }
15493     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15494     if (Subtarget->hasCMov()) {
15495       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15496         .addReg(SrcLoReg).addReg(t4L);
15497       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15498         .addReg(SrcHiReg).addReg(t4H);
15499     } else {
15500       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15501               .addReg(SrcLoReg).addReg(t4L)
15502               .addImm(X86::COND_NE);
15503       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15504       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15505       // 2nd CMOV lowering.
15506       mainMBB->addLiveIn(X86::EFLAGS);
15507       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15508               .addReg(SrcHiReg).addReg(t4H)
15509               .addImm(X86::COND_NE);
15510       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15511       // Replace the original PHI node as mainMBB is changed after CMOV
15512       // lowering.
15513       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15514         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15515       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15516         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15517       PhiL->eraseFromParent();
15518       PhiH->eraseFromParent();
15519     }
15520     break;
15521   }
15522   case X86::ATOMSWAP6432: {
15523     unsigned HiOpc;
15524     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15525     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15526     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15527     break;
15528   }
15529   }
15530
15531   // Copy EDX:EAX back from HiReg:LoReg
15532   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15533   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15534   // Copy ECX:EBX from t1H:t1L
15535   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15536   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15537
15538   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15539   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15540     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15541     if (NewMO.isReg())
15542       NewMO.setIsKill(false);
15543     MIB.addOperand(NewMO);
15544   }
15545   MIB.setMemRefs(MMOBegin, MMOEnd);
15546
15547   // Copy EDX:EAX back to t3H:t3L
15548   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15549   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15550
15551   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15552
15553   mainMBB->addSuccessor(origMainMBB);
15554   mainMBB->addSuccessor(sinkMBB);
15555
15556   // sinkMBB:
15557   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15558           TII->get(TargetOpcode::COPY), DstLoReg)
15559     .addReg(t3L);
15560   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15561           TII->get(TargetOpcode::COPY), DstHiReg)
15562     .addReg(t3H);
15563
15564   MI->eraseFromParent();
15565   return sinkMBB;
15566 }
15567
15568 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15569 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15570 // in the .td file.
15571 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15572                                        const TargetInstrInfo *TII) {
15573   unsigned Opc;
15574   switch (MI->getOpcode()) {
15575   default: llvm_unreachable("illegal opcode!");
15576   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15577   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15578   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15579   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15580   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15581   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15582   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15583   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15584   }
15585
15586   DebugLoc dl = MI->getDebugLoc();
15587   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15588
15589   unsigned NumArgs = MI->getNumOperands();
15590   for (unsigned i = 1; i < NumArgs; ++i) {
15591     MachineOperand &Op = MI->getOperand(i);
15592     if (!(Op.isReg() && Op.isImplicit()))
15593       MIB.addOperand(Op);
15594   }
15595   if (MI->hasOneMemOperand())
15596     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15597
15598   BuildMI(*BB, MI, dl,
15599     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15600     .addReg(X86::XMM0);
15601
15602   MI->eraseFromParent();
15603   return BB;
15604 }
15605
15606 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15607 // defs in an instruction pattern
15608 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15609                                        const TargetInstrInfo *TII) {
15610   unsigned Opc;
15611   switch (MI->getOpcode()) {
15612   default: llvm_unreachable("illegal opcode!");
15613   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15614   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15615   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15616   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15617   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15618   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15619   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15620   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15621   }
15622
15623   DebugLoc dl = MI->getDebugLoc();
15624   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15625
15626   unsigned NumArgs = MI->getNumOperands(); // remove the results
15627   for (unsigned i = 1; i < NumArgs; ++i) {
15628     MachineOperand &Op = MI->getOperand(i);
15629     if (!(Op.isReg() && Op.isImplicit()))
15630       MIB.addOperand(Op);
15631   }
15632   if (MI->hasOneMemOperand())
15633     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15634
15635   BuildMI(*BB, MI, dl,
15636     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15637     .addReg(X86::ECX);
15638
15639   MI->eraseFromParent();
15640   return BB;
15641 }
15642
15643 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15644                                        const TargetInstrInfo *TII,
15645                                        const X86Subtarget* Subtarget) {
15646   DebugLoc dl = MI->getDebugLoc();
15647
15648   // Address into RAX/EAX, other two args into ECX, EDX.
15649   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15650   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15651   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15652   for (int i = 0; i < X86::AddrNumOperands; ++i)
15653     MIB.addOperand(MI->getOperand(i));
15654
15655   unsigned ValOps = X86::AddrNumOperands;
15656   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15657     .addReg(MI->getOperand(ValOps).getReg());
15658   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15659     .addReg(MI->getOperand(ValOps+1).getReg());
15660
15661   // The instruction doesn't actually take any operands though.
15662   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15663
15664   MI->eraseFromParent(); // The pseudo is gone now.
15665   return BB;
15666 }
15667
15668 MachineBasicBlock *
15669 X86TargetLowering::EmitVAARG64WithCustomInserter(
15670                    MachineInstr *MI,
15671                    MachineBasicBlock *MBB) const {
15672   // Emit va_arg instruction on X86-64.
15673
15674   // Operands to this pseudo-instruction:
15675   // 0  ) Output        : destination address (reg)
15676   // 1-5) Input         : va_list address (addr, i64mem)
15677   // 6  ) ArgSize       : Size (in bytes) of vararg type
15678   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15679   // 8  ) Align         : Alignment of type
15680   // 9  ) EFLAGS (implicit-def)
15681
15682   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15683   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15684
15685   unsigned DestReg = MI->getOperand(0).getReg();
15686   MachineOperand &Base = MI->getOperand(1);
15687   MachineOperand &Scale = MI->getOperand(2);
15688   MachineOperand &Index = MI->getOperand(3);
15689   MachineOperand &Disp = MI->getOperand(4);
15690   MachineOperand &Segment = MI->getOperand(5);
15691   unsigned ArgSize = MI->getOperand(6).getImm();
15692   unsigned ArgMode = MI->getOperand(7).getImm();
15693   unsigned Align = MI->getOperand(8).getImm();
15694
15695   // Memory Reference
15696   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15697   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15698   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15699
15700   // Machine Information
15701   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15702   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15703   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15704   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15705   DebugLoc DL = MI->getDebugLoc();
15706
15707   // struct va_list {
15708   //   i32   gp_offset
15709   //   i32   fp_offset
15710   //   i64   overflow_area (address)
15711   //   i64   reg_save_area (address)
15712   // }
15713   // sizeof(va_list) = 24
15714   // alignment(va_list) = 8
15715
15716   unsigned TotalNumIntRegs = 6;
15717   unsigned TotalNumXMMRegs = 8;
15718   bool UseGPOffset = (ArgMode == 1);
15719   bool UseFPOffset = (ArgMode == 2);
15720   unsigned MaxOffset = TotalNumIntRegs * 8 +
15721                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15722
15723   /* Align ArgSize to a multiple of 8 */
15724   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15725   bool NeedsAlign = (Align > 8);
15726
15727   MachineBasicBlock *thisMBB = MBB;
15728   MachineBasicBlock *overflowMBB;
15729   MachineBasicBlock *offsetMBB;
15730   MachineBasicBlock *endMBB;
15731
15732   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15733   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15734   unsigned OffsetReg = 0;
15735
15736   if (!UseGPOffset && !UseFPOffset) {
15737     // If we only pull from the overflow region, we don't create a branch.
15738     // We don't need to alter control flow.
15739     OffsetDestReg = 0; // unused
15740     OverflowDestReg = DestReg;
15741
15742     offsetMBB = nullptr;
15743     overflowMBB = thisMBB;
15744     endMBB = thisMBB;
15745   } else {
15746     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15747     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15748     // If not, pull from overflow_area. (branch to overflowMBB)
15749     //
15750     //       thisMBB
15751     //         |     .
15752     //         |        .
15753     //     offsetMBB   overflowMBB
15754     //         |        .
15755     //         |     .
15756     //        endMBB
15757
15758     // Registers for the PHI in endMBB
15759     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15760     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15761
15762     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15763     MachineFunction *MF = MBB->getParent();
15764     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15765     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15766     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15767
15768     MachineFunction::iterator MBBIter = MBB;
15769     ++MBBIter;
15770
15771     // Insert the new basic blocks
15772     MF->insert(MBBIter, offsetMBB);
15773     MF->insert(MBBIter, overflowMBB);
15774     MF->insert(MBBIter, endMBB);
15775
15776     // Transfer the remainder of MBB and its successor edges to endMBB.
15777     endMBB->splice(endMBB->begin(), thisMBB,
15778                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15779     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15780
15781     // Make offsetMBB and overflowMBB successors of thisMBB
15782     thisMBB->addSuccessor(offsetMBB);
15783     thisMBB->addSuccessor(overflowMBB);
15784
15785     // endMBB is a successor of both offsetMBB and overflowMBB
15786     offsetMBB->addSuccessor(endMBB);
15787     overflowMBB->addSuccessor(endMBB);
15788
15789     // Load the offset value into a register
15790     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15791     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15792       .addOperand(Base)
15793       .addOperand(Scale)
15794       .addOperand(Index)
15795       .addDisp(Disp, UseFPOffset ? 4 : 0)
15796       .addOperand(Segment)
15797       .setMemRefs(MMOBegin, MMOEnd);
15798
15799     // Check if there is enough room left to pull this argument.
15800     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15801       .addReg(OffsetReg)
15802       .addImm(MaxOffset + 8 - ArgSizeA8);
15803
15804     // Branch to "overflowMBB" if offset >= max
15805     // Fall through to "offsetMBB" otherwise
15806     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15807       .addMBB(overflowMBB);
15808   }
15809
15810   // In offsetMBB, emit code to use the reg_save_area.
15811   if (offsetMBB) {
15812     assert(OffsetReg != 0);
15813
15814     // Read the reg_save_area address.
15815     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15816     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15817       .addOperand(Base)
15818       .addOperand(Scale)
15819       .addOperand(Index)
15820       .addDisp(Disp, 16)
15821       .addOperand(Segment)
15822       .setMemRefs(MMOBegin, MMOEnd);
15823
15824     // Zero-extend the offset
15825     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15826       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15827         .addImm(0)
15828         .addReg(OffsetReg)
15829         .addImm(X86::sub_32bit);
15830
15831     // Add the offset to the reg_save_area to get the final address.
15832     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15833       .addReg(OffsetReg64)
15834       .addReg(RegSaveReg);
15835
15836     // Compute the offset for the next argument
15837     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15838     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15839       .addReg(OffsetReg)
15840       .addImm(UseFPOffset ? 16 : 8);
15841
15842     // Store it back into the va_list.
15843     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15844       .addOperand(Base)
15845       .addOperand(Scale)
15846       .addOperand(Index)
15847       .addDisp(Disp, UseFPOffset ? 4 : 0)
15848       .addOperand(Segment)
15849       .addReg(NextOffsetReg)
15850       .setMemRefs(MMOBegin, MMOEnd);
15851
15852     // Jump to endMBB
15853     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15854       .addMBB(endMBB);
15855   }
15856
15857   //
15858   // Emit code to use overflow area
15859   //
15860
15861   // Load the overflow_area address into a register.
15862   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15863   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15864     .addOperand(Base)
15865     .addOperand(Scale)
15866     .addOperand(Index)
15867     .addDisp(Disp, 8)
15868     .addOperand(Segment)
15869     .setMemRefs(MMOBegin, MMOEnd);
15870
15871   // If we need to align it, do so. Otherwise, just copy the address
15872   // to OverflowDestReg.
15873   if (NeedsAlign) {
15874     // Align the overflow address
15875     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15876     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15877
15878     // aligned_addr = (addr + (align-1)) & ~(align-1)
15879     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15880       .addReg(OverflowAddrReg)
15881       .addImm(Align-1);
15882
15883     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15884       .addReg(TmpReg)
15885       .addImm(~(uint64_t)(Align-1));
15886   } else {
15887     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15888       .addReg(OverflowAddrReg);
15889   }
15890
15891   // Compute the next overflow address after this argument.
15892   // (the overflow address should be kept 8-byte aligned)
15893   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15894   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15895     .addReg(OverflowDestReg)
15896     .addImm(ArgSizeA8);
15897
15898   // Store the new overflow address.
15899   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15900     .addOperand(Base)
15901     .addOperand(Scale)
15902     .addOperand(Index)
15903     .addDisp(Disp, 8)
15904     .addOperand(Segment)
15905     .addReg(NextAddrReg)
15906     .setMemRefs(MMOBegin, MMOEnd);
15907
15908   // If we branched, emit the PHI to the front of endMBB.
15909   if (offsetMBB) {
15910     BuildMI(*endMBB, endMBB->begin(), DL,
15911             TII->get(X86::PHI), DestReg)
15912       .addReg(OffsetDestReg).addMBB(offsetMBB)
15913       .addReg(OverflowDestReg).addMBB(overflowMBB);
15914   }
15915
15916   // Erase the pseudo instruction
15917   MI->eraseFromParent();
15918
15919   return endMBB;
15920 }
15921
15922 MachineBasicBlock *
15923 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15924                                                  MachineInstr *MI,
15925                                                  MachineBasicBlock *MBB) const {
15926   // Emit code to save XMM registers to the stack. The ABI says that the
15927   // number of registers to save is given in %al, so it's theoretically
15928   // possible to do an indirect jump trick to avoid saving all of them,
15929   // however this code takes a simpler approach and just executes all
15930   // of the stores if %al is non-zero. It's less code, and it's probably
15931   // easier on the hardware branch predictor, and stores aren't all that
15932   // expensive anyway.
15933
15934   // Create the new basic blocks. One block contains all the XMM stores,
15935   // and one block is the final destination regardless of whether any
15936   // stores were performed.
15937   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15938   MachineFunction *F = MBB->getParent();
15939   MachineFunction::iterator MBBIter = MBB;
15940   ++MBBIter;
15941   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15942   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15943   F->insert(MBBIter, XMMSaveMBB);
15944   F->insert(MBBIter, EndMBB);
15945
15946   // Transfer the remainder of MBB and its successor edges to EndMBB.
15947   EndMBB->splice(EndMBB->begin(), MBB,
15948                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15949   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15950
15951   // The original block will now fall through to the XMM save block.
15952   MBB->addSuccessor(XMMSaveMBB);
15953   // The XMMSaveMBB will fall through to the end block.
15954   XMMSaveMBB->addSuccessor(EndMBB);
15955
15956   // Now add the instructions.
15957   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15958   DebugLoc DL = MI->getDebugLoc();
15959
15960   unsigned CountReg = MI->getOperand(0).getReg();
15961   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15962   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15963
15964   if (!Subtarget->isTargetWin64()) {
15965     // If %al is 0, branch around the XMM save block.
15966     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15967     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15968     MBB->addSuccessor(EndMBB);
15969   }
15970
15971   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15972   // that was just emitted, but clearly shouldn't be "saved".
15973   assert((MI->getNumOperands() <= 3 ||
15974           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15975           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15976          && "Expected last argument to be EFLAGS");
15977   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15978   // In the XMM save block, save all the XMM argument registers.
15979   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15980     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15981     MachineMemOperand *MMO =
15982       F->getMachineMemOperand(
15983           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15984         MachineMemOperand::MOStore,
15985         /*Size=*/16, /*Align=*/16);
15986     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15987       .addFrameIndex(RegSaveFrameIndex)
15988       .addImm(/*Scale=*/1)
15989       .addReg(/*IndexReg=*/0)
15990       .addImm(/*Disp=*/Offset)
15991       .addReg(/*Segment=*/0)
15992       .addReg(MI->getOperand(i).getReg())
15993       .addMemOperand(MMO);
15994   }
15995
15996   MI->eraseFromParent();   // The pseudo instruction is gone now.
15997
15998   return EndMBB;
15999 }
16000
16001 // The EFLAGS operand of SelectItr might be missing a kill marker
16002 // because there were multiple uses of EFLAGS, and ISel didn't know
16003 // which to mark. Figure out whether SelectItr should have had a
16004 // kill marker, and set it if it should. Returns the correct kill
16005 // marker value.
16006 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16007                                      MachineBasicBlock* BB,
16008                                      const TargetRegisterInfo* TRI) {
16009   // Scan forward through BB for a use/def of EFLAGS.
16010   MachineBasicBlock::iterator miI(std::next(SelectItr));
16011   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16012     const MachineInstr& mi = *miI;
16013     if (mi.readsRegister(X86::EFLAGS))
16014       return false;
16015     if (mi.definesRegister(X86::EFLAGS))
16016       break; // Should have kill-flag - update below.
16017   }
16018
16019   // If we hit the end of the block, check whether EFLAGS is live into a
16020   // successor.
16021   if (miI == BB->end()) {
16022     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16023                                           sEnd = BB->succ_end();
16024          sItr != sEnd; ++sItr) {
16025       MachineBasicBlock* succ = *sItr;
16026       if (succ->isLiveIn(X86::EFLAGS))
16027         return false;
16028     }
16029   }
16030
16031   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16032   // out. SelectMI should have a kill flag on EFLAGS.
16033   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16034   return true;
16035 }
16036
16037 MachineBasicBlock *
16038 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16039                                      MachineBasicBlock *BB) const {
16040   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16041   DebugLoc DL = MI->getDebugLoc();
16042
16043   // To "insert" a SELECT_CC instruction, we actually have to insert the
16044   // diamond control-flow pattern.  The incoming instruction knows the
16045   // destination vreg to set, the condition code register to branch on, the
16046   // true/false values to select between, and a branch opcode to use.
16047   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16048   MachineFunction::iterator It = BB;
16049   ++It;
16050
16051   //  thisMBB:
16052   //  ...
16053   //   TrueVal = ...
16054   //   cmpTY ccX, r1, r2
16055   //   bCC copy1MBB
16056   //   fallthrough --> copy0MBB
16057   MachineBasicBlock *thisMBB = BB;
16058   MachineFunction *F = BB->getParent();
16059   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16060   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16061   F->insert(It, copy0MBB);
16062   F->insert(It, sinkMBB);
16063
16064   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16065   // live into the sink and copy blocks.
16066   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16067   if (!MI->killsRegister(X86::EFLAGS) &&
16068       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16069     copy0MBB->addLiveIn(X86::EFLAGS);
16070     sinkMBB->addLiveIn(X86::EFLAGS);
16071   }
16072
16073   // Transfer the remainder of BB and its successor edges to sinkMBB.
16074   sinkMBB->splice(sinkMBB->begin(), BB,
16075                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16076   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16077
16078   // Add the true and fallthrough blocks as its successors.
16079   BB->addSuccessor(copy0MBB);
16080   BB->addSuccessor(sinkMBB);
16081
16082   // Create the conditional branch instruction.
16083   unsigned Opc =
16084     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16085   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16086
16087   //  copy0MBB:
16088   //   %FalseValue = ...
16089   //   # fallthrough to sinkMBB
16090   copy0MBB->addSuccessor(sinkMBB);
16091
16092   //  sinkMBB:
16093   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16094   //  ...
16095   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16096           TII->get(X86::PHI), MI->getOperand(0).getReg())
16097     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16098     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16099
16100   MI->eraseFromParent();   // The pseudo instruction is gone now.
16101   return sinkMBB;
16102 }
16103
16104 MachineBasicBlock *
16105 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16106                                         bool Is64Bit) const {
16107   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16108   DebugLoc DL = MI->getDebugLoc();
16109   MachineFunction *MF = BB->getParent();
16110   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16111
16112   assert(MF->shouldSplitStack());
16113
16114   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16115   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16116
16117   // BB:
16118   //  ... [Till the alloca]
16119   // If stacklet is not large enough, jump to mallocMBB
16120   //
16121   // bumpMBB:
16122   //  Allocate by subtracting from RSP
16123   //  Jump to continueMBB
16124   //
16125   // mallocMBB:
16126   //  Allocate by call to runtime
16127   //
16128   // continueMBB:
16129   //  ...
16130   //  [rest of original BB]
16131   //
16132
16133   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16134   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16135   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16136
16137   MachineRegisterInfo &MRI = MF->getRegInfo();
16138   const TargetRegisterClass *AddrRegClass =
16139     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16140
16141   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16142     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16143     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16144     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16145     sizeVReg = MI->getOperand(1).getReg(),
16146     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16147
16148   MachineFunction::iterator MBBIter = BB;
16149   ++MBBIter;
16150
16151   MF->insert(MBBIter, bumpMBB);
16152   MF->insert(MBBIter, mallocMBB);
16153   MF->insert(MBBIter, continueMBB);
16154
16155   continueMBB->splice(continueMBB->begin(), BB,
16156                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16157   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16158
16159   // Add code to the main basic block to check if the stack limit has been hit,
16160   // and if so, jump to mallocMBB otherwise to bumpMBB.
16161   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16162   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16163     .addReg(tmpSPVReg).addReg(sizeVReg);
16164   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16165     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16166     .addReg(SPLimitVReg);
16167   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16168
16169   // bumpMBB simply decreases the stack pointer, since we know the current
16170   // stacklet has enough space.
16171   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16172     .addReg(SPLimitVReg);
16173   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16174     .addReg(SPLimitVReg);
16175   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16176
16177   // Calls into a routine in libgcc to allocate more space from the heap.
16178   const uint32_t *RegMask =
16179     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16180   if (Is64Bit) {
16181     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16182       .addReg(sizeVReg);
16183     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16184       .addExternalSymbol("__morestack_allocate_stack_space")
16185       .addRegMask(RegMask)
16186       .addReg(X86::RDI, RegState::Implicit)
16187       .addReg(X86::RAX, RegState::ImplicitDefine);
16188   } else {
16189     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16190       .addImm(12);
16191     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16192     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16193       .addExternalSymbol("__morestack_allocate_stack_space")
16194       .addRegMask(RegMask)
16195       .addReg(X86::EAX, RegState::ImplicitDefine);
16196   }
16197
16198   if (!Is64Bit)
16199     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16200       .addImm(16);
16201
16202   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16203     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16204   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16205
16206   // Set up the CFG correctly.
16207   BB->addSuccessor(bumpMBB);
16208   BB->addSuccessor(mallocMBB);
16209   mallocMBB->addSuccessor(continueMBB);
16210   bumpMBB->addSuccessor(continueMBB);
16211
16212   // Take care of the PHI nodes.
16213   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16214           MI->getOperand(0).getReg())
16215     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16216     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16217
16218   // Delete the original pseudo instruction.
16219   MI->eraseFromParent();
16220
16221   // And we're done.
16222   return continueMBB;
16223 }
16224
16225 MachineBasicBlock *
16226 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16227                                           MachineBasicBlock *BB) const {
16228   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16229   DebugLoc DL = MI->getDebugLoc();
16230
16231   assert(!Subtarget->isTargetMacho());
16232
16233   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16234   // non-trivial part is impdef of ESP.
16235
16236   if (Subtarget->isTargetWin64()) {
16237     if (Subtarget->isTargetCygMing()) {
16238       // ___chkstk(Mingw64):
16239       // Clobbers R10, R11, RAX and EFLAGS.
16240       // Updates RSP.
16241       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16242         .addExternalSymbol("___chkstk")
16243         .addReg(X86::RAX, RegState::Implicit)
16244         .addReg(X86::RSP, RegState::Implicit)
16245         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16246         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16247         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16248     } else {
16249       // __chkstk(MSVCRT): does not update stack pointer.
16250       // Clobbers R10, R11 and EFLAGS.
16251       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16252         .addExternalSymbol("__chkstk")
16253         .addReg(X86::RAX, RegState::Implicit)
16254         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16255       // RAX has the offset to be subtracted from RSP.
16256       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16257         .addReg(X86::RSP)
16258         .addReg(X86::RAX);
16259     }
16260   } else {
16261     const char *StackProbeSymbol =
16262       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16263
16264     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16265       .addExternalSymbol(StackProbeSymbol)
16266       .addReg(X86::EAX, RegState::Implicit)
16267       .addReg(X86::ESP, RegState::Implicit)
16268       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16269       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16270       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16271   }
16272
16273   MI->eraseFromParent();   // The pseudo instruction is gone now.
16274   return BB;
16275 }
16276
16277 MachineBasicBlock *
16278 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16279                                       MachineBasicBlock *BB) const {
16280   // This is pretty easy.  We're taking the value that we received from
16281   // our load from the relocation, sticking it in either RDI (x86-64)
16282   // or EAX and doing an indirect call.  The return value will then
16283   // be in the normal return register.
16284   const X86InstrInfo *TII
16285     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16286   DebugLoc DL = MI->getDebugLoc();
16287   MachineFunction *F = BB->getParent();
16288
16289   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16290   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16291
16292   // Get a register mask for the lowered call.
16293   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16294   // proper register mask.
16295   const uint32_t *RegMask =
16296     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16297   if (Subtarget->is64Bit()) {
16298     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16299                                       TII->get(X86::MOV64rm), X86::RDI)
16300     .addReg(X86::RIP)
16301     .addImm(0).addReg(0)
16302     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16303                       MI->getOperand(3).getTargetFlags())
16304     .addReg(0);
16305     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16306     addDirectMem(MIB, X86::RDI);
16307     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16308   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16309     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16310                                       TII->get(X86::MOV32rm), X86::EAX)
16311     .addReg(0)
16312     .addImm(0).addReg(0)
16313     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16314                       MI->getOperand(3).getTargetFlags())
16315     .addReg(0);
16316     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16317     addDirectMem(MIB, X86::EAX);
16318     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16319   } else {
16320     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16321                                       TII->get(X86::MOV32rm), X86::EAX)
16322     .addReg(TII->getGlobalBaseReg(F))
16323     .addImm(0).addReg(0)
16324     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16325                       MI->getOperand(3).getTargetFlags())
16326     .addReg(0);
16327     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16328     addDirectMem(MIB, X86::EAX);
16329     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16330   }
16331
16332   MI->eraseFromParent(); // The pseudo instruction is gone now.
16333   return BB;
16334 }
16335
16336 MachineBasicBlock *
16337 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16338                                     MachineBasicBlock *MBB) const {
16339   DebugLoc DL = MI->getDebugLoc();
16340   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16341
16342   MachineFunction *MF = MBB->getParent();
16343   MachineRegisterInfo &MRI = MF->getRegInfo();
16344
16345   const BasicBlock *BB = MBB->getBasicBlock();
16346   MachineFunction::iterator I = MBB;
16347   ++I;
16348
16349   // Memory Reference
16350   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16351   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16352
16353   unsigned DstReg;
16354   unsigned MemOpndSlot = 0;
16355
16356   unsigned CurOp = 0;
16357
16358   DstReg = MI->getOperand(CurOp++).getReg();
16359   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16360   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16361   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16362   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16363
16364   MemOpndSlot = CurOp;
16365
16366   MVT PVT = getPointerTy();
16367   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16368          "Invalid Pointer Size!");
16369
16370   // For v = setjmp(buf), we generate
16371   //
16372   // thisMBB:
16373   //  buf[LabelOffset] = restoreMBB
16374   //  SjLjSetup restoreMBB
16375   //
16376   // mainMBB:
16377   //  v_main = 0
16378   //
16379   // sinkMBB:
16380   //  v = phi(main, restore)
16381   //
16382   // restoreMBB:
16383   //  v_restore = 1
16384
16385   MachineBasicBlock *thisMBB = MBB;
16386   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16387   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16388   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16389   MF->insert(I, mainMBB);
16390   MF->insert(I, sinkMBB);
16391   MF->push_back(restoreMBB);
16392
16393   MachineInstrBuilder MIB;
16394
16395   // Transfer the remainder of BB and its successor edges to sinkMBB.
16396   sinkMBB->splice(sinkMBB->begin(), MBB,
16397                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16398   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16399
16400   // thisMBB:
16401   unsigned PtrStoreOpc = 0;
16402   unsigned LabelReg = 0;
16403   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16404   Reloc::Model RM = getTargetMachine().getRelocationModel();
16405   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16406                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16407
16408   // Prepare IP either in reg or imm.
16409   if (!UseImmLabel) {
16410     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16411     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16412     LabelReg = MRI.createVirtualRegister(PtrRC);
16413     if (Subtarget->is64Bit()) {
16414       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16415               .addReg(X86::RIP)
16416               .addImm(0)
16417               .addReg(0)
16418               .addMBB(restoreMBB)
16419               .addReg(0);
16420     } else {
16421       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16422       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16423               .addReg(XII->getGlobalBaseReg(MF))
16424               .addImm(0)
16425               .addReg(0)
16426               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16427               .addReg(0);
16428     }
16429   } else
16430     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16431   // Store IP
16432   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16433   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16434     if (i == X86::AddrDisp)
16435       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16436     else
16437       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16438   }
16439   if (!UseImmLabel)
16440     MIB.addReg(LabelReg);
16441   else
16442     MIB.addMBB(restoreMBB);
16443   MIB.setMemRefs(MMOBegin, MMOEnd);
16444   // Setup
16445   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16446           .addMBB(restoreMBB);
16447
16448   const X86RegisterInfo *RegInfo =
16449     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16450   MIB.addRegMask(RegInfo->getNoPreservedMask());
16451   thisMBB->addSuccessor(mainMBB);
16452   thisMBB->addSuccessor(restoreMBB);
16453
16454   // mainMBB:
16455   //  EAX = 0
16456   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16457   mainMBB->addSuccessor(sinkMBB);
16458
16459   // sinkMBB:
16460   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16461           TII->get(X86::PHI), DstReg)
16462     .addReg(mainDstReg).addMBB(mainMBB)
16463     .addReg(restoreDstReg).addMBB(restoreMBB);
16464
16465   // restoreMBB:
16466   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16467   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16468   restoreMBB->addSuccessor(sinkMBB);
16469
16470   MI->eraseFromParent();
16471   return sinkMBB;
16472 }
16473
16474 MachineBasicBlock *
16475 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16476                                      MachineBasicBlock *MBB) const {
16477   DebugLoc DL = MI->getDebugLoc();
16478   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16479
16480   MachineFunction *MF = MBB->getParent();
16481   MachineRegisterInfo &MRI = MF->getRegInfo();
16482
16483   // Memory Reference
16484   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16485   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16486
16487   MVT PVT = getPointerTy();
16488   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16489          "Invalid Pointer Size!");
16490
16491   const TargetRegisterClass *RC =
16492     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16493   unsigned Tmp = MRI.createVirtualRegister(RC);
16494   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16495   const X86RegisterInfo *RegInfo =
16496     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16497   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16498   unsigned SP = RegInfo->getStackRegister();
16499
16500   MachineInstrBuilder MIB;
16501
16502   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16503   const int64_t SPOffset = 2 * PVT.getStoreSize();
16504
16505   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16506   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16507
16508   // Reload FP
16509   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16510   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16511     MIB.addOperand(MI->getOperand(i));
16512   MIB.setMemRefs(MMOBegin, MMOEnd);
16513   // Reload IP
16514   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16515   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16516     if (i == X86::AddrDisp)
16517       MIB.addDisp(MI->getOperand(i), LabelOffset);
16518     else
16519       MIB.addOperand(MI->getOperand(i));
16520   }
16521   MIB.setMemRefs(MMOBegin, MMOEnd);
16522   // Reload SP
16523   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16524   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16525     if (i == X86::AddrDisp)
16526       MIB.addDisp(MI->getOperand(i), SPOffset);
16527     else
16528       MIB.addOperand(MI->getOperand(i));
16529   }
16530   MIB.setMemRefs(MMOBegin, MMOEnd);
16531   // Jump
16532   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16533
16534   MI->eraseFromParent();
16535   return MBB;
16536 }
16537
16538 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16539 // accumulator loops. Writing back to the accumulator allows the coalescer
16540 // to remove extra copies in the loop.   
16541 MachineBasicBlock *
16542 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16543                                  MachineBasicBlock *MBB) const {
16544   MachineOperand &AddendOp = MI->getOperand(3);
16545
16546   // Bail out early if the addend isn't a register - we can't switch these.
16547   if (!AddendOp.isReg())
16548     return MBB;
16549
16550   MachineFunction &MF = *MBB->getParent();
16551   MachineRegisterInfo &MRI = MF.getRegInfo();
16552
16553   // Check whether the addend is defined by a PHI:
16554   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16555   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16556   if (!AddendDef.isPHI())
16557     return MBB;
16558
16559   // Look for the following pattern:
16560   // loop:
16561   //   %addend = phi [%entry, 0], [%loop, %result]
16562   //   ...
16563   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16564
16565   // Replace with:
16566   //   loop:
16567   //   %addend = phi [%entry, 0], [%loop, %result]
16568   //   ...
16569   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16570
16571   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16572     assert(AddendDef.getOperand(i).isReg());
16573     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16574     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16575     if (&PHISrcInst == MI) {
16576       // Found a matching instruction.
16577       unsigned NewFMAOpc = 0;
16578       switch (MI->getOpcode()) {
16579         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16580         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16581         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16582         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16583         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16584         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16585         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16586         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16587         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16588         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16589         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16590         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16591         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16592         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16593         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16594         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16595         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16596         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16597         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16598         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16599         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16600         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16601         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16602         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16603         default: llvm_unreachable("Unrecognized FMA variant.");
16604       }
16605
16606       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16607       MachineInstrBuilder MIB =
16608         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16609         .addOperand(MI->getOperand(0))
16610         .addOperand(MI->getOperand(3))
16611         .addOperand(MI->getOperand(2))
16612         .addOperand(MI->getOperand(1));
16613       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16614       MI->eraseFromParent();
16615     }
16616   }
16617
16618   return MBB;
16619 }
16620
16621 MachineBasicBlock *
16622 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16623                                                MachineBasicBlock *BB) const {
16624   switch (MI->getOpcode()) {
16625   default: llvm_unreachable("Unexpected instr type to insert");
16626   case X86::TAILJMPd64:
16627   case X86::TAILJMPr64:
16628   case X86::TAILJMPm64:
16629     llvm_unreachable("TAILJMP64 would not be touched here.");
16630   case X86::TCRETURNdi64:
16631   case X86::TCRETURNri64:
16632   case X86::TCRETURNmi64:
16633     return BB;
16634   case X86::WIN_ALLOCA:
16635     return EmitLoweredWinAlloca(MI, BB);
16636   case X86::SEG_ALLOCA_32:
16637     return EmitLoweredSegAlloca(MI, BB, false);
16638   case X86::SEG_ALLOCA_64:
16639     return EmitLoweredSegAlloca(MI, BB, true);
16640   case X86::TLSCall_32:
16641   case X86::TLSCall_64:
16642     return EmitLoweredTLSCall(MI, BB);
16643   case X86::CMOV_GR8:
16644   case X86::CMOV_FR32:
16645   case X86::CMOV_FR64:
16646   case X86::CMOV_V4F32:
16647   case X86::CMOV_V2F64:
16648   case X86::CMOV_V2I64:
16649   case X86::CMOV_V8F32:
16650   case X86::CMOV_V4F64:
16651   case X86::CMOV_V4I64:
16652   case X86::CMOV_V16F32:
16653   case X86::CMOV_V8F64:
16654   case X86::CMOV_V8I64:
16655   case X86::CMOV_GR16:
16656   case X86::CMOV_GR32:
16657   case X86::CMOV_RFP32:
16658   case X86::CMOV_RFP64:
16659   case X86::CMOV_RFP80:
16660     return EmitLoweredSelect(MI, BB);
16661
16662   case X86::FP32_TO_INT16_IN_MEM:
16663   case X86::FP32_TO_INT32_IN_MEM:
16664   case X86::FP32_TO_INT64_IN_MEM:
16665   case X86::FP64_TO_INT16_IN_MEM:
16666   case X86::FP64_TO_INT32_IN_MEM:
16667   case X86::FP64_TO_INT64_IN_MEM:
16668   case X86::FP80_TO_INT16_IN_MEM:
16669   case X86::FP80_TO_INT32_IN_MEM:
16670   case X86::FP80_TO_INT64_IN_MEM: {
16671     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16672     DebugLoc DL = MI->getDebugLoc();
16673
16674     // Change the floating point control register to use "round towards zero"
16675     // mode when truncating to an integer value.
16676     MachineFunction *F = BB->getParent();
16677     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16678     addFrameReference(BuildMI(*BB, MI, DL,
16679                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16680
16681     // Load the old value of the high byte of the control word...
16682     unsigned OldCW =
16683       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16684     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16685                       CWFrameIdx);
16686
16687     // Set the high part to be round to zero...
16688     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16689       .addImm(0xC7F);
16690
16691     // Reload the modified control word now...
16692     addFrameReference(BuildMI(*BB, MI, DL,
16693                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16694
16695     // Restore the memory image of control word to original value
16696     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16697       .addReg(OldCW);
16698
16699     // Get the X86 opcode to use.
16700     unsigned Opc;
16701     switch (MI->getOpcode()) {
16702     default: llvm_unreachable("illegal opcode!");
16703     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16704     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16705     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16706     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16707     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16708     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16709     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16710     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16711     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16712     }
16713
16714     X86AddressMode AM;
16715     MachineOperand &Op = MI->getOperand(0);
16716     if (Op.isReg()) {
16717       AM.BaseType = X86AddressMode::RegBase;
16718       AM.Base.Reg = Op.getReg();
16719     } else {
16720       AM.BaseType = X86AddressMode::FrameIndexBase;
16721       AM.Base.FrameIndex = Op.getIndex();
16722     }
16723     Op = MI->getOperand(1);
16724     if (Op.isImm())
16725       AM.Scale = Op.getImm();
16726     Op = MI->getOperand(2);
16727     if (Op.isImm())
16728       AM.IndexReg = Op.getImm();
16729     Op = MI->getOperand(3);
16730     if (Op.isGlobal()) {
16731       AM.GV = Op.getGlobal();
16732     } else {
16733       AM.Disp = Op.getImm();
16734     }
16735     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16736                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16737
16738     // Reload the original control word now.
16739     addFrameReference(BuildMI(*BB, MI, DL,
16740                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16741
16742     MI->eraseFromParent();   // The pseudo instruction is gone now.
16743     return BB;
16744   }
16745     // String/text processing lowering.
16746   case X86::PCMPISTRM128REG:
16747   case X86::VPCMPISTRM128REG:
16748   case X86::PCMPISTRM128MEM:
16749   case X86::VPCMPISTRM128MEM:
16750   case X86::PCMPESTRM128REG:
16751   case X86::VPCMPESTRM128REG:
16752   case X86::PCMPESTRM128MEM:
16753   case X86::VPCMPESTRM128MEM:
16754     assert(Subtarget->hasSSE42() &&
16755            "Target must have SSE4.2 or AVX features enabled");
16756     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16757
16758   // String/text processing lowering.
16759   case X86::PCMPISTRIREG:
16760   case X86::VPCMPISTRIREG:
16761   case X86::PCMPISTRIMEM:
16762   case X86::VPCMPISTRIMEM:
16763   case X86::PCMPESTRIREG:
16764   case X86::VPCMPESTRIREG:
16765   case X86::PCMPESTRIMEM:
16766   case X86::VPCMPESTRIMEM:
16767     assert(Subtarget->hasSSE42() &&
16768            "Target must have SSE4.2 or AVX features enabled");
16769     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16770
16771   // Thread synchronization.
16772   case X86::MONITOR:
16773     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16774
16775   // xbegin
16776   case X86::XBEGIN:
16777     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16778
16779   // Atomic Lowering.
16780   case X86::ATOMAND8:
16781   case X86::ATOMAND16:
16782   case X86::ATOMAND32:
16783   case X86::ATOMAND64:
16784     // Fall through
16785   case X86::ATOMOR8:
16786   case X86::ATOMOR16:
16787   case X86::ATOMOR32:
16788   case X86::ATOMOR64:
16789     // Fall through
16790   case X86::ATOMXOR16:
16791   case X86::ATOMXOR8:
16792   case X86::ATOMXOR32:
16793   case X86::ATOMXOR64:
16794     // Fall through
16795   case X86::ATOMNAND8:
16796   case X86::ATOMNAND16:
16797   case X86::ATOMNAND32:
16798   case X86::ATOMNAND64:
16799     // Fall through
16800   case X86::ATOMMAX8:
16801   case X86::ATOMMAX16:
16802   case X86::ATOMMAX32:
16803   case X86::ATOMMAX64:
16804     // Fall through
16805   case X86::ATOMMIN8:
16806   case X86::ATOMMIN16:
16807   case X86::ATOMMIN32:
16808   case X86::ATOMMIN64:
16809     // Fall through
16810   case X86::ATOMUMAX8:
16811   case X86::ATOMUMAX16:
16812   case X86::ATOMUMAX32:
16813   case X86::ATOMUMAX64:
16814     // Fall through
16815   case X86::ATOMUMIN8:
16816   case X86::ATOMUMIN16:
16817   case X86::ATOMUMIN32:
16818   case X86::ATOMUMIN64:
16819     return EmitAtomicLoadArith(MI, BB);
16820
16821   // This group does 64-bit operations on a 32-bit host.
16822   case X86::ATOMAND6432:
16823   case X86::ATOMOR6432:
16824   case X86::ATOMXOR6432:
16825   case X86::ATOMNAND6432:
16826   case X86::ATOMADD6432:
16827   case X86::ATOMSUB6432:
16828   case X86::ATOMMAX6432:
16829   case X86::ATOMMIN6432:
16830   case X86::ATOMUMAX6432:
16831   case X86::ATOMUMIN6432:
16832   case X86::ATOMSWAP6432:
16833     return EmitAtomicLoadArith6432(MI, BB);
16834
16835   case X86::VASTART_SAVE_XMM_REGS:
16836     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16837
16838   case X86::VAARG_64:
16839     return EmitVAARG64WithCustomInserter(MI, BB);
16840
16841   case X86::EH_SjLj_SetJmp32:
16842   case X86::EH_SjLj_SetJmp64:
16843     return emitEHSjLjSetJmp(MI, BB);
16844
16845   case X86::EH_SjLj_LongJmp32:
16846   case X86::EH_SjLj_LongJmp64:
16847     return emitEHSjLjLongJmp(MI, BB);
16848
16849   case TargetOpcode::STACKMAP:
16850   case TargetOpcode::PATCHPOINT:
16851     return emitPatchPoint(MI, BB);
16852
16853   case X86::VFMADDPDr213r:
16854   case X86::VFMADDPSr213r:
16855   case X86::VFMADDSDr213r:
16856   case X86::VFMADDSSr213r:
16857   case X86::VFMSUBPDr213r:
16858   case X86::VFMSUBPSr213r:
16859   case X86::VFMSUBSDr213r:
16860   case X86::VFMSUBSSr213r:
16861   case X86::VFNMADDPDr213r:
16862   case X86::VFNMADDPSr213r:
16863   case X86::VFNMADDSDr213r:
16864   case X86::VFNMADDSSr213r:
16865   case X86::VFNMSUBPDr213r:
16866   case X86::VFNMSUBPSr213r:
16867   case X86::VFNMSUBSDr213r:
16868   case X86::VFNMSUBSSr213r:
16869   case X86::VFMADDPDr213rY:
16870   case X86::VFMADDPSr213rY:
16871   case X86::VFMSUBPDr213rY:
16872   case X86::VFMSUBPSr213rY:
16873   case X86::VFNMADDPDr213rY:
16874   case X86::VFNMADDPSr213rY:
16875   case X86::VFNMSUBPDr213rY:
16876   case X86::VFNMSUBPSr213rY:
16877     return emitFMA3Instr(MI, BB);
16878   }
16879 }
16880
16881 //===----------------------------------------------------------------------===//
16882 //                           X86 Optimization Hooks
16883 //===----------------------------------------------------------------------===//
16884
16885 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16886                                                        APInt &KnownZero,
16887                                                        APInt &KnownOne,
16888                                                        const SelectionDAG &DAG,
16889                                                        unsigned Depth) const {
16890   unsigned BitWidth = KnownZero.getBitWidth();
16891   unsigned Opc = Op.getOpcode();
16892   assert((Opc >= ISD::BUILTIN_OP_END ||
16893           Opc == ISD::INTRINSIC_WO_CHAIN ||
16894           Opc == ISD::INTRINSIC_W_CHAIN ||
16895           Opc == ISD::INTRINSIC_VOID) &&
16896          "Should use MaskedValueIsZero if you don't know whether Op"
16897          " is a target node!");
16898
16899   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16900   switch (Opc) {
16901   default: break;
16902   case X86ISD::ADD:
16903   case X86ISD::SUB:
16904   case X86ISD::ADC:
16905   case X86ISD::SBB:
16906   case X86ISD::SMUL:
16907   case X86ISD::UMUL:
16908   case X86ISD::INC:
16909   case X86ISD::DEC:
16910   case X86ISD::OR:
16911   case X86ISD::XOR:
16912   case X86ISD::AND:
16913     // These nodes' second result is a boolean.
16914     if (Op.getResNo() == 0)
16915       break;
16916     // Fallthrough
16917   case X86ISD::SETCC:
16918     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16919     break;
16920   case ISD::INTRINSIC_WO_CHAIN: {
16921     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16922     unsigned NumLoBits = 0;
16923     switch (IntId) {
16924     default: break;
16925     case Intrinsic::x86_sse_movmsk_ps:
16926     case Intrinsic::x86_avx_movmsk_ps_256:
16927     case Intrinsic::x86_sse2_movmsk_pd:
16928     case Intrinsic::x86_avx_movmsk_pd_256:
16929     case Intrinsic::x86_mmx_pmovmskb:
16930     case Intrinsic::x86_sse2_pmovmskb_128:
16931     case Intrinsic::x86_avx2_pmovmskb: {
16932       // High bits of movmskp{s|d}, pmovmskb are known zero.
16933       switch (IntId) {
16934         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16935         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16936         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16937         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16938         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16939         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16940         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16941         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16942       }
16943       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16944       break;
16945     }
16946     }
16947     break;
16948   }
16949   }
16950 }
16951
16952 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16953   SDValue Op,
16954   const SelectionDAG &,
16955   unsigned Depth) const {
16956   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16957   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16958     return Op.getValueType().getScalarType().getSizeInBits();
16959
16960   // Fallback case.
16961   return 1;
16962 }
16963
16964 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16965 /// node is a GlobalAddress + offset.
16966 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16967                                        const GlobalValue* &GA,
16968                                        int64_t &Offset) const {
16969   if (N->getOpcode() == X86ISD::Wrapper) {
16970     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16971       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16972       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16973       return true;
16974     }
16975   }
16976   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16977 }
16978
16979 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16980 /// same as extracting the high 128-bit part of 256-bit vector and then
16981 /// inserting the result into the low part of a new 256-bit vector
16982 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16983   EVT VT = SVOp->getValueType(0);
16984   unsigned NumElems = VT.getVectorNumElements();
16985
16986   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16987   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16988     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16989         SVOp->getMaskElt(j) >= 0)
16990       return false;
16991
16992   return true;
16993 }
16994
16995 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16996 /// same as extracting the low 128-bit part of 256-bit vector and then
16997 /// inserting the result into the high part of a new 256-bit vector
16998 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16999   EVT VT = SVOp->getValueType(0);
17000   unsigned NumElems = VT.getVectorNumElements();
17001
17002   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17003   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17004     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17005         SVOp->getMaskElt(j) >= 0)
17006       return false;
17007
17008   return true;
17009 }
17010
17011 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17012 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17013                                         TargetLowering::DAGCombinerInfo &DCI,
17014                                         const X86Subtarget* Subtarget) {
17015   SDLoc dl(N);
17016   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17017   SDValue V1 = SVOp->getOperand(0);
17018   SDValue V2 = SVOp->getOperand(1);
17019   EVT VT = SVOp->getValueType(0);
17020   unsigned NumElems = VT.getVectorNumElements();
17021
17022   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17023       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17024     //
17025     //                   0,0,0,...
17026     //                      |
17027     //    V      UNDEF    BUILD_VECTOR    UNDEF
17028     //     \      /           \           /
17029     //  CONCAT_VECTOR         CONCAT_VECTOR
17030     //         \                  /
17031     //          \                /
17032     //          RESULT: V + zero extended
17033     //
17034     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17035         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17036         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17037       return SDValue();
17038
17039     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17040       return SDValue();
17041
17042     // To match the shuffle mask, the first half of the mask should
17043     // be exactly the first vector, and all the rest a splat with the
17044     // first element of the second one.
17045     for (unsigned i = 0; i != NumElems/2; ++i)
17046       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17047           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17048         return SDValue();
17049
17050     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17051     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17052       if (Ld->hasNUsesOfValue(1, 0)) {
17053         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17054         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17055         SDValue ResNode =
17056           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17057                                   Ld->getMemoryVT(),
17058                                   Ld->getPointerInfo(),
17059                                   Ld->getAlignment(),
17060                                   false/*isVolatile*/, true/*ReadMem*/,
17061                                   false/*WriteMem*/);
17062
17063         // Make sure the newly-created LOAD is in the same position as Ld in
17064         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17065         // and update uses of Ld's output chain to use the TokenFactor.
17066         if (Ld->hasAnyUseOfValue(1)) {
17067           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17068                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17069           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17070           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17071                                  SDValue(ResNode.getNode(), 1));
17072         }
17073
17074         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17075       }
17076     }
17077
17078     // Emit a zeroed vector and insert the desired subvector on its
17079     // first half.
17080     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17081     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17082     return DCI.CombineTo(N, InsV);
17083   }
17084
17085   //===--------------------------------------------------------------------===//
17086   // Combine some shuffles into subvector extracts and inserts:
17087   //
17088
17089   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17090   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17091     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17092     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17093     return DCI.CombineTo(N, InsV);
17094   }
17095
17096   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17097   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17098     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17099     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17100     return DCI.CombineTo(N, InsV);
17101   }
17102
17103   return SDValue();
17104 }
17105
17106 /// PerformShuffleCombine - Performs several different shuffle combines.
17107 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17108                                      TargetLowering::DAGCombinerInfo &DCI,
17109                                      const X86Subtarget *Subtarget) {
17110   SDLoc dl(N);
17111   EVT VT = N->getValueType(0);
17112
17113   // Don't create instructions with illegal types after legalize types has run.
17114   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17115   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17116     return SDValue();
17117
17118   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17119   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17120       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17121     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17122
17123   // Only handle 128 wide vector from here on.
17124   if (!VT.is128BitVector())
17125     return SDValue();
17126
17127   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17128   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17129   // consecutive, non-overlapping, and in the right order.
17130   SmallVector<SDValue, 16> Elts;
17131   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17132     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17133
17134   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17135 }
17136
17137 /// PerformTruncateCombine - Converts truncate operation to
17138 /// a sequence of vector shuffle operations.
17139 /// It is possible when we truncate 256-bit vector to 128-bit vector
17140 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17141                                       TargetLowering::DAGCombinerInfo &DCI,
17142                                       const X86Subtarget *Subtarget)  {
17143   return SDValue();
17144 }
17145
17146 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17147 /// specific shuffle of a load can be folded into a single element load.
17148 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17149 /// shuffles have been customed lowered so we need to handle those here.
17150 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17151                                          TargetLowering::DAGCombinerInfo &DCI) {
17152   if (DCI.isBeforeLegalizeOps())
17153     return SDValue();
17154
17155   SDValue InVec = N->getOperand(0);
17156   SDValue EltNo = N->getOperand(1);
17157
17158   if (!isa<ConstantSDNode>(EltNo))
17159     return SDValue();
17160
17161   EVT VT = InVec.getValueType();
17162
17163   bool HasShuffleIntoBitcast = false;
17164   if (InVec.getOpcode() == ISD::BITCAST) {
17165     // Don't duplicate a load with other uses.
17166     if (!InVec.hasOneUse())
17167       return SDValue();
17168     EVT BCVT = InVec.getOperand(0).getValueType();
17169     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17170       return SDValue();
17171     InVec = InVec.getOperand(0);
17172     HasShuffleIntoBitcast = true;
17173   }
17174
17175   if (!isTargetShuffle(InVec.getOpcode()))
17176     return SDValue();
17177
17178   // Don't duplicate a load with other uses.
17179   if (!InVec.hasOneUse())
17180     return SDValue();
17181
17182   SmallVector<int, 16> ShuffleMask;
17183   bool UnaryShuffle;
17184   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17185                             UnaryShuffle))
17186     return SDValue();
17187
17188   // Select the input vector, guarding against out of range extract vector.
17189   unsigned NumElems = VT.getVectorNumElements();
17190   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17191   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17192   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17193                                          : InVec.getOperand(1);
17194
17195   // If inputs to shuffle are the same for both ops, then allow 2 uses
17196   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17197
17198   if (LdNode.getOpcode() == ISD::BITCAST) {
17199     // Don't duplicate a load with other uses.
17200     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17201       return SDValue();
17202
17203     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17204     LdNode = LdNode.getOperand(0);
17205   }
17206
17207   if (!ISD::isNormalLoad(LdNode.getNode()))
17208     return SDValue();
17209
17210   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17211
17212   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17213     return SDValue();
17214
17215   if (HasShuffleIntoBitcast) {
17216     // If there's a bitcast before the shuffle, check if the load type and
17217     // alignment is valid.
17218     unsigned Align = LN0->getAlignment();
17219     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17220     unsigned NewAlign = TLI.getDataLayout()->
17221       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17222
17223     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17224       return SDValue();
17225   }
17226
17227   // All checks match so transform back to vector_shuffle so that DAG combiner
17228   // can finish the job
17229   SDLoc dl(N);
17230
17231   // Create shuffle node taking into account the case that its a unary shuffle
17232   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17233   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17234                                  InVec.getOperand(0), Shuffle,
17235                                  &ShuffleMask[0]);
17236   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17237   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17238                      EltNo);
17239 }
17240
17241 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17242 /// generation and convert it from being a bunch of shuffles and extracts
17243 /// to a simple store and scalar loads to extract the elements.
17244 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17245                                          TargetLowering::DAGCombinerInfo &DCI) {
17246   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17247   if (NewOp.getNode())
17248     return NewOp;
17249
17250   SDValue InputVector = N->getOperand(0);
17251
17252   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17253   // from mmx to v2i32 has a single usage.
17254   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17255       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17256       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17257     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17258                        N->getValueType(0),
17259                        InputVector.getNode()->getOperand(0));
17260
17261   // Only operate on vectors of 4 elements, where the alternative shuffling
17262   // gets to be more expensive.
17263   if (InputVector.getValueType() != MVT::v4i32)
17264     return SDValue();
17265
17266   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17267   // single use which is a sign-extend or zero-extend, and all elements are
17268   // used.
17269   SmallVector<SDNode *, 4> Uses;
17270   unsigned ExtractedElements = 0;
17271   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17272        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17273     if (UI.getUse().getResNo() != InputVector.getResNo())
17274       return SDValue();
17275
17276     SDNode *Extract = *UI;
17277     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17278       return SDValue();
17279
17280     if (Extract->getValueType(0) != MVT::i32)
17281       return SDValue();
17282     if (!Extract->hasOneUse())
17283       return SDValue();
17284     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17285         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17286       return SDValue();
17287     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17288       return SDValue();
17289
17290     // Record which element was extracted.
17291     ExtractedElements |=
17292       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17293
17294     Uses.push_back(Extract);
17295   }
17296
17297   // If not all the elements were used, this may not be worthwhile.
17298   if (ExtractedElements != 15)
17299     return SDValue();
17300
17301   // Ok, we've now decided to do the transformation.
17302   SDLoc dl(InputVector);
17303
17304   // Store the value to a temporary stack slot.
17305   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17306   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17307                             MachinePointerInfo(), false, false, 0);
17308
17309   // Replace each use (extract) with a load of the appropriate element.
17310   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17311        UE = Uses.end(); UI != UE; ++UI) {
17312     SDNode *Extract = *UI;
17313
17314     // cOMpute the element's address.
17315     SDValue Idx = Extract->getOperand(1);
17316     unsigned EltSize =
17317         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17318     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17319     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17320     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17321
17322     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17323                                      StackPtr, OffsetVal);
17324
17325     // Load the scalar.
17326     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17327                                      ScalarAddr, MachinePointerInfo(),
17328                                      false, false, false, 0);
17329
17330     // Replace the exact with the load.
17331     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17332   }
17333
17334   // The replacement was made in place; don't return anything.
17335   return SDValue();
17336 }
17337
17338 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17339 static std::pair<unsigned, bool>
17340 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17341                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17342   if (!VT.isVector())
17343     return std::make_pair(0, false);
17344
17345   bool NeedSplit = false;
17346   switch (VT.getSimpleVT().SimpleTy) {
17347   default: return std::make_pair(0, false);
17348   case MVT::v32i8:
17349   case MVT::v16i16:
17350   case MVT::v8i32:
17351     if (!Subtarget->hasAVX2())
17352       NeedSplit = true;
17353     if (!Subtarget->hasAVX())
17354       return std::make_pair(0, false);
17355     break;
17356   case MVT::v16i8:
17357   case MVT::v8i16:
17358   case MVT::v4i32:
17359     if (!Subtarget->hasSSE2())
17360       return std::make_pair(0, false);
17361   }
17362
17363   // SSE2 has only a small subset of the operations.
17364   bool hasUnsigned = Subtarget->hasSSE41() ||
17365                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17366   bool hasSigned = Subtarget->hasSSE41() ||
17367                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17368
17369   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17370
17371   unsigned Opc = 0;
17372   // Check for x CC y ? x : y.
17373   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17374       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17375     switch (CC) {
17376     default: break;
17377     case ISD::SETULT:
17378     case ISD::SETULE:
17379       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17380     case ISD::SETUGT:
17381     case ISD::SETUGE:
17382       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17383     case ISD::SETLT:
17384     case ISD::SETLE:
17385       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17386     case ISD::SETGT:
17387     case ISD::SETGE:
17388       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17389     }
17390   // Check for x CC y ? y : x -- a min/max with reversed arms.
17391   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17392              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17393     switch (CC) {
17394     default: break;
17395     case ISD::SETULT:
17396     case ISD::SETULE:
17397       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17398     case ISD::SETUGT:
17399     case ISD::SETUGE:
17400       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17401     case ISD::SETLT:
17402     case ISD::SETLE:
17403       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17404     case ISD::SETGT:
17405     case ISD::SETGE:
17406       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17407     }
17408   }
17409
17410   return std::make_pair(Opc, NeedSplit);
17411 }
17412
17413 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17414 /// nodes.
17415 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17416                                     TargetLowering::DAGCombinerInfo &DCI,
17417                                     const X86Subtarget *Subtarget) {
17418   SDLoc DL(N);
17419   SDValue Cond = N->getOperand(0);
17420   // Get the LHS/RHS of the select.
17421   SDValue LHS = N->getOperand(1);
17422   SDValue RHS = N->getOperand(2);
17423   EVT VT = LHS.getValueType();
17424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17425
17426   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17427   // instructions match the semantics of the common C idiom x<y?x:y but not
17428   // x<=y?x:y, because of how they handle negative zero (which can be
17429   // ignored in unsafe-math mode).
17430   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17431       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17432       (Subtarget->hasSSE2() ||
17433        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17434     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17435
17436     unsigned Opcode = 0;
17437     // Check for x CC y ? x : y.
17438     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17439         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17440       switch (CC) {
17441       default: break;
17442       case ISD::SETULT:
17443         // Converting this to a min would handle NaNs incorrectly, and swapping
17444         // the operands would cause it to handle comparisons between positive
17445         // and negative zero incorrectly.
17446         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17447           if (!DAG.getTarget().Options.UnsafeFPMath &&
17448               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17449             break;
17450           std::swap(LHS, RHS);
17451         }
17452         Opcode = X86ISD::FMIN;
17453         break;
17454       case ISD::SETOLE:
17455         // Converting this to a min would handle comparisons between positive
17456         // and negative zero incorrectly.
17457         if (!DAG.getTarget().Options.UnsafeFPMath &&
17458             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17459           break;
17460         Opcode = X86ISD::FMIN;
17461         break;
17462       case ISD::SETULE:
17463         // Converting this to a min would handle both negative zeros and NaNs
17464         // incorrectly, but we can swap the operands to fix both.
17465         std::swap(LHS, RHS);
17466       case ISD::SETOLT:
17467       case ISD::SETLT:
17468       case ISD::SETLE:
17469         Opcode = X86ISD::FMIN;
17470         break;
17471
17472       case ISD::SETOGE:
17473         // Converting this to a max would handle comparisons between positive
17474         // and negative zero incorrectly.
17475         if (!DAG.getTarget().Options.UnsafeFPMath &&
17476             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17477           break;
17478         Opcode = X86ISD::FMAX;
17479         break;
17480       case ISD::SETUGT:
17481         // Converting this to a max would handle NaNs incorrectly, and swapping
17482         // the operands would cause it to handle comparisons between positive
17483         // and negative zero incorrectly.
17484         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17485           if (!DAG.getTarget().Options.UnsafeFPMath &&
17486               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17487             break;
17488           std::swap(LHS, RHS);
17489         }
17490         Opcode = X86ISD::FMAX;
17491         break;
17492       case ISD::SETUGE:
17493         // Converting this to a max would handle both negative zeros and NaNs
17494         // incorrectly, but we can swap the operands to fix both.
17495         std::swap(LHS, RHS);
17496       case ISD::SETOGT:
17497       case ISD::SETGT:
17498       case ISD::SETGE:
17499         Opcode = X86ISD::FMAX;
17500         break;
17501       }
17502     // Check for x CC y ? y : x -- a min/max with reversed arms.
17503     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17504                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17505       switch (CC) {
17506       default: break;
17507       case ISD::SETOGE:
17508         // Converting this to a min would handle comparisons between positive
17509         // and negative zero incorrectly, and swapping the operands would
17510         // cause it to handle NaNs incorrectly.
17511         if (!DAG.getTarget().Options.UnsafeFPMath &&
17512             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17513           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17514             break;
17515           std::swap(LHS, RHS);
17516         }
17517         Opcode = X86ISD::FMIN;
17518         break;
17519       case ISD::SETUGT:
17520         // Converting this to a min would handle NaNs incorrectly.
17521         if (!DAG.getTarget().Options.UnsafeFPMath &&
17522             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17523           break;
17524         Opcode = X86ISD::FMIN;
17525         break;
17526       case ISD::SETUGE:
17527         // Converting this to a min would handle both negative zeros and NaNs
17528         // incorrectly, but we can swap the operands to fix both.
17529         std::swap(LHS, RHS);
17530       case ISD::SETOGT:
17531       case ISD::SETGT:
17532       case ISD::SETGE:
17533         Opcode = X86ISD::FMIN;
17534         break;
17535
17536       case ISD::SETULT:
17537         // Converting this to a max would handle NaNs incorrectly.
17538         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17539           break;
17540         Opcode = X86ISD::FMAX;
17541         break;
17542       case ISD::SETOLE:
17543         // Converting this to a max would handle comparisons between positive
17544         // and negative zero incorrectly, and swapping the operands would
17545         // cause it to handle NaNs incorrectly.
17546         if (!DAG.getTarget().Options.UnsafeFPMath &&
17547             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17548           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17549             break;
17550           std::swap(LHS, RHS);
17551         }
17552         Opcode = X86ISD::FMAX;
17553         break;
17554       case ISD::SETULE:
17555         // Converting this to a max would handle both negative zeros and NaNs
17556         // incorrectly, but we can swap the operands to fix both.
17557         std::swap(LHS, RHS);
17558       case ISD::SETOLT:
17559       case ISD::SETLT:
17560       case ISD::SETLE:
17561         Opcode = X86ISD::FMAX;
17562         break;
17563       }
17564     }
17565
17566     if (Opcode)
17567       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17568   }
17569
17570   EVT CondVT = Cond.getValueType();
17571   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17572       CondVT.getVectorElementType() == MVT::i1) {
17573     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17574     // lowering on AVX-512. In this case we convert it to
17575     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17576     // The same situation for all 128 and 256-bit vectors of i8 and i16
17577     EVT OpVT = LHS.getValueType();
17578     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17579         (OpVT.getVectorElementType() == MVT::i8 ||
17580          OpVT.getVectorElementType() == MVT::i16)) {
17581       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17582       DCI.AddToWorklist(Cond.getNode());
17583       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17584     }
17585   }
17586   // If this is a select between two integer constants, try to do some
17587   // optimizations.
17588   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17589     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17590       // Don't do this for crazy integer types.
17591       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17592         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17593         // so that TrueC (the true value) is larger than FalseC.
17594         bool NeedsCondInvert = false;
17595
17596         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17597             // Efficiently invertible.
17598             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17599              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17600               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17601           NeedsCondInvert = true;
17602           std::swap(TrueC, FalseC);
17603         }
17604
17605         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17606         if (FalseC->getAPIntValue() == 0 &&
17607             TrueC->getAPIntValue().isPowerOf2()) {
17608           if (NeedsCondInvert) // Invert the condition if needed.
17609             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17610                                DAG.getConstant(1, Cond.getValueType()));
17611
17612           // Zero extend the condition if needed.
17613           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17614
17615           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17616           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17617                              DAG.getConstant(ShAmt, MVT::i8));
17618         }
17619
17620         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17621         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17622           if (NeedsCondInvert) // Invert the condition if needed.
17623             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17624                                DAG.getConstant(1, Cond.getValueType()));
17625
17626           // Zero extend the condition if needed.
17627           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17628                              FalseC->getValueType(0), Cond);
17629           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17630                              SDValue(FalseC, 0));
17631         }
17632
17633         // Optimize cases that will turn into an LEA instruction.  This requires
17634         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17635         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17636           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17637           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17638
17639           bool isFastMultiplier = false;
17640           if (Diff < 10) {
17641             switch ((unsigned char)Diff) {
17642               default: break;
17643               case 1:  // result = add base, cond
17644               case 2:  // result = lea base(    , cond*2)
17645               case 3:  // result = lea base(cond, cond*2)
17646               case 4:  // result = lea base(    , cond*4)
17647               case 5:  // result = lea base(cond, cond*4)
17648               case 8:  // result = lea base(    , cond*8)
17649               case 9:  // result = lea base(cond, cond*8)
17650                 isFastMultiplier = true;
17651                 break;
17652             }
17653           }
17654
17655           if (isFastMultiplier) {
17656             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17657             if (NeedsCondInvert) // Invert the condition if needed.
17658               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17659                                  DAG.getConstant(1, Cond.getValueType()));
17660
17661             // Zero extend the condition if needed.
17662             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17663                                Cond);
17664             // Scale the condition by the difference.
17665             if (Diff != 1)
17666               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17667                                  DAG.getConstant(Diff, Cond.getValueType()));
17668
17669             // Add the base if non-zero.
17670             if (FalseC->getAPIntValue() != 0)
17671               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17672                                  SDValue(FalseC, 0));
17673             return Cond;
17674           }
17675         }
17676       }
17677   }
17678
17679   // Canonicalize max and min:
17680   // (x > y) ? x : y -> (x >= y) ? x : y
17681   // (x < y) ? x : y -> (x <= y) ? x : y
17682   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17683   // the need for an extra compare
17684   // against zero. e.g.
17685   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17686   // subl   %esi, %edi
17687   // testl  %edi, %edi
17688   // movl   $0, %eax
17689   // cmovgl %edi, %eax
17690   // =>
17691   // xorl   %eax, %eax
17692   // subl   %esi, $edi
17693   // cmovsl %eax, %edi
17694   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17695       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17696       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17697     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17698     switch (CC) {
17699     default: break;
17700     case ISD::SETLT:
17701     case ISD::SETGT: {
17702       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17703       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17704                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17705       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17706     }
17707     }
17708   }
17709
17710   // Early exit check
17711   if (!TLI.isTypeLegal(VT))
17712     return SDValue();
17713
17714   // Match VSELECTs into subs with unsigned saturation.
17715   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17716       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17717       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17718        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17719     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17720
17721     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17722     // left side invert the predicate to simplify logic below.
17723     SDValue Other;
17724     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17725       Other = RHS;
17726       CC = ISD::getSetCCInverse(CC, true);
17727     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17728       Other = LHS;
17729     }
17730
17731     if (Other.getNode() && Other->getNumOperands() == 2 &&
17732         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17733       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17734       SDValue CondRHS = Cond->getOperand(1);
17735
17736       // Look for a general sub with unsigned saturation first.
17737       // x >= y ? x-y : 0 --> subus x, y
17738       // x >  y ? x-y : 0 --> subus x, y
17739       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17740           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17741         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17742
17743       // If the RHS is a constant we have to reverse the const canonicalization.
17744       // x > C-1 ? x+-C : 0 --> subus x, C
17745       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17746           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17747         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17748         if (CondRHS.getConstantOperandVal(0) == -A-1)
17749           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17750                              DAG.getConstant(-A, VT));
17751       }
17752
17753       // Another special case: If C was a sign bit, the sub has been
17754       // canonicalized into a xor.
17755       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17756       //        it's safe to decanonicalize the xor?
17757       // x s< 0 ? x^C : 0 --> subus x, C
17758       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17759           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17760           isSplatVector(OpRHS.getNode())) {
17761         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17762         if (A.isSignBit())
17763           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17764       }
17765     }
17766   }
17767
17768   // Try to match a min/max vector operation.
17769   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17770     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17771     unsigned Opc = ret.first;
17772     bool NeedSplit = ret.second;
17773
17774     if (Opc && NeedSplit) {
17775       unsigned NumElems = VT.getVectorNumElements();
17776       // Extract the LHS vectors
17777       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17778       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17779
17780       // Extract the RHS vectors
17781       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17782       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17783
17784       // Create min/max for each subvector
17785       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17786       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17787
17788       // Merge the result
17789       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17790     } else if (Opc)
17791       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17792   }
17793
17794   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17795   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17796       // Check if SETCC has already been promoted
17797       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17798       // Check that condition value type matches vselect operand type
17799       CondVT == VT) { 
17800
17801     assert(Cond.getValueType().isVector() &&
17802            "vector select expects a vector selector!");
17803
17804     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17805     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17806
17807     if (!TValIsAllOnes && !FValIsAllZeros) {
17808       // Try invert the condition if true value is not all 1s and false value
17809       // is not all 0s.
17810       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17811       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17812
17813       if (TValIsAllZeros || FValIsAllOnes) {
17814         SDValue CC = Cond.getOperand(2);
17815         ISD::CondCode NewCC =
17816           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17817                                Cond.getOperand(0).getValueType().isInteger());
17818         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17819         std::swap(LHS, RHS);
17820         TValIsAllOnes = FValIsAllOnes;
17821         FValIsAllZeros = TValIsAllZeros;
17822       }
17823     }
17824
17825     if (TValIsAllOnes || FValIsAllZeros) {
17826       SDValue Ret;
17827
17828       if (TValIsAllOnes && FValIsAllZeros)
17829         Ret = Cond;
17830       else if (TValIsAllOnes)
17831         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17832                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17833       else if (FValIsAllZeros)
17834         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17835                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17836
17837       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17838     }
17839   }
17840
17841   // Try to fold this VSELECT into a MOVSS/MOVSD
17842   if (N->getOpcode() == ISD::VSELECT &&
17843       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17844     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17845         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17846       bool CanFold = false;
17847       unsigned NumElems = Cond.getNumOperands();
17848       SDValue A = LHS;
17849       SDValue B = RHS;
17850       
17851       if (isZero(Cond.getOperand(0))) {
17852         CanFold = true;
17853
17854         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17855         // fold (vselect <0,-1> -> (movsd A, B)
17856         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17857           CanFold = isAllOnes(Cond.getOperand(i));
17858       } else if (isAllOnes(Cond.getOperand(0))) {
17859         CanFold = true;
17860         std::swap(A, B);
17861
17862         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17863         // fold (vselect <-1,0> -> (movsd B, A)
17864         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17865           CanFold = isZero(Cond.getOperand(i));
17866       }
17867
17868       if (CanFold) {
17869         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17870           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17871         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17872       }
17873
17874       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17875         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17876         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17877         //                             (v2i64 (bitcast B)))))
17878         //
17879         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17880         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17881         //                             (v2f64 (bitcast B)))))
17882         //
17883         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17884         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17885         //                             (v2i64 (bitcast A)))))
17886         //
17887         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17888         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17889         //                             (v2f64 (bitcast A)))))
17890
17891         CanFold = (isZero(Cond.getOperand(0)) &&
17892                    isZero(Cond.getOperand(1)) &&
17893                    isAllOnes(Cond.getOperand(2)) &&
17894                    isAllOnes(Cond.getOperand(3)));
17895
17896         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17897             isAllOnes(Cond.getOperand(1)) &&
17898             isZero(Cond.getOperand(2)) &&
17899             isZero(Cond.getOperand(3))) {
17900           CanFold = true;
17901           std::swap(LHS, RHS);
17902         }
17903
17904         if (CanFold) {
17905           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17906           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17907           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17908           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17909                                                 NewB, DAG);
17910           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17911         }
17912       }
17913     }
17914   }
17915
17916   // If we know that this node is legal then we know that it is going to be
17917   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17918   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17919   // to simplify previous instructions.
17920   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17921       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17922     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17923
17924     // Don't optimize vector selects that map to mask-registers.
17925     if (BitWidth == 1)
17926       return SDValue();
17927
17928     // Check all uses of that condition operand to check whether it will be
17929     // consumed by non-BLEND instructions, which may depend on all bits are set
17930     // properly.
17931     for (SDNode::use_iterator I = Cond->use_begin(),
17932                               E = Cond->use_end(); I != E; ++I)
17933       if (I->getOpcode() != ISD::VSELECT)
17934         // TODO: Add other opcodes eventually lowered into BLEND.
17935         return SDValue();
17936
17937     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17938     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17939
17940     APInt KnownZero, KnownOne;
17941     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17942                                           DCI.isBeforeLegalizeOps());
17943     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17944         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17945       DCI.CommitTargetLoweringOpt(TLO);
17946   }
17947
17948   return SDValue();
17949 }
17950
17951 // Check whether a boolean test is testing a boolean value generated by
17952 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17953 // code.
17954 //
17955 // Simplify the following patterns:
17956 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17957 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17958 // to (Op EFLAGS Cond)
17959 //
17960 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17961 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17962 // to (Op EFLAGS !Cond)
17963 //
17964 // where Op could be BRCOND or CMOV.
17965 //
17966 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17967   // Quit if not CMP and SUB with its value result used.
17968   if (Cmp.getOpcode() != X86ISD::CMP &&
17969       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17970       return SDValue();
17971
17972   // Quit if not used as a boolean value.
17973   if (CC != X86::COND_E && CC != X86::COND_NE)
17974     return SDValue();
17975
17976   // Check CMP operands. One of them should be 0 or 1 and the other should be
17977   // an SetCC or extended from it.
17978   SDValue Op1 = Cmp.getOperand(0);
17979   SDValue Op2 = Cmp.getOperand(1);
17980
17981   SDValue SetCC;
17982   const ConstantSDNode* C = nullptr;
17983   bool needOppositeCond = (CC == X86::COND_E);
17984   bool checkAgainstTrue = false; // Is it a comparison against 1?
17985
17986   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17987     SetCC = Op2;
17988   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17989     SetCC = Op1;
17990   else // Quit if all operands are not constants.
17991     return SDValue();
17992
17993   if (C->getZExtValue() == 1) {
17994     needOppositeCond = !needOppositeCond;
17995     checkAgainstTrue = true;
17996   } else if (C->getZExtValue() != 0)
17997     // Quit if the constant is neither 0 or 1.
17998     return SDValue();
17999
18000   bool truncatedToBoolWithAnd = false;
18001   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18002   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18003          SetCC.getOpcode() == ISD::TRUNCATE ||
18004          SetCC.getOpcode() == ISD::AND) {
18005     if (SetCC.getOpcode() == ISD::AND) {
18006       int OpIdx = -1;
18007       ConstantSDNode *CS;
18008       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18009           CS->getZExtValue() == 1)
18010         OpIdx = 1;
18011       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18012           CS->getZExtValue() == 1)
18013         OpIdx = 0;
18014       if (OpIdx == -1)
18015         break;
18016       SetCC = SetCC.getOperand(OpIdx);
18017       truncatedToBoolWithAnd = true;
18018     } else
18019       SetCC = SetCC.getOperand(0);
18020   }
18021
18022   switch (SetCC.getOpcode()) {
18023   case X86ISD::SETCC_CARRY:
18024     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18025     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18026     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18027     // truncated to i1 using 'and'.
18028     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18029       break;
18030     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18031            "Invalid use of SETCC_CARRY!");
18032     // FALL THROUGH
18033   case X86ISD::SETCC:
18034     // Set the condition code or opposite one if necessary.
18035     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18036     if (needOppositeCond)
18037       CC = X86::GetOppositeBranchCondition(CC);
18038     return SetCC.getOperand(1);
18039   case X86ISD::CMOV: {
18040     // Check whether false/true value has canonical one, i.e. 0 or 1.
18041     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18042     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18043     // Quit if true value is not a constant.
18044     if (!TVal)
18045       return SDValue();
18046     // Quit if false value is not a constant.
18047     if (!FVal) {
18048       SDValue Op = SetCC.getOperand(0);
18049       // Skip 'zext' or 'trunc' node.
18050       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18051           Op.getOpcode() == ISD::TRUNCATE)
18052         Op = Op.getOperand(0);
18053       // A special case for rdrand/rdseed, where 0 is set if false cond is
18054       // found.
18055       if ((Op.getOpcode() != X86ISD::RDRAND &&
18056            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18057         return SDValue();
18058     }
18059     // Quit if false value is not the constant 0 or 1.
18060     bool FValIsFalse = true;
18061     if (FVal && FVal->getZExtValue() != 0) {
18062       if (FVal->getZExtValue() != 1)
18063         return SDValue();
18064       // If FVal is 1, opposite cond is needed.
18065       needOppositeCond = !needOppositeCond;
18066       FValIsFalse = false;
18067     }
18068     // Quit if TVal is not the constant opposite of FVal.
18069     if (FValIsFalse && TVal->getZExtValue() != 1)
18070       return SDValue();
18071     if (!FValIsFalse && TVal->getZExtValue() != 0)
18072       return SDValue();
18073     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18074     if (needOppositeCond)
18075       CC = X86::GetOppositeBranchCondition(CC);
18076     return SetCC.getOperand(3);
18077   }
18078   }
18079
18080   return SDValue();
18081 }
18082
18083 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18084 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18085                                   TargetLowering::DAGCombinerInfo &DCI,
18086                                   const X86Subtarget *Subtarget) {
18087   SDLoc DL(N);
18088
18089   // If the flag operand isn't dead, don't touch this CMOV.
18090   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18091     return SDValue();
18092
18093   SDValue FalseOp = N->getOperand(0);
18094   SDValue TrueOp = N->getOperand(1);
18095   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18096   SDValue Cond = N->getOperand(3);
18097
18098   if (CC == X86::COND_E || CC == X86::COND_NE) {
18099     switch (Cond.getOpcode()) {
18100     default: break;
18101     case X86ISD::BSR:
18102     case X86ISD::BSF:
18103       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18104       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18105         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18106     }
18107   }
18108
18109   SDValue Flags;
18110
18111   Flags = checkBoolTestSetCCCombine(Cond, CC);
18112   if (Flags.getNode() &&
18113       // Extra check as FCMOV only supports a subset of X86 cond.
18114       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18115     SDValue Ops[] = { FalseOp, TrueOp,
18116                       DAG.getConstant(CC, MVT::i8), Flags };
18117     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18118   }
18119
18120   // If this is a select between two integer constants, try to do some
18121   // optimizations.  Note that the operands are ordered the opposite of SELECT
18122   // operands.
18123   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18124     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18125       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18126       // larger than FalseC (the false value).
18127       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18128         CC = X86::GetOppositeBranchCondition(CC);
18129         std::swap(TrueC, FalseC);
18130         std::swap(TrueOp, FalseOp);
18131       }
18132
18133       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18134       // This is efficient for any integer data type (including i8/i16) and
18135       // shift amount.
18136       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18137         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18138                            DAG.getConstant(CC, MVT::i8), Cond);
18139
18140         // Zero extend the condition if needed.
18141         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18142
18143         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18144         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18145                            DAG.getConstant(ShAmt, MVT::i8));
18146         if (N->getNumValues() == 2)  // Dead flag value?
18147           return DCI.CombineTo(N, Cond, SDValue());
18148         return Cond;
18149       }
18150
18151       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18152       // for any integer data type, including i8/i16.
18153       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18154         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18155                            DAG.getConstant(CC, MVT::i8), Cond);
18156
18157         // Zero extend the condition if needed.
18158         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18159                            FalseC->getValueType(0), Cond);
18160         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18161                            SDValue(FalseC, 0));
18162
18163         if (N->getNumValues() == 2)  // Dead flag value?
18164           return DCI.CombineTo(N, Cond, SDValue());
18165         return Cond;
18166       }
18167
18168       // Optimize cases that will turn into an LEA instruction.  This requires
18169       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18170       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18171         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18172         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18173
18174         bool isFastMultiplier = false;
18175         if (Diff < 10) {
18176           switch ((unsigned char)Diff) {
18177           default: break;
18178           case 1:  // result = add base, cond
18179           case 2:  // result = lea base(    , cond*2)
18180           case 3:  // result = lea base(cond, cond*2)
18181           case 4:  // result = lea base(    , cond*4)
18182           case 5:  // result = lea base(cond, cond*4)
18183           case 8:  // result = lea base(    , cond*8)
18184           case 9:  // result = lea base(cond, cond*8)
18185             isFastMultiplier = true;
18186             break;
18187           }
18188         }
18189
18190         if (isFastMultiplier) {
18191           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18192           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18193                              DAG.getConstant(CC, MVT::i8), Cond);
18194           // Zero extend the condition if needed.
18195           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18196                              Cond);
18197           // Scale the condition by the difference.
18198           if (Diff != 1)
18199             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18200                                DAG.getConstant(Diff, Cond.getValueType()));
18201
18202           // Add the base if non-zero.
18203           if (FalseC->getAPIntValue() != 0)
18204             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18205                                SDValue(FalseC, 0));
18206           if (N->getNumValues() == 2)  // Dead flag value?
18207             return DCI.CombineTo(N, Cond, SDValue());
18208           return Cond;
18209         }
18210       }
18211     }
18212   }
18213
18214   // Handle these cases:
18215   //   (select (x != c), e, c) -> select (x != c), e, x),
18216   //   (select (x == c), c, e) -> select (x == c), x, e)
18217   // where the c is an integer constant, and the "select" is the combination
18218   // of CMOV and CMP.
18219   //
18220   // The rationale for this change is that the conditional-move from a constant
18221   // needs two instructions, however, conditional-move from a register needs
18222   // only one instruction.
18223   //
18224   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18225   //  some instruction-combining opportunities. This opt needs to be
18226   //  postponed as late as possible.
18227   //
18228   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18229     // the DCI.xxxx conditions are provided to postpone the optimization as
18230     // late as possible.
18231
18232     ConstantSDNode *CmpAgainst = nullptr;
18233     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18234         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18235         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18236
18237       if (CC == X86::COND_NE &&
18238           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18239         CC = X86::GetOppositeBranchCondition(CC);
18240         std::swap(TrueOp, FalseOp);
18241       }
18242
18243       if (CC == X86::COND_E &&
18244           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18245         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18246                           DAG.getConstant(CC, MVT::i8), Cond };
18247         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18248       }
18249     }
18250   }
18251
18252   return SDValue();
18253 }
18254
18255 /// PerformMulCombine - Optimize a single multiply with constant into two
18256 /// in order to implement it with two cheaper instructions, e.g.
18257 /// LEA + SHL, LEA + LEA.
18258 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18259                                  TargetLowering::DAGCombinerInfo &DCI) {
18260   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18261     return SDValue();
18262
18263   EVT VT = N->getValueType(0);
18264   if (VT != MVT::i64)
18265     return SDValue();
18266
18267   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18268   if (!C)
18269     return SDValue();
18270   uint64_t MulAmt = C->getZExtValue();
18271   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18272     return SDValue();
18273
18274   uint64_t MulAmt1 = 0;
18275   uint64_t MulAmt2 = 0;
18276   if ((MulAmt % 9) == 0) {
18277     MulAmt1 = 9;
18278     MulAmt2 = MulAmt / 9;
18279   } else if ((MulAmt % 5) == 0) {
18280     MulAmt1 = 5;
18281     MulAmt2 = MulAmt / 5;
18282   } else if ((MulAmt % 3) == 0) {
18283     MulAmt1 = 3;
18284     MulAmt2 = MulAmt / 3;
18285   }
18286   if (MulAmt2 &&
18287       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18288     SDLoc DL(N);
18289
18290     if (isPowerOf2_64(MulAmt2) &&
18291         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18292       // If second multiplifer is pow2, issue it first. We want the multiply by
18293       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18294       // is an add.
18295       std::swap(MulAmt1, MulAmt2);
18296
18297     SDValue NewMul;
18298     if (isPowerOf2_64(MulAmt1))
18299       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18300                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18301     else
18302       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18303                            DAG.getConstant(MulAmt1, VT));
18304
18305     if (isPowerOf2_64(MulAmt2))
18306       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18307                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18308     else
18309       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18310                            DAG.getConstant(MulAmt2, VT));
18311
18312     // Do not add new nodes to DAG combiner worklist.
18313     DCI.CombineTo(N, NewMul, false);
18314   }
18315   return SDValue();
18316 }
18317
18318 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18319   SDValue N0 = N->getOperand(0);
18320   SDValue N1 = N->getOperand(1);
18321   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18322   EVT VT = N0.getValueType();
18323
18324   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18325   // since the result of setcc_c is all zero's or all ones.
18326   if (VT.isInteger() && !VT.isVector() &&
18327       N1C && N0.getOpcode() == ISD::AND &&
18328       N0.getOperand(1).getOpcode() == ISD::Constant) {
18329     SDValue N00 = N0.getOperand(0);
18330     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18331         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18332           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18333          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18334       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18335       APInt ShAmt = N1C->getAPIntValue();
18336       Mask = Mask.shl(ShAmt);
18337       if (Mask != 0)
18338         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18339                            N00, DAG.getConstant(Mask, VT));
18340     }
18341   }
18342
18343   // Hardware support for vector shifts is sparse which makes us scalarize the
18344   // vector operations in many cases. Also, on sandybridge ADD is faster than
18345   // shl.
18346   // (shl V, 1) -> add V,V
18347   if (isSplatVector(N1.getNode())) {
18348     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18349     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18350     // We shift all of the values by one. In many cases we do not have
18351     // hardware support for this operation. This is better expressed as an ADD
18352     // of two values.
18353     if (N1C && (1 == N1C->getZExtValue())) {
18354       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18355     }
18356   }
18357
18358   return SDValue();
18359 }
18360
18361 /// \brief Returns a vector of 0s if the node in input is a vector logical
18362 /// shift by a constant amount which is known to be bigger than or equal
18363 /// to the vector element size in bits.
18364 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18365                                       const X86Subtarget *Subtarget) {
18366   EVT VT = N->getValueType(0);
18367
18368   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18369       (!Subtarget->hasInt256() ||
18370        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18371     return SDValue();
18372
18373   SDValue Amt = N->getOperand(1);
18374   SDLoc DL(N);
18375   if (isSplatVector(Amt.getNode())) {
18376     SDValue SclrAmt = Amt->getOperand(0);
18377     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18378       APInt ShiftAmt = C->getAPIntValue();
18379       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18380
18381       // SSE2/AVX2 logical shifts always return a vector of 0s
18382       // if the shift amount is bigger than or equal to
18383       // the element size. The constant shift amount will be
18384       // encoded as a 8-bit immediate.
18385       if (ShiftAmt.trunc(8).uge(MaxAmount))
18386         return getZeroVector(VT, Subtarget, DAG, DL);
18387     }
18388   }
18389
18390   return SDValue();
18391 }
18392
18393 /// PerformShiftCombine - Combine shifts.
18394 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18395                                    TargetLowering::DAGCombinerInfo &DCI,
18396                                    const X86Subtarget *Subtarget) {
18397   if (N->getOpcode() == ISD::SHL) {
18398     SDValue V = PerformSHLCombine(N, DAG);
18399     if (V.getNode()) return V;
18400   }
18401
18402   if (N->getOpcode() != ISD::SRA) {
18403     // Try to fold this logical shift into a zero vector.
18404     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18405     if (V.getNode()) return V;
18406   }
18407
18408   return SDValue();
18409 }
18410
18411 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18412 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18413 // and friends.  Likewise for OR -> CMPNEQSS.
18414 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18415                             TargetLowering::DAGCombinerInfo &DCI,
18416                             const X86Subtarget *Subtarget) {
18417   unsigned opcode;
18418
18419   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18420   // we're requiring SSE2 for both.
18421   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18422     SDValue N0 = N->getOperand(0);
18423     SDValue N1 = N->getOperand(1);
18424     SDValue CMP0 = N0->getOperand(1);
18425     SDValue CMP1 = N1->getOperand(1);
18426     SDLoc DL(N);
18427
18428     // The SETCCs should both refer to the same CMP.
18429     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18430       return SDValue();
18431
18432     SDValue CMP00 = CMP0->getOperand(0);
18433     SDValue CMP01 = CMP0->getOperand(1);
18434     EVT     VT    = CMP00.getValueType();
18435
18436     if (VT == MVT::f32 || VT == MVT::f64) {
18437       bool ExpectingFlags = false;
18438       // Check for any users that want flags:
18439       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18440            !ExpectingFlags && UI != UE; ++UI)
18441         switch (UI->getOpcode()) {
18442         default:
18443         case ISD::BR_CC:
18444         case ISD::BRCOND:
18445         case ISD::SELECT:
18446           ExpectingFlags = true;
18447           break;
18448         case ISD::CopyToReg:
18449         case ISD::SIGN_EXTEND:
18450         case ISD::ZERO_EXTEND:
18451         case ISD::ANY_EXTEND:
18452           break;
18453         }
18454
18455       if (!ExpectingFlags) {
18456         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18457         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18458
18459         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18460           X86::CondCode tmp = cc0;
18461           cc0 = cc1;
18462           cc1 = tmp;
18463         }
18464
18465         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18466             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18467           // FIXME: need symbolic constants for these magic numbers.
18468           // See X86ATTInstPrinter.cpp:printSSECC().
18469           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18470           if (Subtarget->hasAVX512()) {
18471             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18472                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18473             if (N->getValueType(0) != MVT::i1)
18474               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18475                                  FSetCC);
18476             return FSetCC;
18477           }
18478           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18479                                               CMP00.getValueType(), CMP00, CMP01,
18480                                               DAG.getConstant(x86cc, MVT::i8));
18481
18482           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18483           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18484
18485           if (is64BitFP && !Subtarget->is64Bit()) {
18486             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18487             // 64-bit integer, since that's not a legal type. Since
18488             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18489             // bits, but can do this little dance to extract the lowest 32 bits
18490             // and work with those going forward.
18491             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18492                                            OnesOrZeroesF);
18493             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18494                                            Vector64);
18495             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18496                                         Vector32, DAG.getIntPtrConstant(0));
18497             IntVT = MVT::i32;
18498           }
18499
18500           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18501           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18502                                       DAG.getConstant(1, IntVT));
18503           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18504           return OneBitOfTruth;
18505         }
18506       }
18507     }
18508   }
18509   return SDValue();
18510 }
18511
18512 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18513 /// so it can be folded inside ANDNP.
18514 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18515   EVT VT = N->getValueType(0);
18516
18517   // Match direct AllOnes for 128 and 256-bit vectors
18518   if (ISD::isBuildVectorAllOnes(N))
18519     return true;
18520
18521   // Look through a bit convert.
18522   if (N->getOpcode() == ISD::BITCAST)
18523     N = N->getOperand(0).getNode();
18524
18525   // Sometimes the operand may come from a insert_subvector building a 256-bit
18526   // allones vector
18527   if (VT.is256BitVector() &&
18528       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18529     SDValue V1 = N->getOperand(0);
18530     SDValue V2 = N->getOperand(1);
18531
18532     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18533         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18534         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18535         ISD::isBuildVectorAllOnes(V2.getNode()))
18536       return true;
18537   }
18538
18539   return false;
18540 }
18541
18542 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18543 // register. In most cases we actually compare or select YMM-sized registers
18544 // and mixing the two types creates horrible code. This method optimizes
18545 // some of the transition sequences.
18546 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18547                                  TargetLowering::DAGCombinerInfo &DCI,
18548                                  const X86Subtarget *Subtarget) {
18549   EVT VT = N->getValueType(0);
18550   if (!VT.is256BitVector())
18551     return SDValue();
18552
18553   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18554           N->getOpcode() == ISD::ZERO_EXTEND ||
18555           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18556
18557   SDValue Narrow = N->getOperand(0);
18558   EVT NarrowVT = Narrow->getValueType(0);
18559   if (!NarrowVT.is128BitVector())
18560     return SDValue();
18561
18562   if (Narrow->getOpcode() != ISD::XOR &&
18563       Narrow->getOpcode() != ISD::AND &&
18564       Narrow->getOpcode() != ISD::OR)
18565     return SDValue();
18566
18567   SDValue N0  = Narrow->getOperand(0);
18568   SDValue N1  = Narrow->getOperand(1);
18569   SDLoc DL(Narrow);
18570
18571   // The Left side has to be a trunc.
18572   if (N0.getOpcode() != ISD::TRUNCATE)
18573     return SDValue();
18574
18575   // The type of the truncated inputs.
18576   EVT WideVT = N0->getOperand(0)->getValueType(0);
18577   if (WideVT != VT)
18578     return SDValue();
18579
18580   // The right side has to be a 'trunc' or a constant vector.
18581   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18582   bool RHSConst = (isSplatVector(N1.getNode()) &&
18583                    isa<ConstantSDNode>(N1->getOperand(0)));
18584   if (!RHSTrunc && !RHSConst)
18585     return SDValue();
18586
18587   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18588
18589   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18590     return SDValue();
18591
18592   // Set N0 and N1 to hold the inputs to the new wide operation.
18593   N0 = N0->getOperand(0);
18594   if (RHSConst) {
18595     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18596                      N1->getOperand(0));
18597     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18598     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18599   } else if (RHSTrunc) {
18600     N1 = N1->getOperand(0);
18601   }
18602
18603   // Generate the wide operation.
18604   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18605   unsigned Opcode = N->getOpcode();
18606   switch (Opcode) {
18607   case ISD::ANY_EXTEND:
18608     return Op;
18609   case ISD::ZERO_EXTEND: {
18610     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18611     APInt Mask = APInt::getAllOnesValue(InBits);
18612     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18613     return DAG.getNode(ISD::AND, DL, VT,
18614                        Op, DAG.getConstant(Mask, VT));
18615   }
18616   case ISD::SIGN_EXTEND:
18617     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18618                        Op, DAG.getValueType(NarrowVT));
18619   default:
18620     llvm_unreachable("Unexpected opcode");
18621   }
18622 }
18623
18624 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18625                                  TargetLowering::DAGCombinerInfo &DCI,
18626                                  const X86Subtarget *Subtarget) {
18627   EVT VT = N->getValueType(0);
18628   if (DCI.isBeforeLegalizeOps())
18629     return SDValue();
18630
18631   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18632   if (R.getNode())
18633     return R;
18634
18635   // Create BEXTR instructions
18636   // BEXTR is ((X >> imm) & (2**size-1))
18637   if (VT == MVT::i32 || VT == MVT::i64) {
18638     SDValue N0 = N->getOperand(0);
18639     SDValue N1 = N->getOperand(1);
18640     SDLoc DL(N);
18641
18642     // Check for BEXTR.
18643     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18644         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18645       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18646       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18647       if (MaskNode && ShiftNode) {
18648         uint64_t Mask = MaskNode->getZExtValue();
18649         uint64_t Shift = ShiftNode->getZExtValue();
18650         if (isMask_64(Mask)) {
18651           uint64_t MaskSize = CountPopulation_64(Mask);
18652           if (Shift + MaskSize <= VT.getSizeInBits())
18653             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18654                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18655         }
18656       }
18657     } // BEXTR
18658
18659     return SDValue();
18660   }
18661
18662   // Want to form ANDNP nodes:
18663   // 1) In the hopes of then easily combining them with OR and AND nodes
18664   //    to form PBLEND/PSIGN.
18665   // 2) To match ANDN packed intrinsics
18666   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18667     return SDValue();
18668
18669   SDValue N0 = N->getOperand(0);
18670   SDValue N1 = N->getOperand(1);
18671   SDLoc DL(N);
18672
18673   // Check LHS for vnot
18674   if (N0.getOpcode() == ISD::XOR &&
18675       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18676       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18677     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18678
18679   // Check RHS for vnot
18680   if (N1.getOpcode() == ISD::XOR &&
18681       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18682       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18683     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18684
18685   return SDValue();
18686 }
18687
18688 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18689                                 TargetLowering::DAGCombinerInfo &DCI,
18690                                 const X86Subtarget *Subtarget) {
18691   if (DCI.isBeforeLegalizeOps())
18692     return SDValue();
18693
18694   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18695   if (R.getNode())
18696     return R;
18697
18698   SDValue N0 = N->getOperand(0);
18699   SDValue N1 = N->getOperand(1);
18700   EVT VT = N->getValueType(0);
18701
18702   // look for psign/blend
18703   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18704     if (!Subtarget->hasSSSE3() ||
18705         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18706       return SDValue();
18707
18708     // Canonicalize pandn to RHS
18709     if (N0.getOpcode() == X86ISD::ANDNP)
18710       std::swap(N0, N1);
18711     // or (and (m, y), (pandn m, x))
18712     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18713       SDValue Mask = N1.getOperand(0);
18714       SDValue X    = N1.getOperand(1);
18715       SDValue Y;
18716       if (N0.getOperand(0) == Mask)
18717         Y = N0.getOperand(1);
18718       if (N0.getOperand(1) == Mask)
18719         Y = N0.getOperand(0);
18720
18721       // Check to see if the mask appeared in both the AND and ANDNP and
18722       if (!Y.getNode())
18723         return SDValue();
18724
18725       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18726       // Look through mask bitcast.
18727       if (Mask.getOpcode() == ISD::BITCAST)
18728         Mask = Mask.getOperand(0);
18729       if (X.getOpcode() == ISD::BITCAST)
18730         X = X.getOperand(0);
18731       if (Y.getOpcode() == ISD::BITCAST)
18732         Y = Y.getOperand(0);
18733
18734       EVT MaskVT = Mask.getValueType();
18735
18736       // Validate that the Mask operand is a vector sra node.
18737       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18738       // there is no psrai.b
18739       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18740       unsigned SraAmt = ~0;
18741       if (Mask.getOpcode() == ISD::SRA) {
18742         SDValue Amt = Mask.getOperand(1);
18743         if (isSplatVector(Amt.getNode())) {
18744           SDValue SclrAmt = Amt->getOperand(0);
18745           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18746             SraAmt = C->getZExtValue();
18747         }
18748       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18749         SDValue SraC = Mask.getOperand(1);
18750         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18751       }
18752       if ((SraAmt + 1) != EltBits)
18753         return SDValue();
18754
18755       SDLoc DL(N);
18756
18757       // Now we know we at least have a plendvb with the mask val.  See if
18758       // we can form a psignb/w/d.
18759       // psign = x.type == y.type == mask.type && y = sub(0, x);
18760       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18761           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18762           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18763         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18764                "Unsupported VT for PSIGN");
18765         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18766         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18767       }
18768       // PBLENDVB only available on SSE 4.1
18769       if (!Subtarget->hasSSE41())
18770         return SDValue();
18771
18772       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18773
18774       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18775       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18776       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18777       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18778       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18779     }
18780   }
18781
18782   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18783     return SDValue();
18784
18785   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18786   MachineFunction &MF = DAG.getMachineFunction();
18787   bool OptForSize = MF.getFunction()->getAttributes().
18788     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18789
18790   // SHLD/SHRD instructions have lower register pressure, but on some
18791   // platforms they have higher latency than the equivalent
18792   // series of shifts/or that would otherwise be generated.
18793   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18794   // have higher latencies and we are not optimizing for size.
18795   if (!OptForSize && Subtarget->isSHLDSlow())
18796     return SDValue();
18797
18798   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18799     std::swap(N0, N1);
18800   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18801     return SDValue();
18802   if (!N0.hasOneUse() || !N1.hasOneUse())
18803     return SDValue();
18804
18805   SDValue ShAmt0 = N0.getOperand(1);
18806   if (ShAmt0.getValueType() != MVT::i8)
18807     return SDValue();
18808   SDValue ShAmt1 = N1.getOperand(1);
18809   if (ShAmt1.getValueType() != MVT::i8)
18810     return SDValue();
18811   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18812     ShAmt0 = ShAmt0.getOperand(0);
18813   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18814     ShAmt1 = ShAmt1.getOperand(0);
18815
18816   SDLoc DL(N);
18817   unsigned Opc = X86ISD::SHLD;
18818   SDValue Op0 = N0.getOperand(0);
18819   SDValue Op1 = N1.getOperand(0);
18820   if (ShAmt0.getOpcode() == ISD::SUB) {
18821     Opc = X86ISD::SHRD;
18822     std::swap(Op0, Op1);
18823     std::swap(ShAmt0, ShAmt1);
18824   }
18825
18826   unsigned Bits = VT.getSizeInBits();
18827   if (ShAmt1.getOpcode() == ISD::SUB) {
18828     SDValue Sum = ShAmt1.getOperand(0);
18829     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18830       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18831       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18832         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18833       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18834         return DAG.getNode(Opc, DL, VT,
18835                            Op0, Op1,
18836                            DAG.getNode(ISD::TRUNCATE, DL,
18837                                        MVT::i8, ShAmt0));
18838     }
18839   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18840     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18841     if (ShAmt0C &&
18842         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18843       return DAG.getNode(Opc, DL, VT,
18844                          N0.getOperand(0), N1.getOperand(0),
18845                          DAG.getNode(ISD::TRUNCATE, DL,
18846                                        MVT::i8, ShAmt0));
18847   }
18848
18849   return SDValue();
18850 }
18851
18852 // Generate NEG and CMOV for integer abs.
18853 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18854   EVT VT = N->getValueType(0);
18855
18856   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18857   // 8-bit integer abs to NEG and CMOV.
18858   if (VT.isInteger() && VT.getSizeInBits() == 8)
18859     return SDValue();
18860
18861   SDValue N0 = N->getOperand(0);
18862   SDValue N1 = N->getOperand(1);
18863   SDLoc DL(N);
18864
18865   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18866   // and change it to SUB and CMOV.
18867   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18868       N0.getOpcode() == ISD::ADD &&
18869       N0.getOperand(1) == N1 &&
18870       N1.getOpcode() == ISD::SRA &&
18871       N1.getOperand(0) == N0.getOperand(0))
18872     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18873       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18874         // Generate SUB & CMOV.
18875         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18876                                   DAG.getConstant(0, VT), N0.getOperand(0));
18877
18878         SDValue Ops[] = { N0.getOperand(0), Neg,
18879                           DAG.getConstant(X86::COND_GE, MVT::i8),
18880                           SDValue(Neg.getNode(), 1) };
18881         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18882       }
18883   return SDValue();
18884 }
18885
18886 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18887 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18888                                  TargetLowering::DAGCombinerInfo &DCI,
18889                                  const X86Subtarget *Subtarget) {
18890   if (DCI.isBeforeLegalizeOps())
18891     return SDValue();
18892
18893   if (Subtarget->hasCMov()) {
18894     SDValue RV = performIntegerAbsCombine(N, DAG);
18895     if (RV.getNode())
18896       return RV;
18897   }
18898
18899   return SDValue();
18900 }
18901
18902 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18903 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18904                                   TargetLowering::DAGCombinerInfo &DCI,
18905                                   const X86Subtarget *Subtarget) {
18906   LoadSDNode *Ld = cast<LoadSDNode>(N);
18907   EVT RegVT = Ld->getValueType(0);
18908   EVT MemVT = Ld->getMemoryVT();
18909   SDLoc dl(Ld);
18910   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18911   unsigned RegSz = RegVT.getSizeInBits();
18912
18913   // On Sandybridge unaligned 256bit loads are inefficient.
18914   ISD::LoadExtType Ext = Ld->getExtensionType();
18915   unsigned Alignment = Ld->getAlignment();
18916   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18917   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18918       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18919     unsigned NumElems = RegVT.getVectorNumElements();
18920     if (NumElems < 2)
18921       return SDValue();
18922
18923     SDValue Ptr = Ld->getBasePtr();
18924     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18925
18926     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18927                                   NumElems/2);
18928     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18929                                 Ld->getPointerInfo(), Ld->isVolatile(),
18930                                 Ld->isNonTemporal(), Ld->isInvariant(),
18931                                 Alignment);
18932     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18933     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18934                                 Ld->getPointerInfo(), Ld->isVolatile(),
18935                                 Ld->isNonTemporal(), Ld->isInvariant(),
18936                                 std::min(16U, Alignment));
18937     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18938                              Load1.getValue(1),
18939                              Load2.getValue(1));
18940
18941     SDValue NewVec = DAG.getUNDEF(RegVT);
18942     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18943     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18944     return DCI.CombineTo(N, NewVec, TF, true);
18945   }
18946
18947   // If this is a vector EXT Load then attempt to optimize it using a
18948   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18949   // expansion is still better than scalar code.
18950   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18951   // emit a shuffle and a arithmetic shift.
18952   // TODO: It is possible to support ZExt by zeroing the undef values
18953   // during the shuffle phase or after the shuffle.
18954   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18955       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18956     assert(MemVT != RegVT && "Cannot extend to the same type");
18957     assert(MemVT.isVector() && "Must load a vector from memory");
18958
18959     unsigned NumElems = RegVT.getVectorNumElements();
18960     unsigned MemSz = MemVT.getSizeInBits();
18961     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18962
18963     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18964       return SDValue();
18965
18966     // All sizes must be a power of two.
18967     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18968       return SDValue();
18969
18970     // Attempt to load the original value using scalar loads.
18971     // Find the largest scalar type that divides the total loaded size.
18972     MVT SclrLoadTy = MVT::i8;
18973     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18974          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18975       MVT Tp = (MVT::SimpleValueType)tp;
18976       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18977         SclrLoadTy = Tp;
18978       }
18979     }
18980
18981     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18982     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18983         (64 <= MemSz))
18984       SclrLoadTy = MVT::f64;
18985
18986     // Calculate the number of scalar loads that we need to perform
18987     // in order to load our vector from memory.
18988     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18989     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18990       return SDValue();
18991
18992     unsigned loadRegZize = RegSz;
18993     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18994       loadRegZize /= 2;
18995
18996     // Represent our vector as a sequence of elements which are the
18997     // largest scalar that we can load.
18998     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18999       loadRegZize/SclrLoadTy.getSizeInBits());
19000
19001     // Represent the data using the same element type that is stored in
19002     // memory. In practice, we ''widen'' MemVT.
19003     EVT WideVecVT =
19004           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19005                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19006
19007     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19008       "Invalid vector type");
19009
19010     // We can't shuffle using an illegal type.
19011     if (!TLI.isTypeLegal(WideVecVT))
19012       return SDValue();
19013
19014     SmallVector<SDValue, 8> Chains;
19015     SDValue Ptr = Ld->getBasePtr();
19016     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19017                                         TLI.getPointerTy());
19018     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19019
19020     for (unsigned i = 0; i < NumLoads; ++i) {
19021       // Perform a single load.
19022       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19023                                        Ptr, Ld->getPointerInfo(),
19024                                        Ld->isVolatile(), Ld->isNonTemporal(),
19025                                        Ld->isInvariant(), Ld->getAlignment());
19026       Chains.push_back(ScalarLoad.getValue(1));
19027       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19028       // another round of DAGCombining.
19029       if (i == 0)
19030         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19031       else
19032         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19033                           ScalarLoad, DAG.getIntPtrConstant(i));
19034
19035       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19036     }
19037
19038     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19039
19040     // Bitcast the loaded value to a vector of the original element type, in
19041     // the size of the target vector type.
19042     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19043     unsigned SizeRatio = RegSz/MemSz;
19044
19045     if (Ext == ISD::SEXTLOAD) {
19046       // If we have SSE4.1 we can directly emit a VSEXT node.
19047       if (Subtarget->hasSSE41()) {
19048         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19049         return DCI.CombineTo(N, Sext, TF, true);
19050       }
19051
19052       // Otherwise we'll shuffle the small elements in the high bits of the
19053       // larger type and perform an arithmetic shift. If the shift is not legal
19054       // it's better to scalarize.
19055       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19056         return SDValue();
19057
19058       // Redistribute the loaded elements into the different locations.
19059       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19060       for (unsigned i = 0; i != NumElems; ++i)
19061         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19062
19063       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19064                                            DAG.getUNDEF(WideVecVT),
19065                                            &ShuffleVec[0]);
19066
19067       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19068
19069       // Build the arithmetic shift.
19070       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19071                      MemVT.getVectorElementType().getSizeInBits();
19072       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19073                           DAG.getConstant(Amt, RegVT));
19074
19075       return DCI.CombineTo(N, Shuff, TF, true);
19076     }
19077
19078     // Redistribute the loaded elements into the different locations.
19079     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19080     for (unsigned i = 0; i != NumElems; ++i)
19081       ShuffleVec[i*SizeRatio] = i;
19082
19083     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19084                                          DAG.getUNDEF(WideVecVT),
19085                                          &ShuffleVec[0]);
19086
19087     // Bitcast to the requested type.
19088     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19089     // Replace the original load with the new sequence
19090     // and return the new chain.
19091     return DCI.CombineTo(N, Shuff, TF, true);
19092   }
19093
19094   return SDValue();
19095 }
19096
19097 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19098 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19099                                    const X86Subtarget *Subtarget) {
19100   StoreSDNode *St = cast<StoreSDNode>(N);
19101   EVT VT = St->getValue().getValueType();
19102   EVT StVT = St->getMemoryVT();
19103   SDLoc dl(St);
19104   SDValue StoredVal = St->getOperand(1);
19105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19106
19107   // If we are saving a concatenation of two XMM registers, perform two stores.
19108   // On Sandy Bridge, 256-bit memory operations are executed by two
19109   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19110   // memory  operation.
19111   unsigned Alignment = St->getAlignment();
19112   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19113   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19114       StVT == VT && !IsAligned) {
19115     unsigned NumElems = VT.getVectorNumElements();
19116     if (NumElems < 2)
19117       return SDValue();
19118
19119     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19120     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19121
19122     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19123     SDValue Ptr0 = St->getBasePtr();
19124     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19125
19126     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19127                                 St->getPointerInfo(), St->isVolatile(),
19128                                 St->isNonTemporal(), Alignment);
19129     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19130                                 St->getPointerInfo(), St->isVolatile(),
19131                                 St->isNonTemporal(),
19132                                 std::min(16U, Alignment));
19133     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19134   }
19135
19136   // Optimize trunc store (of multiple scalars) to shuffle and store.
19137   // First, pack all of the elements in one place. Next, store to memory
19138   // in fewer chunks.
19139   if (St->isTruncatingStore() && VT.isVector()) {
19140     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19141     unsigned NumElems = VT.getVectorNumElements();
19142     assert(StVT != VT && "Cannot truncate to the same type");
19143     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19144     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19145
19146     // From, To sizes and ElemCount must be pow of two
19147     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19148     // We are going to use the original vector elt for storing.
19149     // Accumulated smaller vector elements must be a multiple of the store size.
19150     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19151
19152     unsigned SizeRatio  = FromSz / ToSz;
19153
19154     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19155
19156     // Create a type on which we perform the shuffle
19157     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19158             StVT.getScalarType(), NumElems*SizeRatio);
19159
19160     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19161
19162     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19163     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19164     for (unsigned i = 0; i != NumElems; ++i)
19165       ShuffleVec[i] = i * SizeRatio;
19166
19167     // Can't shuffle using an illegal type.
19168     if (!TLI.isTypeLegal(WideVecVT))
19169       return SDValue();
19170
19171     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19172                                          DAG.getUNDEF(WideVecVT),
19173                                          &ShuffleVec[0]);
19174     // At this point all of the data is stored at the bottom of the
19175     // register. We now need to save it to mem.
19176
19177     // Find the largest store unit
19178     MVT StoreType = MVT::i8;
19179     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19180          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19181       MVT Tp = (MVT::SimpleValueType)tp;
19182       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19183         StoreType = Tp;
19184     }
19185
19186     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19187     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19188         (64 <= NumElems * ToSz))
19189       StoreType = MVT::f64;
19190
19191     // Bitcast the original vector into a vector of store-size units
19192     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19193             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19194     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19195     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19196     SmallVector<SDValue, 8> Chains;
19197     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19198                                         TLI.getPointerTy());
19199     SDValue Ptr = St->getBasePtr();
19200
19201     // Perform one or more big stores into memory.
19202     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19203       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19204                                    StoreType, ShuffWide,
19205                                    DAG.getIntPtrConstant(i));
19206       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19207                                 St->getPointerInfo(), St->isVolatile(),
19208                                 St->isNonTemporal(), St->getAlignment());
19209       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19210       Chains.push_back(Ch);
19211     }
19212
19213     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19214   }
19215
19216   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19217   // the FP state in cases where an emms may be missing.
19218   // A preferable solution to the general problem is to figure out the right
19219   // places to insert EMMS.  This qualifies as a quick hack.
19220
19221   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19222   if (VT.getSizeInBits() != 64)
19223     return SDValue();
19224
19225   const Function *F = DAG.getMachineFunction().getFunction();
19226   bool NoImplicitFloatOps = F->getAttributes().
19227     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19228   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19229                      && Subtarget->hasSSE2();
19230   if ((VT.isVector() ||
19231        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19232       isa<LoadSDNode>(St->getValue()) &&
19233       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19234       St->getChain().hasOneUse() && !St->isVolatile()) {
19235     SDNode* LdVal = St->getValue().getNode();
19236     LoadSDNode *Ld = nullptr;
19237     int TokenFactorIndex = -1;
19238     SmallVector<SDValue, 8> Ops;
19239     SDNode* ChainVal = St->getChain().getNode();
19240     // Must be a store of a load.  We currently handle two cases:  the load
19241     // is a direct child, and it's under an intervening TokenFactor.  It is
19242     // possible to dig deeper under nested TokenFactors.
19243     if (ChainVal == LdVal)
19244       Ld = cast<LoadSDNode>(St->getChain());
19245     else if (St->getValue().hasOneUse() &&
19246              ChainVal->getOpcode() == ISD::TokenFactor) {
19247       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19248         if (ChainVal->getOperand(i).getNode() == LdVal) {
19249           TokenFactorIndex = i;
19250           Ld = cast<LoadSDNode>(St->getValue());
19251         } else
19252           Ops.push_back(ChainVal->getOperand(i));
19253       }
19254     }
19255
19256     if (!Ld || !ISD::isNormalLoad(Ld))
19257       return SDValue();
19258
19259     // If this is not the MMX case, i.e. we are just turning i64 load/store
19260     // into f64 load/store, avoid the transformation if there are multiple
19261     // uses of the loaded value.
19262     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19263       return SDValue();
19264
19265     SDLoc LdDL(Ld);
19266     SDLoc StDL(N);
19267     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19268     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19269     // pair instead.
19270     if (Subtarget->is64Bit() || F64IsLegal) {
19271       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19272       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19273                                   Ld->getPointerInfo(), Ld->isVolatile(),
19274                                   Ld->isNonTemporal(), Ld->isInvariant(),
19275                                   Ld->getAlignment());
19276       SDValue NewChain = NewLd.getValue(1);
19277       if (TokenFactorIndex != -1) {
19278         Ops.push_back(NewChain);
19279         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19280       }
19281       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19282                           St->getPointerInfo(),
19283                           St->isVolatile(), St->isNonTemporal(),
19284                           St->getAlignment());
19285     }
19286
19287     // Otherwise, lower to two pairs of 32-bit loads / stores.
19288     SDValue LoAddr = Ld->getBasePtr();
19289     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19290                                  DAG.getConstant(4, MVT::i32));
19291
19292     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19293                                Ld->getPointerInfo(),
19294                                Ld->isVolatile(), Ld->isNonTemporal(),
19295                                Ld->isInvariant(), Ld->getAlignment());
19296     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19297                                Ld->getPointerInfo().getWithOffset(4),
19298                                Ld->isVolatile(), Ld->isNonTemporal(),
19299                                Ld->isInvariant(),
19300                                MinAlign(Ld->getAlignment(), 4));
19301
19302     SDValue NewChain = LoLd.getValue(1);
19303     if (TokenFactorIndex != -1) {
19304       Ops.push_back(LoLd);
19305       Ops.push_back(HiLd);
19306       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19307     }
19308
19309     LoAddr = St->getBasePtr();
19310     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19311                          DAG.getConstant(4, MVT::i32));
19312
19313     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19314                                 St->getPointerInfo(),
19315                                 St->isVolatile(), St->isNonTemporal(),
19316                                 St->getAlignment());
19317     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19318                                 St->getPointerInfo().getWithOffset(4),
19319                                 St->isVolatile(),
19320                                 St->isNonTemporal(),
19321                                 MinAlign(St->getAlignment(), 4));
19322     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19323   }
19324   return SDValue();
19325 }
19326
19327 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19328 /// and return the operands for the horizontal operation in LHS and RHS.  A
19329 /// horizontal operation performs the binary operation on successive elements
19330 /// of its first operand, then on successive elements of its second operand,
19331 /// returning the resulting values in a vector.  For example, if
19332 ///   A = < float a0, float a1, float a2, float a3 >
19333 /// and
19334 ///   B = < float b0, float b1, float b2, float b3 >
19335 /// then the result of doing a horizontal operation on A and B is
19336 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19337 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19338 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19339 /// set to A, RHS to B, and the routine returns 'true'.
19340 /// Note that the binary operation should have the property that if one of the
19341 /// operands is UNDEF then the result is UNDEF.
19342 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19343   // Look for the following pattern: if
19344   //   A = < float a0, float a1, float a2, float a3 >
19345   //   B = < float b0, float b1, float b2, float b3 >
19346   // and
19347   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19348   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19349   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19350   // which is A horizontal-op B.
19351
19352   // At least one of the operands should be a vector shuffle.
19353   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19354       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19355     return false;
19356
19357   MVT VT = LHS.getSimpleValueType();
19358
19359   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19360          "Unsupported vector type for horizontal add/sub");
19361
19362   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19363   // operate independently on 128-bit lanes.
19364   unsigned NumElts = VT.getVectorNumElements();
19365   unsigned NumLanes = VT.getSizeInBits()/128;
19366   unsigned NumLaneElts = NumElts / NumLanes;
19367   assert((NumLaneElts % 2 == 0) &&
19368          "Vector type should have an even number of elements in each lane");
19369   unsigned HalfLaneElts = NumLaneElts/2;
19370
19371   // View LHS in the form
19372   //   LHS = VECTOR_SHUFFLE A, B, LMask
19373   // If LHS is not a shuffle then pretend it is the shuffle
19374   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19375   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19376   // type VT.
19377   SDValue A, B;
19378   SmallVector<int, 16> LMask(NumElts);
19379   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19380     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19381       A = LHS.getOperand(0);
19382     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19383       B = LHS.getOperand(1);
19384     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19385     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19386   } else {
19387     if (LHS.getOpcode() != ISD::UNDEF)
19388       A = LHS;
19389     for (unsigned i = 0; i != NumElts; ++i)
19390       LMask[i] = i;
19391   }
19392
19393   // Likewise, view RHS in the form
19394   //   RHS = VECTOR_SHUFFLE C, D, RMask
19395   SDValue C, D;
19396   SmallVector<int, 16> RMask(NumElts);
19397   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19398     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19399       C = RHS.getOperand(0);
19400     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19401       D = RHS.getOperand(1);
19402     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19403     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19404   } else {
19405     if (RHS.getOpcode() != ISD::UNDEF)
19406       C = RHS;
19407     for (unsigned i = 0; i != NumElts; ++i)
19408       RMask[i] = i;
19409   }
19410
19411   // Check that the shuffles are both shuffling the same vectors.
19412   if (!(A == C && B == D) && !(A == D && B == C))
19413     return false;
19414
19415   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19416   if (!A.getNode() && !B.getNode())
19417     return false;
19418
19419   // If A and B occur in reverse order in RHS, then "swap" them (which means
19420   // rewriting the mask).
19421   if (A != C)
19422     CommuteVectorShuffleMask(RMask, NumElts);
19423
19424   // At this point LHS and RHS are equivalent to
19425   //   LHS = VECTOR_SHUFFLE A, B, LMask
19426   //   RHS = VECTOR_SHUFFLE A, B, RMask
19427   // Check that the masks correspond to performing a horizontal operation.
19428   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19429     for (unsigned i = 0; i != NumLaneElts; ++i) {
19430       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19431
19432       // Ignore any UNDEF components.
19433       if (LIdx < 0 || RIdx < 0 ||
19434           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19435           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19436         continue;
19437
19438       // Check that successive elements are being operated on.  If not, this is
19439       // not a horizontal operation.
19440       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19441       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19442       if (!(LIdx == Index && RIdx == Index + 1) &&
19443           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19444         return false;
19445     }
19446   }
19447
19448   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19449   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19450   return true;
19451 }
19452
19453 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19454 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19455                                   const X86Subtarget *Subtarget) {
19456   EVT VT = N->getValueType(0);
19457   SDValue LHS = N->getOperand(0);
19458   SDValue RHS = N->getOperand(1);
19459
19460   // Try to synthesize horizontal adds from adds of shuffles.
19461   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19462        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19463       isHorizontalBinOp(LHS, RHS, true))
19464     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19465   return SDValue();
19466 }
19467
19468 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19469 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19470                                   const X86Subtarget *Subtarget) {
19471   EVT VT = N->getValueType(0);
19472   SDValue LHS = N->getOperand(0);
19473   SDValue RHS = N->getOperand(1);
19474
19475   // Try to synthesize horizontal subs from subs of shuffles.
19476   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19477        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19478       isHorizontalBinOp(LHS, RHS, false))
19479     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19480   return SDValue();
19481 }
19482
19483 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19484 /// X86ISD::FXOR nodes.
19485 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19486   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19487   // F[X]OR(0.0, x) -> x
19488   // F[X]OR(x, 0.0) -> x
19489   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19490     if (C->getValueAPF().isPosZero())
19491       return N->getOperand(1);
19492   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19493     if (C->getValueAPF().isPosZero())
19494       return N->getOperand(0);
19495   return SDValue();
19496 }
19497
19498 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19499 /// X86ISD::FMAX nodes.
19500 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19501   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19502
19503   // Only perform optimizations if UnsafeMath is used.
19504   if (!DAG.getTarget().Options.UnsafeFPMath)
19505     return SDValue();
19506
19507   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19508   // into FMINC and FMAXC, which are Commutative operations.
19509   unsigned NewOp = 0;
19510   switch (N->getOpcode()) {
19511     default: llvm_unreachable("unknown opcode");
19512     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19513     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19514   }
19515
19516   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19517                      N->getOperand(0), N->getOperand(1));
19518 }
19519
19520 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19521 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19522   // FAND(0.0, x) -> 0.0
19523   // FAND(x, 0.0) -> 0.0
19524   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19525     if (C->getValueAPF().isPosZero())
19526       return N->getOperand(0);
19527   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19528     if (C->getValueAPF().isPosZero())
19529       return N->getOperand(1);
19530   return SDValue();
19531 }
19532
19533 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19534 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19535   // FANDN(x, 0.0) -> 0.0
19536   // FANDN(0.0, x) -> x
19537   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19538     if (C->getValueAPF().isPosZero())
19539       return N->getOperand(1);
19540   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19541     if (C->getValueAPF().isPosZero())
19542       return N->getOperand(1);
19543   return SDValue();
19544 }
19545
19546 static SDValue PerformBTCombine(SDNode *N,
19547                                 SelectionDAG &DAG,
19548                                 TargetLowering::DAGCombinerInfo &DCI) {
19549   // BT ignores high bits in the bit index operand.
19550   SDValue Op1 = N->getOperand(1);
19551   if (Op1.hasOneUse()) {
19552     unsigned BitWidth = Op1.getValueSizeInBits();
19553     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19554     APInt KnownZero, KnownOne;
19555     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19556                                           !DCI.isBeforeLegalizeOps());
19557     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19558     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19559         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19560       DCI.CommitTargetLoweringOpt(TLO);
19561   }
19562   return SDValue();
19563 }
19564
19565 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19566   SDValue Op = N->getOperand(0);
19567   if (Op.getOpcode() == ISD::BITCAST)
19568     Op = Op.getOperand(0);
19569   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19570   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19571       VT.getVectorElementType().getSizeInBits() ==
19572       OpVT.getVectorElementType().getSizeInBits()) {
19573     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19574   }
19575   return SDValue();
19576 }
19577
19578 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19579                                                const X86Subtarget *Subtarget) {
19580   EVT VT = N->getValueType(0);
19581   if (!VT.isVector())
19582     return SDValue();
19583
19584   SDValue N0 = N->getOperand(0);
19585   SDValue N1 = N->getOperand(1);
19586   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19587   SDLoc dl(N);
19588
19589   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19590   // both SSE and AVX2 since there is no sign-extended shift right
19591   // operation on a vector with 64-bit elements.
19592   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19593   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19594   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19595       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19596     SDValue N00 = N0.getOperand(0);
19597
19598     // EXTLOAD has a better solution on AVX2,
19599     // it may be replaced with X86ISD::VSEXT node.
19600     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19601       if (!ISD::isNormalLoad(N00.getNode()))
19602         return SDValue();
19603
19604     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19605         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19606                                   N00, N1);
19607       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19608     }
19609   }
19610   return SDValue();
19611 }
19612
19613 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19614                                   TargetLowering::DAGCombinerInfo &DCI,
19615                                   const X86Subtarget *Subtarget) {
19616   if (!DCI.isBeforeLegalizeOps())
19617     return SDValue();
19618
19619   if (!Subtarget->hasFp256())
19620     return SDValue();
19621
19622   EVT VT = N->getValueType(0);
19623   if (VT.isVector() && VT.getSizeInBits() == 256) {
19624     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19625     if (R.getNode())
19626       return R;
19627   }
19628
19629   return SDValue();
19630 }
19631
19632 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19633                                  const X86Subtarget* Subtarget) {
19634   SDLoc dl(N);
19635   EVT VT = N->getValueType(0);
19636
19637   // Let legalize expand this if it isn't a legal type yet.
19638   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19639     return SDValue();
19640
19641   EVT ScalarVT = VT.getScalarType();
19642   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19643       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19644     return SDValue();
19645
19646   SDValue A = N->getOperand(0);
19647   SDValue B = N->getOperand(1);
19648   SDValue C = N->getOperand(2);
19649
19650   bool NegA = (A.getOpcode() == ISD::FNEG);
19651   bool NegB = (B.getOpcode() == ISD::FNEG);
19652   bool NegC = (C.getOpcode() == ISD::FNEG);
19653
19654   // Negative multiplication when NegA xor NegB
19655   bool NegMul = (NegA != NegB);
19656   if (NegA)
19657     A = A.getOperand(0);
19658   if (NegB)
19659     B = B.getOperand(0);
19660   if (NegC)
19661     C = C.getOperand(0);
19662
19663   unsigned Opcode;
19664   if (!NegMul)
19665     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19666   else
19667     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19668
19669   return DAG.getNode(Opcode, dl, VT, A, B, C);
19670 }
19671
19672 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19673                                   TargetLowering::DAGCombinerInfo &DCI,
19674                                   const X86Subtarget *Subtarget) {
19675   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19676   //           (and (i32 x86isd::setcc_carry), 1)
19677   // This eliminates the zext. This transformation is necessary because
19678   // ISD::SETCC is always legalized to i8.
19679   SDLoc dl(N);
19680   SDValue N0 = N->getOperand(0);
19681   EVT VT = N->getValueType(0);
19682
19683   if (N0.getOpcode() == ISD::AND &&
19684       N0.hasOneUse() &&
19685       N0.getOperand(0).hasOneUse()) {
19686     SDValue N00 = N0.getOperand(0);
19687     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19688       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19689       if (!C || C->getZExtValue() != 1)
19690         return SDValue();
19691       return DAG.getNode(ISD::AND, dl, VT,
19692                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19693                                      N00.getOperand(0), N00.getOperand(1)),
19694                          DAG.getConstant(1, VT));
19695     }
19696   }
19697
19698   if (N0.getOpcode() == ISD::TRUNCATE &&
19699       N0.hasOneUse() &&
19700       N0.getOperand(0).hasOneUse()) {
19701     SDValue N00 = N0.getOperand(0);
19702     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19703       return DAG.getNode(ISD::AND, dl, VT,
19704                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19705                                      N00.getOperand(0), N00.getOperand(1)),
19706                          DAG.getConstant(1, VT));
19707     }
19708   }
19709   if (VT.is256BitVector()) {
19710     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19711     if (R.getNode())
19712       return R;
19713   }
19714
19715   return SDValue();
19716 }
19717
19718 // Optimize x == -y --> x+y == 0
19719 //          x != -y --> x+y != 0
19720 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19721                                       const X86Subtarget* Subtarget) {
19722   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19723   SDValue LHS = N->getOperand(0);
19724   SDValue RHS = N->getOperand(1);
19725   EVT VT = N->getValueType(0);
19726   SDLoc DL(N);
19727
19728   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19729     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19730       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19731         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19732                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19733         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19734                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19735       }
19736   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19737     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19738       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19739         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19740                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19741         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19742                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19743       }
19744
19745   if (VT.getScalarType() == MVT::i1) {
19746     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19747       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19748     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19749     if (!IsSEXT0 && !IsVZero0)
19750       return SDValue();
19751     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19752       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19753     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19754
19755     if (!IsSEXT1 && !IsVZero1)
19756       return SDValue();
19757
19758     if (IsSEXT0 && IsVZero1) {
19759       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19760       if (CC == ISD::SETEQ)
19761         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19762       return LHS.getOperand(0);
19763     }
19764     if (IsSEXT1 && IsVZero0) {
19765       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19766       if (CC == ISD::SETEQ)
19767         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19768       return RHS.getOperand(0);
19769     }
19770   }
19771
19772   return SDValue();
19773 }
19774
19775 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19776 // as "sbb reg,reg", since it can be extended without zext and produces
19777 // an all-ones bit which is more useful than 0/1 in some cases.
19778 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19779                                MVT VT) {
19780   if (VT == MVT::i8)
19781     return DAG.getNode(ISD::AND, DL, VT,
19782                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19783                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19784                        DAG.getConstant(1, VT));
19785   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19786   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19787                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19788                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19789 }
19790
19791 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19792 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19793                                    TargetLowering::DAGCombinerInfo &DCI,
19794                                    const X86Subtarget *Subtarget) {
19795   SDLoc DL(N);
19796   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19797   SDValue EFLAGS = N->getOperand(1);
19798
19799   if (CC == X86::COND_A) {
19800     // Try to convert COND_A into COND_B in an attempt to facilitate
19801     // materializing "setb reg".
19802     //
19803     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19804     // cannot take an immediate as its first operand.
19805     //
19806     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19807         EFLAGS.getValueType().isInteger() &&
19808         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19809       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19810                                    EFLAGS.getNode()->getVTList(),
19811                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19812       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19813       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19814     }
19815   }
19816
19817   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19818   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19819   // cases.
19820   if (CC == X86::COND_B)
19821     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19822
19823   SDValue Flags;
19824
19825   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19826   if (Flags.getNode()) {
19827     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19828     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19829   }
19830
19831   return SDValue();
19832 }
19833
19834 // Optimize branch condition evaluation.
19835 //
19836 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19837                                     TargetLowering::DAGCombinerInfo &DCI,
19838                                     const X86Subtarget *Subtarget) {
19839   SDLoc DL(N);
19840   SDValue Chain = N->getOperand(0);
19841   SDValue Dest = N->getOperand(1);
19842   SDValue EFLAGS = N->getOperand(3);
19843   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19844
19845   SDValue Flags;
19846
19847   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19848   if (Flags.getNode()) {
19849     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19850     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19851                        Flags);
19852   }
19853
19854   return SDValue();
19855 }
19856
19857 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19858                                         const X86TargetLowering *XTLI) {
19859   SDValue Op0 = N->getOperand(0);
19860   EVT InVT = Op0->getValueType(0);
19861
19862   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19863   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19864     SDLoc dl(N);
19865     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19866     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19867     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19868   }
19869
19870   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19871   // a 32-bit target where SSE doesn't support i64->FP operations.
19872   if (Op0.getOpcode() == ISD::LOAD) {
19873     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19874     EVT VT = Ld->getValueType(0);
19875     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19876         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19877         !XTLI->getSubtarget()->is64Bit() &&
19878         VT == MVT::i64) {
19879       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19880                                           Ld->getChain(), Op0, DAG);
19881       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19882       return FILDChain;
19883     }
19884   }
19885   return SDValue();
19886 }
19887
19888 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19889 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19890                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19891   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19892   // the result is either zero or one (depending on the input carry bit).
19893   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19894   if (X86::isZeroNode(N->getOperand(0)) &&
19895       X86::isZeroNode(N->getOperand(1)) &&
19896       // We don't have a good way to replace an EFLAGS use, so only do this when
19897       // dead right now.
19898       SDValue(N, 1).use_empty()) {
19899     SDLoc DL(N);
19900     EVT VT = N->getValueType(0);
19901     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19902     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19903                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19904                                            DAG.getConstant(X86::COND_B,MVT::i8),
19905                                            N->getOperand(2)),
19906                                DAG.getConstant(1, VT));
19907     return DCI.CombineTo(N, Res1, CarryOut);
19908   }
19909
19910   return SDValue();
19911 }
19912
19913 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19914 //      (add Y, (setne X, 0)) -> sbb -1, Y
19915 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19916 //      (sub (setne X, 0), Y) -> adc -1, Y
19917 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19918   SDLoc DL(N);
19919
19920   // Look through ZExts.
19921   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19922   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19923     return SDValue();
19924
19925   SDValue SetCC = Ext.getOperand(0);
19926   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19927     return SDValue();
19928
19929   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19930   if (CC != X86::COND_E && CC != X86::COND_NE)
19931     return SDValue();
19932
19933   SDValue Cmp = SetCC.getOperand(1);
19934   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19935       !X86::isZeroNode(Cmp.getOperand(1)) ||
19936       !Cmp.getOperand(0).getValueType().isInteger())
19937     return SDValue();
19938
19939   SDValue CmpOp0 = Cmp.getOperand(0);
19940   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19941                                DAG.getConstant(1, CmpOp0.getValueType()));
19942
19943   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19944   if (CC == X86::COND_NE)
19945     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19946                        DL, OtherVal.getValueType(), OtherVal,
19947                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19948   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19949                      DL, OtherVal.getValueType(), OtherVal,
19950                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19951 }
19952
19953 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19954 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19955                                  const X86Subtarget *Subtarget) {
19956   EVT VT = N->getValueType(0);
19957   SDValue Op0 = N->getOperand(0);
19958   SDValue Op1 = N->getOperand(1);
19959
19960   // Try to synthesize horizontal adds from adds of shuffles.
19961   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19962        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19963       isHorizontalBinOp(Op0, Op1, true))
19964     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19965
19966   return OptimizeConditionalInDecrement(N, DAG);
19967 }
19968
19969 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19970                                  const X86Subtarget *Subtarget) {
19971   SDValue Op0 = N->getOperand(0);
19972   SDValue Op1 = N->getOperand(1);
19973
19974   // X86 can't encode an immediate LHS of a sub. See if we can push the
19975   // negation into a preceding instruction.
19976   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19977     // If the RHS of the sub is a XOR with one use and a constant, invert the
19978     // immediate. Then add one to the LHS of the sub so we can turn
19979     // X-Y -> X+~Y+1, saving one register.
19980     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19981         isa<ConstantSDNode>(Op1.getOperand(1))) {
19982       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19983       EVT VT = Op0.getValueType();
19984       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19985                                    Op1.getOperand(0),
19986                                    DAG.getConstant(~XorC, VT));
19987       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19988                          DAG.getConstant(C->getAPIntValue()+1, VT));
19989     }
19990   }
19991
19992   // Try to synthesize horizontal adds from adds of shuffles.
19993   EVT VT = N->getValueType(0);
19994   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19995        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19996       isHorizontalBinOp(Op0, Op1, true))
19997     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19998
19999   return OptimizeConditionalInDecrement(N, DAG);
20000 }
20001
20002 /// performVZEXTCombine - Performs build vector combines
20003 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20004                                         TargetLowering::DAGCombinerInfo &DCI,
20005                                         const X86Subtarget *Subtarget) {
20006   // (vzext (bitcast (vzext (x)) -> (vzext x)
20007   SDValue In = N->getOperand(0);
20008   while (In.getOpcode() == ISD::BITCAST)
20009     In = In.getOperand(0);
20010
20011   if (In.getOpcode() != X86ISD::VZEXT)
20012     return SDValue();
20013
20014   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20015                      In.getOperand(0));
20016 }
20017
20018 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20019                                              DAGCombinerInfo &DCI) const {
20020   SelectionDAG &DAG = DCI.DAG;
20021   switch (N->getOpcode()) {
20022   default: break;
20023   case ISD::EXTRACT_VECTOR_ELT:
20024     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20025   case ISD::VSELECT:
20026   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20027   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20028   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20029   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20030   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20031   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20032   case ISD::SHL:
20033   case ISD::SRA:
20034   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20035   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20036   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20037   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20038   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20039   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20040   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20041   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20042   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20043   case X86ISD::FXOR:
20044   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20045   case X86ISD::FMIN:
20046   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20047   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20048   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20049   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20050   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20051   case ISD::ANY_EXTEND:
20052   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20053   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20054   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20055   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20056   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20057   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20058   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20059   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20060   case X86ISD::SHUFP:       // Handle all target specific shuffles
20061   case X86ISD::PALIGNR:
20062   case X86ISD::UNPCKH:
20063   case X86ISD::UNPCKL:
20064   case X86ISD::MOVHLPS:
20065   case X86ISD::MOVLHPS:
20066   case X86ISD::PSHUFD:
20067   case X86ISD::PSHUFHW:
20068   case X86ISD::PSHUFLW:
20069   case X86ISD::MOVSS:
20070   case X86ISD::MOVSD:
20071   case X86ISD::VPERMILP:
20072   case X86ISD::VPERM2X128:
20073   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20074   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20075   }
20076
20077   return SDValue();
20078 }
20079
20080 /// isTypeDesirableForOp - Return true if the target has native support for
20081 /// the specified value type and it is 'desirable' to use the type for the
20082 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20083 /// instruction encodings are longer and some i16 instructions are slow.
20084 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20085   if (!isTypeLegal(VT))
20086     return false;
20087   if (VT != MVT::i16)
20088     return true;
20089
20090   switch (Opc) {
20091   default:
20092     return true;
20093   case ISD::LOAD:
20094   case ISD::SIGN_EXTEND:
20095   case ISD::ZERO_EXTEND:
20096   case ISD::ANY_EXTEND:
20097   case ISD::SHL:
20098   case ISD::SRL:
20099   case ISD::SUB:
20100   case ISD::ADD:
20101   case ISD::MUL:
20102   case ISD::AND:
20103   case ISD::OR:
20104   case ISD::XOR:
20105     return false;
20106   }
20107 }
20108
20109 /// IsDesirableToPromoteOp - This method query the target whether it is
20110 /// beneficial for dag combiner to promote the specified node. If true, it
20111 /// should return the desired promotion type by reference.
20112 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20113   EVT VT = Op.getValueType();
20114   if (VT != MVT::i16)
20115     return false;
20116
20117   bool Promote = false;
20118   bool Commute = false;
20119   switch (Op.getOpcode()) {
20120   default: break;
20121   case ISD::LOAD: {
20122     LoadSDNode *LD = cast<LoadSDNode>(Op);
20123     // If the non-extending load has a single use and it's not live out, then it
20124     // might be folded.
20125     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20126                                                      Op.hasOneUse()*/) {
20127       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20128              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20129         // The only case where we'd want to promote LOAD (rather then it being
20130         // promoted as an operand is when it's only use is liveout.
20131         if (UI->getOpcode() != ISD::CopyToReg)
20132           return false;
20133       }
20134     }
20135     Promote = true;
20136     break;
20137   }
20138   case ISD::SIGN_EXTEND:
20139   case ISD::ZERO_EXTEND:
20140   case ISD::ANY_EXTEND:
20141     Promote = true;
20142     break;
20143   case ISD::SHL:
20144   case ISD::SRL: {
20145     SDValue N0 = Op.getOperand(0);
20146     // Look out for (store (shl (load), x)).
20147     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20148       return false;
20149     Promote = true;
20150     break;
20151   }
20152   case ISD::ADD:
20153   case ISD::MUL:
20154   case ISD::AND:
20155   case ISD::OR:
20156   case ISD::XOR:
20157     Commute = true;
20158     // fallthrough
20159   case ISD::SUB: {
20160     SDValue N0 = Op.getOperand(0);
20161     SDValue N1 = Op.getOperand(1);
20162     if (!Commute && MayFoldLoad(N1))
20163       return false;
20164     // Avoid disabling potential load folding opportunities.
20165     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20166       return false;
20167     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20168       return false;
20169     Promote = true;
20170   }
20171   }
20172
20173   PVT = MVT::i32;
20174   return Promote;
20175 }
20176
20177 //===----------------------------------------------------------------------===//
20178 //                           X86 Inline Assembly Support
20179 //===----------------------------------------------------------------------===//
20180
20181 namespace {
20182   // Helper to match a string separated by whitespace.
20183   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20184     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20185
20186     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20187       StringRef piece(*args[i]);
20188       if (!s.startswith(piece)) // Check if the piece matches.
20189         return false;
20190
20191       s = s.substr(piece.size());
20192       StringRef::size_type pos = s.find_first_not_of(" \t");
20193       if (pos == 0) // We matched a prefix.
20194         return false;
20195
20196       s = s.substr(pos);
20197     }
20198
20199     return s.empty();
20200   }
20201   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20202 }
20203
20204 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20205
20206   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20207     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20208         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20209         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20210
20211       if (AsmPieces.size() == 3)
20212         return true;
20213       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20214         return true;
20215     }
20216   }
20217   return false;
20218 }
20219
20220 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20221   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20222
20223   std::string AsmStr = IA->getAsmString();
20224
20225   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20226   if (!Ty || Ty->getBitWidth() % 16 != 0)
20227     return false;
20228
20229   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20230   SmallVector<StringRef, 4> AsmPieces;
20231   SplitString(AsmStr, AsmPieces, ";\n");
20232
20233   switch (AsmPieces.size()) {
20234   default: return false;
20235   case 1:
20236     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20237     // we will turn this bswap into something that will be lowered to logical
20238     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20239     // lower so don't worry about this.
20240     // bswap $0
20241     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20242         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20243         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20244         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20245         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20246         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20247       // No need to check constraints, nothing other than the equivalent of
20248       // "=r,0" would be valid here.
20249       return IntrinsicLowering::LowerToByteSwap(CI);
20250     }
20251
20252     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20253     if (CI->getType()->isIntegerTy(16) &&
20254         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20255         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20256          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20257       AsmPieces.clear();
20258       const std::string &ConstraintsStr = IA->getConstraintString();
20259       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20260       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20261       if (clobbersFlagRegisters(AsmPieces))
20262         return IntrinsicLowering::LowerToByteSwap(CI);
20263     }
20264     break;
20265   case 3:
20266     if (CI->getType()->isIntegerTy(32) &&
20267         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20268         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20269         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20270         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20271       AsmPieces.clear();
20272       const std::string &ConstraintsStr = IA->getConstraintString();
20273       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20274       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20275       if (clobbersFlagRegisters(AsmPieces))
20276         return IntrinsicLowering::LowerToByteSwap(CI);
20277     }
20278
20279     if (CI->getType()->isIntegerTy(64)) {
20280       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20281       if (Constraints.size() >= 2 &&
20282           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20283           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20284         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20285         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20286             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20287             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20288           return IntrinsicLowering::LowerToByteSwap(CI);
20289       }
20290     }
20291     break;
20292   }
20293   return false;
20294 }
20295
20296 /// getConstraintType - Given a constraint letter, return the type of
20297 /// constraint it is for this target.
20298 X86TargetLowering::ConstraintType
20299 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20300   if (Constraint.size() == 1) {
20301     switch (Constraint[0]) {
20302     case 'R':
20303     case 'q':
20304     case 'Q':
20305     case 'f':
20306     case 't':
20307     case 'u':
20308     case 'y':
20309     case 'x':
20310     case 'Y':
20311     case 'l':
20312       return C_RegisterClass;
20313     case 'a':
20314     case 'b':
20315     case 'c':
20316     case 'd':
20317     case 'S':
20318     case 'D':
20319     case 'A':
20320       return C_Register;
20321     case 'I':
20322     case 'J':
20323     case 'K':
20324     case 'L':
20325     case 'M':
20326     case 'N':
20327     case 'G':
20328     case 'C':
20329     case 'e':
20330     case 'Z':
20331       return C_Other;
20332     default:
20333       break;
20334     }
20335   }
20336   return TargetLowering::getConstraintType(Constraint);
20337 }
20338
20339 /// Examine constraint type and operand type and determine a weight value.
20340 /// This object must already have been set up with the operand type
20341 /// and the current alternative constraint selected.
20342 TargetLowering::ConstraintWeight
20343   X86TargetLowering::getSingleConstraintMatchWeight(
20344     AsmOperandInfo &info, const char *constraint) const {
20345   ConstraintWeight weight = CW_Invalid;
20346   Value *CallOperandVal = info.CallOperandVal;
20347     // If we don't have a value, we can't do a match,
20348     // but allow it at the lowest weight.
20349   if (!CallOperandVal)
20350     return CW_Default;
20351   Type *type = CallOperandVal->getType();
20352   // Look at the constraint type.
20353   switch (*constraint) {
20354   default:
20355     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20356   case 'R':
20357   case 'q':
20358   case 'Q':
20359   case 'a':
20360   case 'b':
20361   case 'c':
20362   case 'd':
20363   case 'S':
20364   case 'D':
20365   case 'A':
20366     if (CallOperandVal->getType()->isIntegerTy())
20367       weight = CW_SpecificReg;
20368     break;
20369   case 'f':
20370   case 't':
20371   case 'u':
20372     if (type->isFloatingPointTy())
20373       weight = CW_SpecificReg;
20374     break;
20375   case 'y':
20376     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20377       weight = CW_SpecificReg;
20378     break;
20379   case 'x':
20380   case 'Y':
20381     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20382         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20383       weight = CW_Register;
20384     break;
20385   case 'I':
20386     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20387       if (C->getZExtValue() <= 31)
20388         weight = CW_Constant;
20389     }
20390     break;
20391   case 'J':
20392     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20393       if (C->getZExtValue() <= 63)
20394         weight = CW_Constant;
20395     }
20396     break;
20397   case 'K':
20398     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20399       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20400         weight = CW_Constant;
20401     }
20402     break;
20403   case 'L':
20404     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20405       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20406         weight = CW_Constant;
20407     }
20408     break;
20409   case 'M':
20410     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20411       if (C->getZExtValue() <= 3)
20412         weight = CW_Constant;
20413     }
20414     break;
20415   case 'N':
20416     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20417       if (C->getZExtValue() <= 0xff)
20418         weight = CW_Constant;
20419     }
20420     break;
20421   case 'G':
20422   case 'C':
20423     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20424       weight = CW_Constant;
20425     }
20426     break;
20427   case 'e':
20428     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20429       if ((C->getSExtValue() >= -0x80000000LL) &&
20430           (C->getSExtValue() <= 0x7fffffffLL))
20431         weight = CW_Constant;
20432     }
20433     break;
20434   case 'Z':
20435     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20436       if (C->getZExtValue() <= 0xffffffff)
20437         weight = CW_Constant;
20438     }
20439     break;
20440   }
20441   return weight;
20442 }
20443
20444 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20445 /// with another that has more specific requirements based on the type of the
20446 /// corresponding operand.
20447 const char *X86TargetLowering::
20448 LowerXConstraint(EVT ConstraintVT) const {
20449   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20450   // 'f' like normal targets.
20451   if (ConstraintVT.isFloatingPoint()) {
20452     if (Subtarget->hasSSE2())
20453       return "Y";
20454     if (Subtarget->hasSSE1())
20455       return "x";
20456   }
20457
20458   return TargetLowering::LowerXConstraint(ConstraintVT);
20459 }
20460
20461 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20462 /// vector.  If it is invalid, don't add anything to Ops.
20463 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20464                                                      std::string &Constraint,
20465                                                      std::vector<SDValue>&Ops,
20466                                                      SelectionDAG &DAG) const {
20467   SDValue Result;
20468
20469   // Only support length 1 constraints for now.
20470   if (Constraint.length() > 1) return;
20471
20472   char ConstraintLetter = Constraint[0];
20473   switch (ConstraintLetter) {
20474   default: break;
20475   case 'I':
20476     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20477       if (C->getZExtValue() <= 31) {
20478         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20479         break;
20480       }
20481     }
20482     return;
20483   case 'J':
20484     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20485       if (C->getZExtValue() <= 63) {
20486         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20487         break;
20488       }
20489     }
20490     return;
20491   case 'K':
20492     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20493       if (isInt<8>(C->getSExtValue())) {
20494         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20495         break;
20496       }
20497     }
20498     return;
20499   case 'N':
20500     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20501       if (C->getZExtValue() <= 255) {
20502         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20503         break;
20504       }
20505     }
20506     return;
20507   case 'e': {
20508     // 32-bit signed value
20509     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20510       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20511                                            C->getSExtValue())) {
20512         // Widen to 64 bits here to get it sign extended.
20513         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20514         break;
20515       }
20516     // FIXME gcc accepts some relocatable values here too, but only in certain
20517     // memory models; it's complicated.
20518     }
20519     return;
20520   }
20521   case 'Z': {
20522     // 32-bit unsigned value
20523     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20524       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20525                                            C->getZExtValue())) {
20526         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20527         break;
20528       }
20529     }
20530     // FIXME gcc accepts some relocatable values here too, but only in certain
20531     // memory models; it's complicated.
20532     return;
20533   }
20534   case 'i': {
20535     // Literal immediates are always ok.
20536     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20537       // Widen to 64 bits here to get it sign extended.
20538       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20539       break;
20540     }
20541
20542     // In any sort of PIC mode addresses need to be computed at runtime by
20543     // adding in a register or some sort of table lookup.  These can't
20544     // be used as immediates.
20545     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20546       return;
20547
20548     // If we are in non-pic codegen mode, we allow the address of a global (with
20549     // an optional displacement) to be used with 'i'.
20550     GlobalAddressSDNode *GA = nullptr;
20551     int64_t Offset = 0;
20552
20553     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20554     while (1) {
20555       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20556         Offset += GA->getOffset();
20557         break;
20558       } else if (Op.getOpcode() == ISD::ADD) {
20559         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20560           Offset += C->getZExtValue();
20561           Op = Op.getOperand(0);
20562           continue;
20563         }
20564       } else if (Op.getOpcode() == ISD::SUB) {
20565         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20566           Offset += -C->getZExtValue();
20567           Op = Op.getOperand(0);
20568           continue;
20569         }
20570       }
20571
20572       // Otherwise, this isn't something we can handle, reject it.
20573       return;
20574     }
20575
20576     const GlobalValue *GV = GA->getGlobal();
20577     // If we require an extra load to get this address, as in PIC mode, we
20578     // can't accept it.
20579     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20580                                                         getTargetMachine())))
20581       return;
20582
20583     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20584                                         GA->getValueType(0), Offset);
20585     break;
20586   }
20587   }
20588
20589   if (Result.getNode()) {
20590     Ops.push_back(Result);
20591     return;
20592   }
20593   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20594 }
20595
20596 std::pair<unsigned, const TargetRegisterClass*>
20597 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20598                                                 MVT VT) const {
20599   // First, see if this is a constraint that directly corresponds to an LLVM
20600   // register class.
20601   if (Constraint.size() == 1) {
20602     // GCC Constraint Letters
20603     switch (Constraint[0]) {
20604     default: break;
20605       // TODO: Slight differences here in allocation order and leaving
20606       // RIP in the class. Do they matter any more here than they do
20607       // in the normal allocation?
20608     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20609       if (Subtarget->is64Bit()) {
20610         if (VT == MVT::i32 || VT == MVT::f32)
20611           return std::make_pair(0U, &X86::GR32RegClass);
20612         if (VT == MVT::i16)
20613           return std::make_pair(0U, &X86::GR16RegClass);
20614         if (VT == MVT::i8 || VT == MVT::i1)
20615           return std::make_pair(0U, &X86::GR8RegClass);
20616         if (VT == MVT::i64 || VT == MVT::f64)
20617           return std::make_pair(0U, &X86::GR64RegClass);
20618         break;
20619       }
20620       // 32-bit fallthrough
20621     case 'Q':   // Q_REGS
20622       if (VT == MVT::i32 || VT == MVT::f32)
20623         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20624       if (VT == MVT::i16)
20625         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20626       if (VT == MVT::i8 || VT == MVT::i1)
20627         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20628       if (VT == MVT::i64)
20629         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20630       break;
20631     case 'r':   // GENERAL_REGS
20632     case 'l':   // INDEX_REGS
20633       if (VT == MVT::i8 || VT == MVT::i1)
20634         return std::make_pair(0U, &X86::GR8RegClass);
20635       if (VT == MVT::i16)
20636         return std::make_pair(0U, &X86::GR16RegClass);
20637       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20638         return std::make_pair(0U, &X86::GR32RegClass);
20639       return std::make_pair(0U, &X86::GR64RegClass);
20640     case 'R':   // LEGACY_REGS
20641       if (VT == MVT::i8 || VT == MVT::i1)
20642         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20643       if (VT == MVT::i16)
20644         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20645       if (VT == MVT::i32 || !Subtarget->is64Bit())
20646         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20647       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20648     case 'f':  // FP Stack registers.
20649       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20650       // value to the correct fpstack register class.
20651       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20652         return std::make_pair(0U, &X86::RFP32RegClass);
20653       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20654         return std::make_pair(0U, &X86::RFP64RegClass);
20655       return std::make_pair(0U, &X86::RFP80RegClass);
20656     case 'y':   // MMX_REGS if MMX allowed.
20657       if (!Subtarget->hasMMX()) break;
20658       return std::make_pair(0U, &X86::VR64RegClass);
20659     case 'Y':   // SSE_REGS if SSE2 allowed
20660       if (!Subtarget->hasSSE2()) break;
20661       // FALL THROUGH.
20662     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20663       if (!Subtarget->hasSSE1()) break;
20664
20665       switch (VT.SimpleTy) {
20666       default: break;
20667       // Scalar SSE types.
20668       case MVT::f32:
20669       case MVT::i32:
20670         return std::make_pair(0U, &X86::FR32RegClass);
20671       case MVT::f64:
20672       case MVT::i64:
20673         return std::make_pair(0U, &X86::FR64RegClass);
20674       // Vector types.
20675       case MVT::v16i8:
20676       case MVT::v8i16:
20677       case MVT::v4i32:
20678       case MVT::v2i64:
20679       case MVT::v4f32:
20680       case MVT::v2f64:
20681         return std::make_pair(0U, &X86::VR128RegClass);
20682       // AVX types.
20683       case MVT::v32i8:
20684       case MVT::v16i16:
20685       case MVT::v8i32:
20686       case MVT::v4i64:
20687       case MVT::v8f32:
20688       case MVT::v4f64:
20689         return std::make_pair(0U, &X86::VR256RegClass);
20690       case MVT::v8f64:
20691       case MVT::v16f32:
20692       case MVT::v16i32:
20693       case MVT::v8i64:
20694         return std::make_pair(0U, &X86::VR512RegClass);
20695       }
20696       break;
20697     }
20698   }
20699
20700   // Use the default implementation in TargetLowering to convert the register
20701   // constraint into a member of a register class.
20702   std::pair<unsigned, const TargetRegisterClass*> Res;
20703   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20704
20705   // Not found as a standard register?
20706   if (!Res.second) {
20707     // Map st(0) -> st(7) -> ST0
20708     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20709         tolower(Constraint[1]) == 's' &&
20710         tolower(Constraint[2]) == 't' &&
20711         Constraint[3] == '(' &&
20712         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20713         Constraint[5] == ')' &&
20714         Constraint[6] == '}') {
20715
20716       Res.first = X86::ST0+Constraint[4]-'0';
20717       Res.second = &X86::RFP80RegClass;
20718       return Res;
20719     }
20720
20721     // GCC allows "st(0)" to be called just plain "st".
20722     if (StringRef("{st}").equals_lower(Constraint)) {
20723       Res.first = X86::ST0;
20724       Res.second = &X86::RFP80RegClass;
20725       return Res;
20726     }
20727
20728     // flags -> EFLAGS
20729     if (StringRef("{flags}").equals_lower(Constraint)) {
20730       Res.first = X86::EFLAGS;
20731       Res.second = &X86::CCRRegClass;
20732       return Res;
20733     }
20734
20735     // 'A' means EAX + EDX.
20736     if (Constraint == "A") {
20737       Res.first = X86::EAX;
20738       Res.second = &X86::GR32_ADRegClass;
20739       return Res;
20740     }
20741     return Res;
20742   }
20743
20744   // Otherwise, check to see if this is a register class of the wrong value
20745   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20746   // turn into {ax},{dx}.
20747   if (Res.second->hasType(VT))
20748     return Res;   // Correct type already, nothing to do.
20749
20750   // All of the single-register GCC register classes map their values onto
20751   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20752   // really want an 8-bit or 32-bit register, map to the appropriate register
20753   // class and return the appropriate register.
20754   if (Res.second == &X86::GR16RegClass) {
20755     if (VT == MVT::i8 || VT == MVT::i1) {
20756       unsigned DestReg = 0;
20757       switch (Res.first) {
20758       default: break;
20759       case X86::AX: DestReg = X86::AL; break;
20760       case X86::DX: DestReg = X86::DL; break;
20761       case X86::CX: DestReg = X86::CL; break;
20762       case X86::BX: DestReg = X86::BL; break;
20763       }
20764       if (DestReg) {
20765         Res.first = DestReg;
20766         Res.second = &X86::GR8RegClass;
20767       }
20768     } else if (VT == MVT::i32 || VT == MVT::f32) {
20769       unsigned DestReg = 0;
20770       switch (Res.first) {
20771       default: break;
20772       case X86::AX: DestReg = X86::EAX; break;
20773       case X86::DX: DestReg = X86::EDX; break;
20774       case X86::CX: DestReg = X86::ECX; break;
20775       case X86::BX: DestReg = X86::EBX; break;
20776       case X86::SI: DestReg = X86::ESI; break;
20777       case X86::DI: DestReg = X86::EDI; break;
20778       case X86::BP: DestReg = X86::EBP; break;
20779       case X86::SP: DestReg = X86::ESP; break;
20780       }
20781       if (DestReg) {
20782         Res.first = DestReg;
20783         Res.second = &X86::GR32RegClass;
20784       }
20785     } else if (VT == MVT::i64 || VT == MVT::f64) {
20786       unsigned DestReg = 0;
20787       switch (Res.first) {
20788       default: break;
20789       case X86::AX: DestReg = X86::RAX; break;
20790       case X86::DX: DestReg = X86::RDX; break;
20791       case X86::CX: DestReg = X86::RCX; break;
20792       case X86::BX: DestReg = X86::RBX; break;
20793       case X86::SI: DestReg = X86::RSI; break;
20794       case X86::DI: DestReg = X86::RDI; break;
20795       case X86::BP: DestReg = X86::RBP; break;
20796       case X86::SP: DestReg = X86::RSP; break;
20797       }
20798       if (DestReg) {
20799         Res.first = DestReg;
20800         Res.second = &X86::GR64RegClass;
20801       }
20802     }
20803   } else if (Res.second == &X86::FR32RegClass ||
20804              Res.second == &X86::FR64RegClass ||
20805              Res.second == &X86::VR128RegClass ||
20806              Res.second == &X86::VR256RegClass ||
20807              Res.second == &X86::FR32XRegClass ||
20808              Res.second == &X86::FR64XRegClass ||
20809              Res.second == &X86::VR128XRegClass ||
20810              Res.second == &X86::VR256XRegClass ||
20811              Res.second == &X86::VR512RegClass) {
20812     // Handle references to XMM physical registers that got mapped into the
20813     // wrong class.  This can happen with constraints like {xmm0} where the
20814     // target independent register mapper will just pick the first match it can
20815     // find, ignoring the required type.
20816
20817     if (VT == MVT::f32 || VT == MVT::i32)
20818       Res.second = &X86::FR32RegClass;
20819     else if (VT == MVT::f64 || VT == MVT::i64)
20820       Res.second = &X86::FR64RegClass;
20821     else if (X86::VR128RegClass.hasType(VT))
20822       Res.second = &X86::VR128RegClass;
20823     else if (X86::VR256RegClass.hasType(VT))
20824       Res.second = &X86::VR256RegClass;
20825     else if (X86::VR512RegClass.hasType(VT))
20826       Res.second = &X86::VR512RegClass;
20827   }
20828
20829   return Res;
20830 }
20831
20832 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20833                                             Type *Ty) const {
20834   // Scaling factors are not free at all.
20835   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20836   // will take 2 allocations instead of 1 for plain addressing mode,
20837   // i.e. inst (reg1).
20838   if (isLegalAddressingMode(AM, Ty))
20839     // Scale represents reg2 * scale, thus account for 1
20840     // as soon as we use a second register.
20841     return AM.Scale != 0;
20842   return -1;
20843 }