Fix i128 div/mod on mingw64
[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                        makeArrayRef(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   if (Subtarget->isTargetWin64()) {
1524     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1525     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1526     setOperationAction(ISD::SREM, MVT::i128, Custom);
1527     setOperationAction(ISD::UREM, MVT::i128, Custom);
1528     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1529     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1530   }
1531
1532   // We have target-specific dag combine patterns for the following nodes:
1533   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1534   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1535   setTargetDAGCombine(ISD::VSELECT);
1536   setTargetDAGCombine(ISD::SELECT);
1537   setTargetDAGCombine(ISD::SHL);
1538   setTargetDAGCombine(ISD::SRA);
1539   setTargetDAGCombine(ISD::SRL);
1540   setTargetDAGCombine(ISD::OR);
1541   setTargetDAGCombine(ISD::AND);
1542   setTargetDAGCombine(ISD::ADD);
1543   setTargetDAGCombine(ISD::FADD);
1544   setTargetDAGCombine(ISD::FSUB);
1545   setTargetDAGCombine(ISD::FMA);
1546   setTargetDAGCombine(ISD::SUB);
1547   setTargetDAGCombine(ISD::LOAD);
1548   setTargetDAGCombine(ISD::STORE);
1549   setTargetDAGCombine(ISD::ZERO_EXTEND);
1550   setTargetDAGCombine(ISD::ANY_EXTEND);
1551   setTargetDAGCombine(ISD::SIGN_EXTEND);
1552   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1553   setTargetDAGCombine(ISD::TRUNCATE);
1554   setTargetDAGCombine(ISD::SINT_TO_FP);
1555   setTargetDAGCombine(ISD::SETCC);
1556   if (Subtarget->is64Bit())
1557     setTargetDAGCombine(ISD::MUL);
1558   setTargetDAGCombine(ISD::XOR);
1559
1560   computeRegisterProperties();
1561
1562   // On Darwin, -Os means optimize for size without hurting performance,
1563   // do not reduce the limit.
1564   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1565   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1566   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1567   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1568   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1569   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1570   setPrefLoopAlignment(4); // 2^4 bytes.
1571
1572   // Predictable cmov don't hurt on atom because it's in-order.
1573   PredictableSelectIsExpensive = !Subtarget->isAtom();
1574
1575   setPrefFunctionAlignment(4); // 2^4 bytes.
1576 }
1577
1578 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1579   if (!VT.isVector())
1580     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1581
1582   if (Subtarget->hasAVX512())
1583     switch(VT.getVectorNumElements()) {
1584     case  8: return MVT::v8i1;
1585     case 16: return MVT::v16i1;
1586   }
1587
1588   return VT.changeVectorElementTypeToInteger();
1589 }
1590
1591 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1592 /// the desired ByVal argument alignment.
1593 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1594   if (MaxAlign == 16)
1595     return;
1596   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1597     if (VTy->getBitWidth() == 128)
1598       MaxAlign = 16;
1599   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1600     unsigned EltAlign = 0;
1601     getMaxByValAlign(ATy->getElementType(), EltAlign);
1602     if (EltAlign > MaxAlign)
1603       MaxAlign = EltAlign;
1604   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1605     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1606       unsigned EltAlign = 0;
1607       getMaxByValAlign(STy->getElementType(i), EltAlign);
1608       if (EltAlign > MaxAlign)
1609         MaxAlign = EltAlign;
1610       if (MaxAlign == 16)
1611         break;
1612     }
1613   }
1614 }
1615
1616 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1617 /// function arguments in the caller parameter area. For X86, aggregates
1618 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1619 /// are at 4-byte boundaries.
1620 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1621   if (Subtarget->is64Bit()) {
1622     // Max of 8 and alignment of type.
1623     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1624     if (TyAlign > 8)
1625       return TyAlign;
1626     return 8;
1627   }
1628
1629   unsigned Align = 4;
1630   if (Subtarget->hasSSE1())
1631     getMaxByValAlign(Ty, Align);
1632   return Align;
1633 }
1634
1635 /// getOptimalMemOpType - Returns the target specific optimal type for load
1636 /// and store operations as a result of memset, memcpy, and memmove
1637 /// lowering. If DstAlign is zero that means it's safe to destination
1638 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1639 /// means there isn't a need to check it against alignment requirement,
1640 /// probably because the source does not need to be loaded. If 'IsMemset' is
1641 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1642 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1643 /// source is constant so it does not need to be loaded.
1644 /// It returns EVT::Other if the type should be determined using generic
1645 /// target-independent logic.
1646 EVT
1647 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1648                                        unsigned DstAlign, unsigned SrcAlign,
1649                                        bool IsMemset, bool ZeroMemset,
1650                                        bool MemcpyStrSrc,
1651                                        MachineFunction &MF) const {
1652   const Function *F = MF.getFunction();
1653   if ((!IsMemset || ZeroMemset) &&
1654       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1655                                        Attribute::NoImplicitFloat)) {
1656     if (Size >= 16 &&
1657         (Subtarget->isUnalignedMemAccessFast() ||
1658          ((DstAlign == 0 || DstAlign >= 16) &&
1659           (SrcAlign == 0 || SrcAlign >= 16)))) {
1660       if (Size >= 32) {
1661         if (Subtarget->hasInt256())
1662           return MVT::v8i32;
1663         if (Subtarget->hasFp256())
1664           return MVT::v8f32;
1665       }
1666       if (Subtarget->hasSSE2())
1667         return MVT::v4i32;
1668       if (Subtarget->hasSSE1())
1669         return MVT::v4f32;
1670     } else if (!MemcpyStrSrc && Size >= 8 &&
1671                !Subtarget->is64Bit() &&
1672                Subtarget->hasSSE2()) {
1673       // Do not use f64 to lower memcpy if source is string constant. It's
1674       // better to use i32 to avoid the loads.
1675       return MVT::f64;
1676     }
1677   }
1678   if (Subtarget->is64Bit() && Size >= 8)
1679     return MVT::i64;
1680   return MVT::i32;
1681 }
1682
1683 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1684   if (VT == MVT::f32)
1685     return X86ScalarSSEf32;
1686   else if (VT == MVT::f64)
1687     return X86ScalarSSEf64;
1688   return true;
1689 }
1690
1691 bool
1692 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1693                                                  unsigned,
1694                                                  bool *Fast) const {
1695   if (Fast)
1696     *Fast = Subtarget->isUnalignedMemAccessFast();
1697   return true;
1698 }
1699
1700 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1701 /// current function.  The returned value is a member of the
1702 /// MachineJumpTableInfo::JTEntryKind enum.
1703 unsigned X86TargetLowering::getJumpTableEncoding() const {
1704   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1705   // symbol.
1706   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1707       Subtarget->isPICStyleGOT())
1708     return MachineJumpTableInfo::EK_Custom32;
1709
1710   // Otherwise, use the normal jump table encoding heuristics.
1711   return TargetLowering::getJumpTableEncoding();
1712 }
1713
1714 const MCExpr *
1715 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1716                                              const MachineBasicBlock *MBB,
1717                                              unsigned uid,MCContext &Ctx) const{
1718   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1719          Subtarget->isPICStyleGOT());
1720   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1721   // entries.
1722   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1723                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1724 }
1725
1726 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1727 /// jumptable.
1728 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1729                                                     SelectionDAG &DAG) const {
1730   if (!Subtarget->is64Bit())
1731     // This doesn't have SDLoc associated with it, but is not really the
1732     // same as a Register.
1733     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1734   return Table;
1735 }
1736
1737 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1738 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1739 /// MCExpr.
1740 const MCExpr *X86TargetLowering::
1741 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1742                              MCContext &Ctx) const {
1743   // X86-64 uses RIP relative addressing based on the jump table label.
1744   if (Subtarget->isPICStyleRIPRel())
1745     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1746
1747   // Otherwise, the reference is relative to the PIC base.
1748   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1749 }
1750
1751 // FIXME: Why this routine is here? Move to RegInfo!
1752 std::pair<const TargetRegisterClass*, uint8_t>
1753 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1754   const TargetRegisterClass *RRC = nullptr;
1755   uint8_t Cost = 1;
1756   switch (VT.SimpleTy) {
1757   default:
1758     return TargetLowering::findRepresentativeClass(VT);
1759   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1760     RRC = Subtarget->is64Bit() ?
1761       (const TargetRegisterClass*)&X86::GR64RegClass :
1762       (const TargetRegisterClass*)&X86::GR32RegClass;
1763     break;
1764   case MVT::x86mmx:
1765     RRC = &X86::VR64RegClass;
1766     break;
1767   case MVT::f32: case MVT::f64:
1768   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1769   case MVT::v4f32: case MVT::v2f64:
1770   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1771   case MVT::v4f64:
1772     RRC = &X86::VR128RegClass;
1773     break;
1774   }
1775   return std::make_pair(RRC, Cost);
1776 }
1777
1778 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1779                                                unsigned &Offset) const {
1780   if (!Subtarget->isTargetLinux())
1781     return false;
1782
1783   if (Subtarget->is64Bit()) {
1784     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1785     Offset = 0x28;
1786     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1787       AddressSpace = 256;
1788     else
1789       AddressSpace = 257;
1790   } else {
1791     // %gs:0x14 on i386
1792     Offset = 0x14;
1793     AddressSpace = 256;
1794   }
1795   return true;
1796 }
1797
1798 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1799                                             unsigned DestAS) const {
1800   assert(SrcAS != DestAS && "Expected different address spaces!");
1801
1802   return SrcAS < 256 && DestAS < 256;
1803 }
1804
1805 //===----------------------------------------------------------------------===//
1806 //               Return Value Calling Convention Implementation
1807 //===----------------------------------------------------------------------===//
1808
1809 #include "X86GenCallingConv.inc"
1810
1811 bool
1812 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1813                                   MachineFunction &MF, bool isVarArg,
1814                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1815                         LLVMContext &Context) const {
1816   SmallVector<CCValAssign, 16> RVLocs;
1817   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1818                  RVLocs, Context);
1819   return CCInfo.CheckReturn(Outs, RetCC_X86);
1820 }
1821
1822 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1823   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1824   return ScratchRegs;
1825 }
1826
1827 SDValue
1828 X86TargetLowering::LowerReturn(SDValue Chain,
1829                                CallingConv::ID CallConv, bool isVarArg,
1830                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1831                                const SmallVectorImpl<SDValue> &OutVals,
1832                                SDLoc dl, SelectionDAG &DAG) const {
1833   MachineFunction &MF = DAG.getMachineFunction();
1834   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1835
1836   SmallVector<CCValAssign, 16> RVLocs;
1837   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1838                  RVLocs, *DAG.getContext());
1839   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1840
1841   SDValue Flag;
1842   SmallVector<SDValue, 6> RetOps;
1843   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1844   // Operand #1 = Bytes To Pop
1845   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1846                    MVT::i16));
1847
1848   // Copy the result values into the output registers.
1849   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1850     CCValAssign &VA = RVLocs[i];
1851     assert(VA.isRegLoc() && "Can only return in registers!");
1852     SDValue ValToCopy = OutVals[i];
1853     EVT ValVT = ValToCopy.getValueType();
1854
1855     // Promote values to the appropriate types
1856     if (VA.getLocInfo() == CCValAssign::SExt)
1857       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1858     else if (VA.getLocInfo() == CCValAssign::ZExt)
1859       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1860     else if (VA.getLocInfo() == CCValAssign::AExt)
1861       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1862     else if (VA.getLocInfo() == CCValAssign::BCvt)
1863       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1864
1865     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1866            "Unexpected FP-extend for return value.");  
1867
1868     // If this is x86-64, and we disabled SSE, we can't return FP values,
1869     // or SSE or MMX vectors.
1870     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1871          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1872           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1873       report_fatal_error("SSE register return with SSE disabled");
1874     }
1875     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1876     // llvm-gcc has never done it right and no one has noticed, so this
1877     // should be OK for now.
1878     if (ValVT == MVT::f64 &&
1879         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1880       report_fatal_error("SSE2 register return with SSE2 disabled");
1881
1882     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1883     // the RET instruction and handled by the FP Stackifier.
1884     if (VA.getLocReg() == X86::ST0 ||
1885         VA.getLocReg() == X86::ST1) {
1886       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1887       // change the value to the FP stack register class.
1888       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1889         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1890       RetOps.push_back(ValToCopy);
1891       // Don't emit a copytoreg.
1892       continue;
1893     }
1894
1895     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1896     // which is returned in RAX / RDX.
1897     if (Subtarget->is64Bit()) {
1898       if (ValVT == MVT::x86mmx) {
1899         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1900           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1901           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1902                                   ValToCopy);
1903           // If we don't have SSE2 available, convert to v4f32 so the generated
1904           // register is legal.
1905           if (!Subtarget->hasSSE2())
1906             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1907         }
1908       }
1909     }
1910
1911     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1912     Flag = Chain.getValue(1);
1913     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1914   }
1915
1916   // The x86-64 ABIs require that for returning structs by value we copy
1917   // the sret argument into %rax/%eax (depending on ABI) for the return.
1918   // Win32 requires us to put the sret argument to %eax as well.
1919   // We saved the argument into a virtual register in the entry block,
1920   // so now we copy the value out and into %rax/%eax.
1921   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1922       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1923     MachineFunction &MF = DAG.getMachineFunction();
1924     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1925     unsigned Reg = FuncInfo->getSRetReturnReg();
1926     assert(Reg &&
1927            "SRetReturnReg should have been set in LowerFormalArguments().");
1928     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1929
1930     unsigned RetValReg
1931         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1932           X86::RAX : X86::EAX;
1933     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1934     Flag = Chain.getValue(1);
1935
1936     // RAX/EAX now acts like a return value.
1937     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1938   }
1939
1940   RetOps[0] = Chain;  // Update chain.
1941
1942   // Add the flag if we have it.
1943   if (Flag.getNode())
1944     RetOps.push_back(Flag);
1945
1946   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1947 }
1948
1949 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1950   if (N->getNumValues() != 1)
1951     return false;
1952   if (!N->hasNUsesOfValue(1, 0))
1953     return false;
1954
1955   SDValue TCChain = Chain;
1956   SDNode *Copy = *N->use_begin();
1957   if (Copy->getOpcode() == ISD::CopyToReg) {
1958     // If the copy has a glue operand, we conservatively assume it isn't safe to
1959     // perform a tail call.
1960     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1961       return false;
1962     TCChain = Copy->getOperand(0);
1963   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1964     return false;
1965
1966   bool HasRet = false;
1967   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1968        UI != UE; ++UI) {
1969     if (UI->getOpcode() != X86ISD::RET_FLAG)
1970       return false;
1971     HasRet = true;
1972   }
1973
1974   if (!HasRet)
1975     return false;
1976
1977   Chain = TCChain;
1978   return true;
1979 }
1980
1981 MVT
1982 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1983                                             ISD::NodeType ExtendKind) const {
1984   MVT ReturnMVT;
1985   // TODO: Is this also valid on 32-bit?
1986   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1987     ReturnMVT = MVT::i8;
1988   else
1989     ReturnMVT = MVT::i32;
1990
1991   MVT MinVT = getRegisterType(ReturnMVT);
1992   return VT.bitsLT(MinVT) ? MinVT : VT;
1993 }
1994
1995 /// LowerCallResult - Lower the result values of a call into the
1996 /// appropriate copies out of appropriate physical registers.
1997 ///
1998 SDValue
1999 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2000                                    CallingConv::ID CallConv, bool isVarArg,
2001                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2002                                    SDLoc dl, SelectionDAG &DAG,
2003                                    SmallVectorImpl<SDValue> &InVals) const {
2004
2005   // Assign locations to each value returned by this call.
2006   SmallVector<CCValAssign, 16> RVLocs;
2007   bool Is64Bit = Subtarget->is64Bit();
2008   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2009                  getTargetMachine(), RVLocs, *DAG.getContext());
2010   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2011
2012   // Copy all of the result registers out of their specified physreg.
2013   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2014     CCValAssign &VA = RVLocs[i];
2015     EVT CopyVT = VA.getValVT();
2016
2017     // If this is x86-64, and we disabled SSE, we can't return FP values
2018     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2019         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2020       report_fatal_error("SSE register return with SSE disabled");
2021     }
2022
2023     SDValue Val;
2024
2025     // If this is a call to a function that returns an fp value on the floating
2026     // point stack, we must guarantee the value is popped from the stack, so
2027     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2028     // if the return value is not used. We use the FpPOP_RETVAL instruction
2029     // instead.
2030     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2031       // If we prefer to use the value in xmm registers, copy it out as f80 and
2032       // use a truncate to move it from fp stack reg to xmm reg.
2033       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2034       SDValue Ops[] = { Chain, InFlag };
2035       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2036                                          MVT::Other, MVT::Glue, Ops), 1);
2037       Val = Chain.getValue(0);
2038
2039       // Round the f80 to the right size, which also moves it to the appropriate
2040       // xmm register.
2041       if (CopyVT != VA.getValVT())
2042         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2043                           // This truncation won't change the value.
2044                           DAG.getIntPtrConstant(1));
2045     } else {
2046       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2047                                  CopyVT, InFlag).getValue(1);
2048       Val = Chain.getValue(0);
2049     }
2050     InFlag = Chain.getValue(2);
2051     InVals.push_back(Val);
2052   }
2053
2054   return Chain;
2055 }
2056
2057 //===----------------------------------------------------------------------===//
2058 //                C & StdCall & Fast Calling Convention implementation
2059 //===----------------------------------------------------------------------===//
2060 //  StdCall calling convention seems to be standard for many Windows' API
2061 //  routines and around. It differs from C calling convention just a little:
2062 //  callee should clean up the stack, not caller. Symbols should be also
2063 //  decorated in some fancy way :) It doesn't support any vector arguments.
2064 //  For info on fast calling convention see Fast Calling Convention (tail call)
2065 //  implementation LowerX86_32FastCCCallTo.
2066
2067 /// CallIsStructReturn - Determines whether a call uses struct return
2068 /// semantics.
2069 enum StructReturnType {
2070   NotStructReturn,
2071   RegStructReturn,
2072   StackStructReturn
2073 };
2074 static StructReturnType
2075 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2076   if (Outs.empty())
2077     return NotStructReturn;
2078
2079   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2080   if (!Flags.isSRet())
2081     return NotStructReturn;
2082   if (Flags.isInReg())
2083     return RegStructReturn;
2084   return StackStructReturn;
2085 }
2086
2087 /// ArgsAreStructReturn - Determines whether a function uses struct
2088 /// return semantics.
2089 static StructReturnType
2090 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2091   if (Ins.empty())
2092     return NotStructReturn;
2093
2094   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2095   if (!Flags.isSRet())
2096     return NotStructReturn;
2097   if (Flags.isInReg())
2098     return RegStructReturn;
2099   return StackStructReturn;
2100 }
2101
2102 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2103 /// by "Src" to address "Dst" with size and alignment information specified by
2104 /// the specific parameter attribute. The copy will be passed as a byval
2105 /// function parameter.
2106 static SDValue
2107 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2108                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2109                           SDLoc dl) {
2110   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2111
2112   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2113                        /*isVolatile*/false, /*AlwaysInline=*/true,
2114                        MachinePointerInfo(), MachinePointerInfo());
2115 }
2116
2117 /// IsTailCallConvention - Return true if the calling convention is one that
2118 /// supports tail call optimization.
2119 static bool IsTailCallConvention(CallingConv::ID CC) {
2120   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2121           CC == CallingConv::HiPE);
2122 }
2123
2124 /// \brief Return true if the calling convention is a C calling convention.
2125 static bool IsCCallConvention(CallingConv::ID CC) {
2126   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2127           CC == CallingConv::X86_64_SysV);
2128 }
2129
2130 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2131   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2132     return false;
2133
2134   CallSite CS(CI);
2135   CallingConv::ID CalleeCC = CS.getCallingConv();
2136   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2137     return false;
2138
2139   return true;
2140 }
2141
2142 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2143 /// a tailcall target by changing its ABI.
2144 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2145                                    bool GuaranteedTailCallOpt) {
2146   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2147 }
2148
2149 SDValue
2150 X86TargetLowering::LowerMemArgument(SDValue Chain,
2151                                     CallingConv::ID CallConv,
2152                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2153                                     SDLoc dl, SelectionDAG &DAG,
2154                                     const CCValAssign &VA,
2155                                     MachineFrameInfo *MFI,
2156                                     unsigned i) const {
2157   // Create the nodes corresponding to a load from this parameter slot.
2158   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2159   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2160                               getTargetMachine().Options.GuaranteedTailCallOpt);
2161   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2162   EVT ValVT;
2163
2164   // If value is passed by pointer we have address passed instead of the value
2165   // itself.
2166   if (VA.getLocInfo() == CCValAssign::Indirect)
2167     ValVT = VA.getLocVT();
2168   else
2169     ValVT = VA.getValVT();
2170
2171   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2172   // changed with more analysis.
2173   // In case of tail call optimization mark all arguments mutable. Since they
2174   // could be overwritten by lowering of arguments in case of a tail call.
2175   if (Flags.isByVal()) {
2176     unsigned Bytes = Flags.getByValSize();
2177     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2178     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2179     return DAG.getFrameIndex(FI, getPointerTy());
2180   } else {
2181     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2182                                     VA.getLocMemOffset(), isImmutable);
2183     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2184     return DAG.getLoad(ValVT, dl, Chain, FIN,
2185                        MachinePointerInfo::getFixedStack(FI),
2186                        false, false, false, 0);
2187   }
2188 }
2189
2190 SDValue
2191 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2192                                         CallingConv::ID CallConv,
2193                                         bool isVarArg,
2194                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2195                                         SDLoc dl,
2196                                         SelectionDAG &DAG,
2197                                         SmallVectorImpl<SDValue> &InVals)
2198                                           const {
2199   MachineFunction &MF = DAG.getMachineFunction();
2200   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2201
2202   const Function* Fn = MF.getFunction();
2203   if (Fn->hasExternalLinkage() &&
2204       Subtarget->isTargetCygMing() &&
2205       Fn->getName() == "main")
2206     FuncInfo->setForceFramePointer(true);
2207
2208   MachineFrameInfo *MFI = MF.getFrameInfo();
2209   bool Is64Bit = Subtarget->is64Bit();
2210   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2211
2212   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2213          "Var args not supported with calling convention fastcc, ghc or hipe");
2214
2215   // Assign locations to all of the incoming arguments.
2216   SmallVector<CCValAssign, 16> ArgLocs;
2217   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2218                  ArgLocs, *DAG.getContext());
2219
2220   // Allocate shadow area for Win64
2221   if (IsWin64)
2222     CCInfo.AllocateStack(32, 8);
2223
2224   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2225
2226   unsigned LastVal = ~0U;
2227   SDValue ArgValue;
2228   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2229     CCValAssign &VA = ArgLocs[i];
2230     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2231     // places.
2232     assert(VA.getValNo() != LastVal &&
2233            "Don't support value assigned to multiple locs yet");
2234     (void)LastVal;
2235     LastVal = VA.getValNo();
2236
2237     if (VA.isRegLoc()) {
2238       EVT RegVT = VA.getLocVT();
2239       const TargetRegisterClass *RC;
2240       if (RegVT == MVT::i32)
2241         RC = &X86::GR32RegClass;
2242       else if (Is64Bit && RegVT == MVT::i64)
2243         RC = &X86::GR64RegClass;
2244       else if (RegVT == MVT::f32)
2245         RC = &X86::FR32RegClass;
2246       else if (RegVT == MVT::f64)
2247         RC = &X86::FR64RegClass;
2248       else if (RegVT.is512BitVector())
2249         RC = &X86::VR512RegClass;
2250       else if (RegVT.is256BitVector())
2251         RC = &X86::VR256RegClass;
2252       else if (RegVT.is128BitVector())
2253         RC = &X86::VR128RegClass;
2254       else if (RegVT == MVT::x86mmx)
2255         RC = &X86::VR64RegClass;
2256       else if (RegVT == MVT::i1)
2257         RC = &X86::VK1RegClass;
2258       else if (RegVT == MVT::v8i1)
2259         RC = &X86::VK8RegClass;
2260       else if (RegVT == MVT::v16i1)
2261         RC = &X86::VK16RegClass;
2262       else
2263         llvm_unreachable("Unknown argument type!");
2264
2265       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2266       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2267
2268       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2269       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2270       // right size.
2271       if (VA.getLocInfo() == CCValAssign::SExt)
2272         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2273                                DAG.getValueType(VA.getValVT()));
2274       else if (VA.getLocInfo() == CCValAssign::ZExt)
2275         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2276                                DAG.getValueType(VA.getValVT()));
2277       else if (VA.getLocInfo() == CCValAssign::BCvt)
2278         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2279
2280       if (VA.isExtInLoc()) {
2281         // Handle MMX values passed in XMM regs.
2282         if (RegVT.isVector())
2283           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2284         else
2285           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2286       }
2287     } else {
2288       assert(VA.isMemLoc());
2289       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2290     }
2291
2292     // If value is passed via pointer - do a load.
2293     if (VA.getLocInfo() == CCValAssign::Indirect)
2294       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2295                              MachinePointerInfo(), false, false, false, 0);
2296
2297     InVals.push_back(ArgValue);
2298   }
2299
2300   // The x86-64 ABIs require that for returning structs by value we copy
2301   // the sret argument into %rax/%eax (depending on ABI) for the return.
2302   // Win32 requires us to put the sret argument to %eax as well.
2303   // Save the argument into a virtual register so that we can access it
2304   // from the return points.
2305   if (MF.getFunction()->hasStructRetAttr() &&
2306       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2307     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2308     unsigned Reg = FuncInfo->getSRetReturnReg();
2309     if (!Reg) {
2310       MVT PtrTy = getPointerTy();
2311       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2312       FuncInfo->setSRetReturnReg(Reg);
2313     }
2314     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2315     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2316   }
2317
2318   unsigned StackSize = CCInfo.getNextStackOffset();
2319   // Align stack specially for tail calls.
2320   if (FuncIsMadeTailCallSafe(CallConv,
2321                              MF.getTarget().Options.GuaranteedTailCallOpt))
2322     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2323
2324   // If the function takes variable number of arguments, make a frame index for
2325   // the start of the first vararg value... for expansion of llvm.va_start.
2326   if (isVarArg) {
2327     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2328                     CallConv != CallingConv::X86_ThisCall)) {
2329       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2330     }
2331     if (Is64Bit) {
2332       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2333
2334       // FIXME: We should really autogenerate these arrays
2335       static const MCPhysReg GPR64ArgRegsWin64[] = {
2336         X86::RCX, X86::RDX, X86::R8,  X86::R9
2337       };
2338       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2339         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2340       };
2341       static const MCPhysReg XMMArgRegs64Bit[] = {
2342         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2343         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2344       };
2345       const MCPhysReg *GPR64ArgRegs;
2346       unsigned NumXMMRegs = 0;
2347
2348       if (IsWin64) {
2349         // The XMM registers which might contain var arg parameters are shadowed
2350         // in their paired GPR.  So we only need to save the GPR to their home
2351         // slots.
2352         TotalNumIntRegs = 4;
2353         GPR64ArgRegs = GPR64ArgRegsWin64;
2354       } else {
2355         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2356         GPR64ArgRegs = GPR64ArgRegs64Bit;
2357
2358         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2359                                                 TotalNumXMMRegs);
2360       }
2361       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2362                                                        TotalNumIntRegs);
2363
2364       bool NoImplicitFloatOps = Fn->getAttributes().
2365         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2366       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2367              "SSE register cannot be used when SSE is disabled!");
2368       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2369                NoImplicitFloatOps) &&
2370              "SSE register cannot be used when SSE is disabled!");
2371       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2372           !Subtarget->hasSSE1())
2373         // Kernel mode asks for SSE to be disabled, so don't push them
2374         // on the stack.
2375         TotalNumXMMRegs = 0;
2376
2377       if (IsWin64) {
2378         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2379         // Get to the caller-allocated home save location.  Add 8 to account
2380         // for the return address.
2381         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2382         FuncInfo->setRegSaveFrameIndex(
2383           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2384         // Fixup to set vararg frame on shadow area (4 x i64).
2385         if (NumIntRegs < 4)
2386           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2387       } else {
2388         // For X86-64, if there are vararg parameters that are passed via
2389         // registers, then we must store them to their spots on the stack so
2390         // they may be loaded by deferencing the result of va_next.
2391         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2392         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2393         FuncInfo->setRegSaveFrameIndex(
2394           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2395                                false));
2396       }
2397
2398       // Store the integer parameter registers.
2399       SmallVector<SDValue, 8> MemOps;
2400       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2401                                         getPointerTy());
2402       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2403       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2404         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2405                                   DAG.getIntPtrConstant(Offset));
2406         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2407                                      &X86::GR64RegClass);
2408         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2409         SDValue Store =
2410           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2411                        MachinePointerInfo::getFixedStack(
2412                          FuncInfo->getRegSaveFrameIndex(), Offset),
2413                        false, false, 0);
2414         MemOps.push_back(Store);
2415         Offset += 8;
2416       }
2417
2418       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2419         // Now store the XMM (fp + vector) parameter registers.
2420         SmallVector<SDValue, 11> SaveXMMOps;
2421         SaveXMMOps.push_back(Chain);
2422
2423         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2424         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2425         SaveXMMOps.push_back(ALVal);
2426
2427         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2428                                FuncInfo->getRegSaveFrameIndex()));
2429         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2430                                FuncInfo->getVarArgsFPOffset()));
2431
2432         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2433           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2434                                        &X86::VR128RegClass);
2435           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2436           SaveXMMOps.push_back(Val);
2437         }
2438         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2439                                      MVT::Other, SaveXMMOps));
2440       }
2441
2442       if (!MemOps.empty())
2443         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2444     }
2445   }
2446
2447   // Some CCs need callee pop.
2448   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2449                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2450     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2451   } else {
2452     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2453     // If this is an sret function, the return should pop the hidden pointer.
2454     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2455         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2456         argsAreStructReturn(Ins) == StackStructReturn)
2457       FuncInfo->setBytesToPopOnReturn(4);
2458   }
2459
2460   if (!Is64Bit) {
2461     // RegSaveFrameIndex is X86-64 only.
2462     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2463     if (CallConv == CallingConv::X86_FastCall ||
2464         CallConv == CallingConv::X86_ThisCall)
2465       // fastcc functions can't have varargs.
2466       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2467   }
2468
2469   FuncInfo->setArgumentStackSize(StackSize);
2470
2471   return Chain;
2472 }
2473
2474 SDValue
2475 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2476                                     SDValue StackPtr, SDValue Arg,
2477                                     SDLoc dl, SelectionDAG &DAG,
2478                                     const CCValAssign &VA,
2479                                     ISD::ArgFlagsTy Flags) const {
2480   unsigned LocMemOffset = VA.getLocMemOffset();
2481   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2482   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2483   if (Flags.isByVal())
2484     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2485
2486   return DAG.getStore(Chain, dl, Arg, PtrOff,
2487                       MachinePointerInfo::getStack(LocMemOffset),
2488                       false, false, 0);
2489 }
2490
2491 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2492 /// optimization is performed and it is required.
2493 SDValue
2494 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2495                                            SDValue &OutRetAddr, SDValue Chain,
2496                                            bool IsTailCall, bool Is64Bit,
2497                                            int FPDiff, SDLoc dl) const {
2498   // Adjust the Return address stack slot.
2499   EVT VT = getPointerTy();
2500   OutRetAddr = getReturnAddressFrameIndex(DAG);
2501
2502   // Load the "old" Return address.
2503   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2504                            false, false, false, 0);
2505   return SDValue(OutRetAddr.getNode(), 1);
2506 }
2507
2508 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2509 /// optimization is performed and it is required (FPDiff!=0).
2510 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2511                                         SDValue Chain, SDValue RetAddrFrIdx,
2512                                         EVT PtrVT, unsigned SlotSize,
2513                                         int FPDiff, SDLoc dl) {
2514   // Store the return address to the appropriate stack slot.
2515   if (!FPDiff) return Chain;
2516   // Calculate the new stack slot for the return address.
2517   int NewReturnAddrFI =
2518     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2519                                          false);
2520   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2521   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2522                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2523                        false, false, 0);
2524   return Chain;
2525 }
2526
2527 SDValue
2528 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2529                              SmallVectorImpl<SDValue> &InVals) const {
2530   SelectionDAG &DAG                     = CLI.DAG;
2531   SDLoc &dl                             = CLI.DL;
2532   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2533   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2534   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2535   SDValue Chain                         = CLI.Chain;
2536   SDValue Callee                        = CLI.Callee;
2537   CallingConv::ID CallConv              = CLI.CallConv;
2538   bool &isTailCall                      = CLI.IsTailCall;
2539   bool isVarArg                         = CLI.IsVarArg;
2540
2541   MachineFunction &MF = DAG.getMachineFunction();
2542   bool Is64Bit        = Subtarget->is64Bit();
2543   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2544   StructReturnType SR = callIsStructReturn(Outs);
2545   bool IsSibcall      = false;
2546
2547   if (MF.getTarget().Options.DisableTailCalls)
2548     isTailCall = false;
2549
2550   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2551   if (IsMustTail) {
2552     // Force this to be a tail call.  The verifier rules are enough to ensure
2553     // that we can lower this successfully without moving the return address
2554     // around.
2555     isTailCall = true;
2556   } else if (isTailCall) {
2557     // Check if it's really possible to do a tail call.
2558     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2559                     isVarArg, SR != NotStructReturn,
2560                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2561                     Outs, OutVals, Ins, DAG);
2562
2563     // Sibcalls are automatically detected tailcalls which do not require
2564     // ABI changes.
2565     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2566       IsSibcall = true;
2567
2568     if (isTailCall)
2569       ++NumTailCalls;
2570   }
2571
2572   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2573          "Var args not supported with calling convention fastcc, ghc or hipe");
2574
2575   // Analyze operands of the call, assigning locations to each operand.
2576   SmallVector<CCValAssign, 16> ArgLocs;
2577   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2578                  ArgLocs, *DAG.getContext());
2579
2580   // Allocate shadow area for Win64
2581   if (IsWin64)
2582     CCInfo.AllocateStack(32, 8);
2583
2584   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2585
2586   // Get a count of how many bytes are to be pushed on the stack.
2587   unsigned NumBytes = CCInfo.getNextStackOffset();
2588   if (IsSibcall)
2589     // This is a sibcall. The memory operands are available in caller's
2590     // own caller's stack.
2591     NumBytes = 0;
2592   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2593            IsTailCallConvention(CallConv))
2594     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2595
2596   int FPDiff = 0;
2597   if (isTailCall && !IsSibcall && !IsMustTail) {
2598     // Lower arguments at fp - stackoffset + fpdiff.
2599     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2600     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2601
2602     FPDiff = NumBytesCallerPushed - NumBytes;
2603
2604     // Set the delta of movement of the returnaddr stackslot.
2605     // But only set if delta is greater than previous delta.
2606     if (FPDiff < X86Info->getTCReturnAddrDelta())
2607       X86Info->setTCReturnAddrDelta(FPDiff);
2608   }
2609
2610   unsigned NumBytesToPush = NumBytes;
2611   unsigned NumBytesToPop = NumBytes;
2612
2613   // If we have an inalloca argument, all stack space has already been allocated
2614   // for us and be right at the top of the stack.  We don't support multiple
2615   // arguments passed in memory when using inalloca.
2616   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2617     NumBytesToPush = 0;
2618     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2619            "an inalloca argument must be the only memory argument");
2620   }
2621
2622   if (!IsSibcall)
2623     Chain = DAG.getCALLSEQ_START(
2624         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2625
2626   SDValue RetAddrFrIdx;
2627   // Load return address for tail calls.
2628   if (isTailCall && FPDiff)
2629     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2630                                     Is64Bit, FPDiff, dl);
2631
2632   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2633   SmallVector<SDValue, 8> MemOpChains;
2634   SDValue StackPtr;
2635
2636   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2637   // of tail call optimization arguments are handle later.
2638   const X86RegisterInfo *RegInfo =
2639     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2640   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2641     // Skip inalloca arguments, they have already been written.
2642     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2643     if (Flags.isInAlloca())
2644       continue;
2645
2646     CCValAssign &VA = ArgLocs[i];
2647     EVT RegVT = VA.getLocVT();
2648     SDValue Arg = OutVals[i];
2649     bool isByVal = Flags.isByVal();
2650
2651     // Promote the value if needed.
2652     switch (VA.getLocInfo()) {
2653     default: llvm_unreachable("Unknown loc info!");
2654     case CCValAssign::Full: break;
2655     case CCValAssign::SExt:
2656       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2657       break;
2658     case CCValAssign::ZExt:
2659       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2660       break;
2661     case CCValAssign::AExt:
2662       if (RegVT.is128BitVector()) {
2663         // Special case: passing MMX values in XMM registers.
2664         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2665         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2666         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2667       } else
2668         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2669       break;
2670     case CCValAssign::BCvt:
2671       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2672       break;
2673     case CCValAssign::Indirect: {
2674       // Store the argument.
2675       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2676       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2677       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2678                            MachinePointerInfo::getFixedStack(FI),
2679                            false, false, 0);
2680       Arg = SpillSlot;
2681       break;
2682     }
2683     }
2684
2685     if (VA.isRegLoc()) {
2686       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2687       if (isVarArg && IsWin64) {
2688         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2689         // shadow reg if callee is a varargs function.
2690         unsigned ShadowReg = 0;
2691         switch (VA.getLocReg()) {
2692         case X86::XMM0: ShadowReg = X86::RCX; break;
2693         case X86::XMM1: ShadowReg = X86::RDX; break;
2694         case X86::XMM2: ShadowReg = X86::R8; break;
2695         case X86::XMM3: ShadowReg = X86::R9; break;
2696         }
2697         if (ShadowReg)
2698           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2699       }
2700     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2701       assert(VA.isMemLoc());
2702       if (!StackPtr.getNode())
2703         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2704                                       getPointerTy());
2705       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2706                                              dl, DAG, VA, Flags));
2707     }
2708   }
2709
2710   if (!MemOpChains.empty())
2711     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2712
2713   if (Subtarget->isPICStyleGOT()) {
2714     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2715     // GOT pointer.
2716     if (!isTailCall) {
2717       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2718                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2719     } else {
2720       // If we are tail calling and generating PIC/GOT style code load the
2721       // address of the callee into ECX. The value in ecx is used as target of
2722       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2723       // for tail calls on PIC/GOT architectures. Normally we would just put the
2724       // address of GOT into ebx and then call target@PLT. But for tail calls
2725       // ebx would be restored (since ebx is callee saved) before jumping to the
2726       // target@PLT.
2727
2728       // Note: The actual moving to ECX is done further down.
2729       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2730       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2731           !G->getGlobal()->hasProtectedVisibility())
2732         Callee = LowerGlobalAddress(Callee, DAG);
2733       else if (isa<ExternalSymbolSDNode>(Callee))
2734         Callee = LowerExternalSymbol(Callee, DAG);
2735     }
2736   }
2737
2738   if (Is64Bit && isVarArg && !IsWin64) {
2739     // From AMD64 ABI document:
2740     // For calls that may call functions that use varargs or stdargs
2741     // (prototype-less calls or calls to functions containing ellipsis (...) in
2742     // the declaration) %al is used as hidden argument to specify the number
2743     // of SSE registers used. The contents of %al do not need to match exactly
2744     // the number of registers, but must be an ubound on the number of SSE
2745     // registers used and is in the range 0 - 8 inclusive.
2746
2747     // Count the number of XMM registers allocated.
2748     static const MCPhysReg XMMArgRegs[] = {
2749       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2750       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2751     };
2752     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2753     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2754            && "SSE registers cannot be used when SSE is disabled");
2755
2756     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2757                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2758   }
2759
2760   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2761   // don't need this because the eligibility check rejects calls that require
2762   // shuffling arguments passed in memory.
2763   if (!IsSibcall && isTailCall) {
2764     // Force all the incoming stack arguments to be loaded from the stack
2765     // before any new outgoing arguments are stored to the stack, because the
2766     // outgoing stack slots may alias the incoming argument stack slots, and
2767     // the alias isn't otherwise explicit. This is slightly more conservative
2768     // than necessary, because it means that each store effectively depends
2769     // on every argument instead of just those arguments it would clobber.
2770     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2771
2772     SmallVector<SDValue, 8> MemOpChains2;
2773     SDValue FIN;
2774     int FI = 0;
2775     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2776       CCValAssign &VA = ArgLocs[i];
2777       if (VA.isRegLoc())
2778         continue;
2779       assert(VA.isMemLoc());
2780       SDValue Arg = OutVals[i];
2781       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2782       // Skip inalloca arguments.  They don't require any work.
2783       if (Flags.isInAlloca())
2784         continue;
2785       // Create frame index.
2786       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2787       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2788       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2789       FIN = DAG.getFrameIndex(FI, getPointerTy());
2790
2791       if (Flags.isByVal()) {
2792         // Copy relative to framepointer.
2793         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2794         if (!StackPtr.getNode())
2795           StackPtr = DAG.getCopyFromReg(Chain, dl,
2796                                         RegInfo->getStackRegister(),
2797                                         getPointerTy());
2798         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2799
2800         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2801                                                          ArgChain,
2802                                                          Flags, DAG, dl));
2803       } else {
2804         // Store relative to framepointer.
2805         MemOpChains2.push_back(
2806           DAG.getStore(ArgChain, dl, Arg, FIN,
2807                        MachinePointerInfo::getFixedStack(FI),
2808                        false, false, 0));
2809       }
2810     }
2811
2812     if (!MemOpChains2.empty())
2813       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2814
2815     // Store the return address to the appropriate stack slot.
2816     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2817                                      getPointerTy(), RegInfo->getSlotSize(),
2818                                      FPDiff, dl);
2819   }
2820
2821   // Build a sequence of copy-to-reg nodes chained together with token chain
2822   // and flag operands which copy the outgoing args into registers.
2823   SDValue InFlag;
2824   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2825     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2826                              RegsToPass[i].second, InFlag);
2827     InFlag = Chain.getValue(1);
2828   }
2829
2830   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2831     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2832     // In the 64-bit large code model, we have to make all calls
2833     // through a register, since the call instruction's 32-bit
2834     // pc-relative offset may not be large enough to hold the whole
2835     // address.
2836   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2837     // If the callee is a GlobalAddress node (quite common, every direct call
2838     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2839     // it.
2840
2841     // We should use extra load for direct calls to dllimported functions in
2842     // non-JIT mode.
2843     const GlobalValue *GV = G->getGlobal();
2844     if (!GV->hasDLLImportStorageClass()) {
2845       unsigned char OpFlags = 0;
2846       bool ExtraLoad = false;
2847       unsigned WrapperKind = ISD::DELETED_NODE;
2848
2849       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2850       // external symbols most go through the PLT in PIC mode.  If the symbol
2851       // has hidden or protected visibility, or if it is static or local, then
2852       // we don't need to use the PLT - we can directly call it.
2853       if (Subtarget->isTargetELF() &&
2854           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2855           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2856         OpFlags = X86II::MO_PLT;
2857       } else if (Subtarget->isPICStyleStubAny() &&
2858                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2859                  (!Subtarget->getTargetTriple().isMacOSX() ||
2860                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2861         // PC-relative references to external symbols should go through $stub,
2862         // unless we're building with the leopard linker or later, which
2863         // automatically synthesizes these stubs.
2864         OpFlags = X86II::MO_DARWIN_STUB;
2865       } else if (Subtarget->isPICStyleRIPRel() &&
2866                  isa<Function>(GV) &&
2867                  cast<Function>(GV)->getAttributes().
2868                    hasAttribute(AttributeSet::FunctionIndex,
2869                                 Attribute::NonLazyBind)) {
2870         // If the function is marked as non-lazy, generate an indirect call
2871         // which loads from the GOT directly. This avoids runtime overhead
2872         // at the cost of eager binding (and one extra byte of encoding).
2873         OpFlags = X86II::MO_GOTPCREL;
2874         WrapperKind = X86ISD::WrapperRIP;
2875         ExtraLoad = true;
2876       }
2877
2878       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2879                                           G->getOffset(), OpFlags);
2880
2881       // Add a wrapper if needed.
2882       if (WrapperKind != ISD::DELETED_NODE)
2883         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2884       // Add extra indirection if needed.
2885       if (ExtraLoad)
2886         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2887                              MachinePointerInfo::getGOT(),
2888                              false, false, false, 0);
2889     }
2890   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2891     unsigned char OpFlags = 0;
2892
2893     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2894     // external symbols should go through the PLT.
2895     if (Subtarget->isTargetELF() &&
2896         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2897       OpFlags = X86II::MO_PLT;
2898     } else if (Subtarget->isPICStyleStubAny() &&
2899                (!Subtarget->getTargetTriple().isMacOSX() ||
2900                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2901       // PC-relative references to external symbols should go through $stub,
2902       // unless we're building with the leopard linker or later, which
2903       // automatically synthesizes these stubs.
2904       OpFlags = X86II::MO_DARWIN_STUB;
2905     }
2906
2907     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2908                                          OpFlags);
2909   }
2910
2911   // Returns a chain & a flag for retval copy to use.
2912   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2913   SmallVector<SDValue, 8> Ops;
2914
2915   if (!IsSibcall && isTailCall) {
2916     Chain = DAG.getCALLSEQ_END(Chain,
2917                                DAG.getIntPtrConstant(NumBytesToPop, true),
2918                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2919     InFlag = Chain.getValue(1);
2920   }
2921
2922   Ops.push_back(Chain);
2923   Ops.push_back(Callee);
2924
2925   if (isTailCall)
2926     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2927
2928   // Add argument registers to the end of the list so that they are known live
2929   // into the call.
2930   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2931     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2932                                   RegsToPass[i].second.getValueType()));
2933
2934   // Add a register mask operand representing the call-preserved registers.
2935   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2936   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2937   assert(Mask && "Missing call preserved mask for calling convention");
2938   Ops.push_back(DAG.getRegisterMask(Mask));
2939
2940   if (InFlag.getNode())
2941     Ops.push_back(InFlag);
2942
2943   if (isTailCall) {
2944     // We used to do:
2945     //// If this is the first return lowered for this function, add the regs
2946     //// to the liveout set for the function.
2947     // This isn't right, although it's probably harmless on x86; liveouts
2948     // should be computed from returns not tail calls.  Consider a void
2949     // function making a tail call to a function returning int.
2950     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2951   }
2952
2953   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2954   InFlag = Chain.getValue(1);
2955
2956   // Create the CALLSEQ_END node.
2957   unsigned NumBytesForCalleeToPop;
2958   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2959                        getTargetMachine().Options.GuaranteedTailCallOpt))
2960     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2961   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2962            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2963            SR == StackStructReturn)
2964     // If this is a call to a struct-return function, the callee
2965     // pops the hidden struct pointer, so we have to push it back.
2966     // This is common for Darwin/X86, Linux & Mingw32 targets.
2967     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2968     NumBytesForCalleeToPop = 4;
2969   else
2970     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2971
2972   // Returns a flag for retval copy to use.
2973   if (!IsSibcall) {
2974     Chain = DAG.getCALLSEQ_END(Chain,
2975                                DAG.getIntPtrConstant(NumBytesToPop, true),
2976                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2977                                                      true),
2978                                InFlag, dl);
2979     InFlag = Chain.getValue(1);
2980   }
2981
2982   // Handle result values, copying them out of physregs into vregs that we
2983   // return.
2984   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2985                          Ins, dl, DAG, InVals);
2986 }
2987
2988 //===----------------------------------------------------------------------===//
2989 //                Fast Calling Convention (tail call) implementation
2990 //===----------------------------------------------------------------------===//
2991
2992 //  Like std call, callee cleans arguments, convention except that ECX is
2993 //  reserved for storing the tail called function address. Only 2 registers are
2994 //  free for argument passing (inreg). Tail call optimization is performed
2995 //  provided:
2996 //                * tailcallopt is enabled
2997 //                * caller/callee are fastcc
2998 //  On X86_64 architecture with GOT-style position independent code only local
2999 //  (within module) calls are supported at the moment.
3000 //  To keep the stack aligned according to platform abi the function
3001 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3002 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3003 //  If a tail called function callee has more arguments than the caller the
3004 //  caller needs to make sure that there is room to move the RETADDR to. This is
3005 //  achieved by reserving an area the size of the argument delta right after the
3006 //  original REtADDR, but before the saved framepointer or the spilled registers
3007 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3008 //  stack layout:
3009 //    arg1
3010 //    arg2
3011 //    RETADDR
3012 //    [ new RETADDR
3013 //      move area ]
3014 //    (possible EBP)
3015 //    ESI
3016 //    EDI
3017 //    local1 ..
3018
3019 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3020 /// for a 16 byte align requirement.
3021 unsigned
3022 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3023                                                SelectionDAG& DAG) const {
3024   MachineFunction &MF = DAG.getMachineFunction();
3025   const TargetMachine &TM = MF.getTarget();
3026   const X86RegisterInfo *RegInfo =
3027     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3028   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3029   unsigned StackAlignment = TFI.getStackAlignment();
3030   uint64_t AlignMask = StackAlignment - 1;
3031   int64_t Offset = StackSize;
3032   unsigned SlotSize = RegInfo->getSlotSize();
3033   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3034     // Number smaller than 12 so just add the difference.
3035     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3036   } else {
3037     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3038     Offset = ((~AlignMask) & Offset) + StackAlignment +
3039       (StackAlignment-SlotSize);
3040   }
3041   return Offset;
3042 }
3043
3044 /// MatchingStackOffset - Return true if the given stack call argument is
3045 /// already available in the same position (relatively) of the caller's
3046 /// incoming argument stack.
3047 static
3048 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3049                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3050                          const X86InstrInfo *TII) {
3051   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3052   int FI = INT_MAX;
3053   if (Arg.getOpcode() == ISD::CopyFromReg) {
3054     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3055     if (!TargetRegisterInfo::isVirtualRegister(VR))
3056       return false;
3057     MachineInstr *Def = MRI->getVRegDef(VR);
3058     if (!Def)
3059       return false;
3060     if (!Flags.isByVal()) {
3061       if (!TII->isLoadFromStackSlot(Def, FI))
3062         return false;
3063     } else {
3064       unsigned Opcode = Def->getOpcode();
3065       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3066           Def->getOperand(1).isFI()) {
3067         FI = Def->getOperand(1).getIndex();
3068         Bytes = Flags.getByValSize();
3069       } else
3070         return false;
3071     }
3072   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3073     if (Flags.isByVal())
3074       // ByVal argument is passed in as a pointer but it's now being
3075       // dereferenced. e.g.
3076       // define @foo(%struct.X* %A) {
3077       //   tail call @bar(%struct.X* byval %A)
3078       // }
3079       return false;
3080     SDValue Ptr = Ld->getBasePtr();
3081     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3082     if (!FINode)
3083       return false;
3084     FI = FINode->getIndex();
3085   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3086     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3087     FI = FINode->getIndex();
3088     Bytes = Flags.getByValSize();
3089   } else
3090     return false;
3091
3092   assert(FI != INT_MAX);
3093   if (!MFI->isFixedObjectIndex(FI))
3094     return false;
3095   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3096 }
3097
3098 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3099 /// for tail call optimization. Targets which want to do tail call
3100 /// optimization should implement this function.
3101 bool
3102 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3103                                                      CallingConv::ID CalleeCC,
3104                                                      bool isVarArg,
3105                                                      bool isCalleeStructRet,
3106                                                      bool isCallerStructRet,
3107                                                      Type *RetTy,
3108                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3109                                     const SmallVectorImpl<SDValue> &OutVals,
3110                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3111                                                      SelectionDAG &DAG) const {
3112   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3113     return false;
3114
3115   // If -tailcallopt is specified, make fastcc functions tail-callable.
3116   const MachineFunction &MF = DAG.getMachineFunction();
3117   const Function *CallerF = MF.getFunction();
3118
3119   // If the function return type is x86_fp80 and the callee return type is not,
3120   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3121   // perform a tailcall optimization here.
3122   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3123     return false;
3124
3125   CallingConv::ID CallerCC = CallerF->getCallingConv();
3126   bool CCMatch = CallerCC == CalleeCC;
3127   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3128   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3129
3130   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3131     if (IsTailCallConvention(CalleeCC) && CCMatch)
3132       return true;
3133     return false;
3134   }
3135
3136   // Look for obvious safe cases to perform tail call optimization that do not
3137   // require ABI changes. This is what gcc calls sibcall.
3138
3139   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3140   // emit a special epilogue.
3141   const X86RegisterInfo *RegInfo =
3142     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3143   if (RegInfo->needsStackRealignment(MF))
3144     return false;
3145
3146   // Also avoid sibcall optimization if either caller or callee uses struct
3147   // return semantics.
3148   if (isCalleeStructRet || isCallerStructRet)
3149     return false;
3150
3151   // An stdcall/thiscall caller is expected to clean up its arguments; the
3152   // callee isn't going to do that.
3153   // FIXME: this is more restrictive than needed. We could produce a tailcall
3154   // when the stack adjustment matches. For example, with a thiscall that takes
3155   // only one argument.
3156   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3157                    CallerCC == CallingConv::X86_ThisCall))
3158     return false;
3159
3160   // Do not sibcall optimize vararg calls unless all arguments are passed via
3161   // registers.
3162   if (isVarArg && !Outs.empty()) {
3163
3164     // Optimizing for varargs on Win64 is unlikely to be safe without
3165     // additional testing.
3166     if (IsCalleeWin64 || IsCallerWin64)
3167       return false;
3168
3169     SmallVector<CCValAssign, 16> ArgLocs;
3170     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3171                    getTargetMachine(), ArgLocs, *DAG.getContext());
3172
3173     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3174     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3175       if (!ArgLocs[i].isRegLoc())
3176         return false;
3177   }
3178
3179   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3180   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3181   // this into a sibcall.
3182   bool Unused = false;
3183   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3184     if (!Ins[i].Used) {
3185       Unused = true;
3186       break;
3187     }
3188   }
3189   if (Unused) {
3190     SmallVector<CCValAssign, 16> RVLocs;
3191     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3192                    getTargetMachine(), RVLocs, *DAG.getContext());
3193     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3194     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3195       CCValAssign &VA = RVLocs[i];
3196       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3197         return false;
3198     }
3199   }
3200
3201   // If the calling conventions do not match, then we'd better make sure the
3202   // results are returned in the same way as what the caller expects.
3203   if (!CCMatch) {
3204     SmallVector<CCValAssign, 16> RVLocs1;
3205     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3206                     getTargetMachine(), RVLocs1, *DAG.getContext());
3207     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3208
3209     SmallVector<CCValAssign, 16> RVLocs2;
3210     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3211                     getTargetMachine(), RVLocs2, *DAG.getContext());
3212     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3213
3214     if (RVLocs1.size() != RVLocs2.size())
3215       return false;
3216     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3217       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3218         return false;
3219       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3220         return false;
3221       if (RVLocs1[i].isRegLoc()) {
3222         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3223           return false;
3224       } else {
3225         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3226           return false;
3227       }
3228     }
3229   }
3230
3231   // If the callee takes no arguments then go on to check the results of the
3232   // call.
3233   if (!Outs.empty()) {
3234     // Check if stack adjustment is needed. For now, do not do this if any
3235     // argument is passed on the stack.
3236     SmallVector<CCValAssign, 16> ArgLocs;
3237     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3238                    getTargetMachine(), ArgLocs, *DAG.getContext());
3239
3240     // Allocate shadow area for Win64
3241     if (IsCalleeWin64)
3242       CCInfo.AllocateStack(32, 8);
3243
3244     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3245     if (CCInfo.getNextStackOffset()) {
3246       MachineFunction &MF = DAG.getMachineFunction();
3247       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3248         return false;
3249
3250       // Check if the arguments are already laid out in the right way as
3251       // the caller's fixed stack objects.
3252       MachineFrameInfo *MFI = MF.getFrameInfo();
3253       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3254       const X86InstrInfo *TII =
3255         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3256       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3257         CCValAssign &VA = ArgLocs[i];
3258         SDValue Arg = OutVals[i];
3259         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3260         if (VA.getLocInfo() == CCValAssign::Indirect)
3261           return false;
3262         if (!VA.isRegLoc()) {
3263           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3264                                    MFI, MRI, TII))
3265             return false;
3266         }
3267       }
3268     }
3269
3270     // If the tailcall address may be in a register, then make sure it's
3271     // possible to register allocate for it. In 32-bit, the call address can
3272     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3273     // callee-saved registers are restored. These happen to be the same
3274     // registers used to pass 'inreg' arguments so watch out for those.
3275     if (!Subtarget->is64Bit() &&
3276         ((!isa<GlobalAddressSDNode>(Callee) &&
3277           !isa<ExternalSymbolSDNode>(Callee)) ||
3278          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3279       unsigned NumInRegs = 0;
3280       // In PIC we need an extra register to formulate the address computation
3281       // for the callee.
3282       unsigned MaxInRegs =
3283           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3284
3285       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3286         CCValAssign &VA = ArgLocs[i];
3287         if (!VA.isRegLoc())
3288           continue;
3289         unsigned Reg = VA.getLocReg();
3290         switch (Reg) {
3291         default: break;
3292         case X86::EAX: case X86::EDX: case X86::ECX:
3293           if (++NumInRegs == MaxInRegs)
3294             return false;
3295           break;
3296         }
3297       }
3298     }
3299   }
3300
3301   return true;
3302 }
3303
3304 FastISel *
3305 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3306                                   const TargetLibraryInfo *libInfo) const {
3307   return X86::createFastISel(funcInfo, libInfo);
3308 }
3309
3310 //===----------------------------------------------------------------------===//
3311 //                           Other Lowering Hooks
3312 //===----------------------------------------------------------------------===//
3313
3314 static bool MayFoldLoad(SDValue Op) {
3315   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3316 }
3317
3318 static bool MayFoldIntoStore(SDValue Op) {
3319   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3320 }
3321
3322 static bool isTargetShuffle(unsigned Opcode) {
3323   switch(Opcode) {
3324   default: return false;
3325   case X86ISD::PSHUFD:
3326   case X86ISD::PSHUFHW:
3327   case X86ISD::PSHUFLW:
3328   case X86ISD::SHUFP:
3329   case X86ISD::PALIGNR:
3330   case X86ISD::MOVLHPS:
3331   case X86ISD::MOVLHPD:
3332   case X86ISD::MOVHLPS:
3333   case X86ISD::MOVLPS:
3334   case X86ISD::MOVLPD:
3335   case X86ISD::MOVSHDUP:
3336   case X86ISD::MOVSLDUP:
3337   case X86ISD::MOVDDUP:
3338   case X86ISD::MOVSS:
3339   case X86ISD::MOVSD:
3340   case X86ISD::UNPCKL:
3341   case X86ISD::UNPCKH:
3342   case X86ISD::VPERMILP:
3343   case X86ISD::VPERM2X128:
3344   case X86ISD::VPERMI:
3345     return true;
3346   }
3347 }
3348
3349 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3350                                     SDValue V1, SelectionDAG &DAG) {
3351   switch(Opc) {
3352   default: llvm_unreachable("Unknown x86 shuffle node");
3353   case X86ISD::MOVSHDUP:
3354   case X86ISD::MOVSLDUP:
3355   case X86ISD::MOVDDUP:
3356     return DAG.getNode(Opc, dl, VT, V1);
3357   }
3358 }
3359
3360 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3361                                     SDValue V1, unsigned TargetMask,
3362                                     SelectionDAG &DAG) {
3363   switch(Opc) {
3364   default: llvm_unreachable("Unknown x86 shuffle node");
3365   case X86ISD::PSHUFD:
3366   case X86ISD::PSHUFHW:
3367   case X86ISD::PSHUFLW:
3368   case X86ISD::VPERMILP:
3369   case X86ISD::VPERMI:
3370     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3371   }
3372 }
3373
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375                                     SDValue V1, SDValue V2, unsigned TargetMask,
3376                                     SelectionDAG &DAG) {
3377   switch(Opc) {
3378   default: llvm_unreachable("Unknown x86 shuffle node");
3379   case X86ISD::PALIGNR:
3380   case X86ISD::SHUFP:
3381   case X86ISD::VPERM2X128:
3382     return DAG.getNode(Opc, dl, VT, V1, V2,
3383                        DAG.getConstant(TargetMask, MVT::i8));
3384   }
3385 }
3386
3387 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3388                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3389   switch(Opc) {
3390   default: llvm_unreachable("Unknown x86 shuffle node");
3391   case X86ISD::MOVLHPS:
3392   case X86ISD::MOVLHPD:
3393   case X86ISD::MOVHLPS:
3394   case X86ISD::MOVLPS:
3395   case X86ISD::MOVLPD:
3396   case X86ISD::MOVSS:
3397   case X86ISD::MOVSD:
3398   case X86ISD::UNPCKL:
3399   case X86ISD::UNPCKH:
3400     return DAG.getNode(Opc, dl, VT, V1, V2);
3401   }
3402 }
3403
3404 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3405   MachineFunction &MF = DAG.getMachineFunction();
3406   const X86RegisterInfo *RegInfo =
3407     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3408   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3409   int ReturnAddrIndex = FuncInfo->getRAIndex();
3410
3411   if (ReturnAddrIndex == 0) {
3412     // Set up a frame object for the return address.
3413     unsigned SlotSize = RegInfo->getSlotSize();
3414     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3415                                                            -(int64_t)SlotSize,
3416                                                            false);
3417     FuncInfo->setRAIndex(ReturnAddrIndex);
3418   }
3419
3420   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3421 }
3422
3423 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3424                                        bool hasSymbolicDisplacement) {
3425   // Offset should fit into 32 bit immediate field.
3426   if (!isInt<32>(Offset))
3427     return false;
3428
3429   // If we don't have a symbolic displacement - we don't have any extra
3430   // restrictions.
3431   if (!hasSymbolicDisplacement)
3432     return true;
3433
3434   // FIXME: Some tweaks might be needed for medium code model.
3435   if (M != CodeModel::Small && M != CodeModel::Kernel)
3436     return false;
3437
3438   // For small code model we assume that latest object is 16MB before end of 31
3439   // bits boundary. We may also accept pretty large negative constants knowing
3440   // that all objects are in the positive half of address space.
3441   if (M == CodeModel::Small && Offset < 16*1024*1024)
3442     return true;
3443
3444   // For kernel code model we know that all object resist in the negative half
3445   // of 32bits address space. We may not accept negative offsets, since they may
3446   // be just off and we may accept pretty large positive ones.
3447   if (M == CodeModel::Kernel && Offset > 0)
3448     return true;
3449
3450   return false;
3451 }
3452
3453 /// isCalleePop - Determines whether the callee is required to pop its
3454 /// own arguments. Callee pop is necessary to support tail calls.
3455 bool X86::isCalleePop(CallingConv::ID CallingConv,
3456                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3457   if (IsVarArg)
3458     return false;
3459
3460   switch (CallingConv) {
3461   default:
3462     return false;
3463   case CallingConv::X86_StdCall:
3464     return !is64Bit;
3465   case CallingConv::X86_FastCall:
3466     return !is64Bit;
3467   case CallingConv::X86_ThisCall:
3468     return !is64Bit;
3469   case CallingConv::Fast:
3470     return TailCallOpt;
3471   case CallingConv::GHC:
3472     return TailCallOpt;
3473   case CallingConv::HiPE:
3474     return TailCallOpt;
3475   }
3476 }
3477
3478 /// \brief Return true if the condition is an unsigned comparison operation.
3479 static bool isX86CCUnsigned(unsigned X86CC) {
3480   switch (X86CC) {
3481   default: llvm_unreachable("Invalid integer condition!");
3482   case X86::COND_E:     return true;
3483   case X86::COND_G:     return false;
3484   case X86::COND_GE:    return false;
3485   case X86::COND_L:     return false;
3486   case X86::COND_LE:    return false;
3487   case X86::COND_NE:    return true;
3488   case X86::COND_B:     return true;
3489   case X86::COND_A:     return true;
3490   case X86::COND_BE:    return true;
3491   case X86::COND_AE:    return true;
3492   }
3493   llvm_unreachable("covered switch fell through?!");
3494 }
3495
3496 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3497 /// specific condition code, returning the condition code and the LHS/RHS of the
3498 /// comparison to make.
3499 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3500                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3501   if (!isFP) {
3502     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3503       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3504         // X > -1   -> X == 0, jump !sign.
3505         RHS = DAG.getConstant(0, RHS.getValueType());
3506         return X86::COND_NS;
3507       }
3508       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3509         // X < 0   -> X == 0, jump on sign.
3510         return X86::COND_S;
3511       }
3512       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3513         // X < 1   -> X <= 0
3514         RHS = DAG.getConstant(0, RHS.getValueType());
3515         return X86::COND_LE;
3516       }
3517     }
3518
3519     switch (SetCCOpcode) {
3520     default: llvm_unreachable("Invalid integer condition!");
3521     case ISD::SETEQ:  return X86::COND_E;
3522     case ISD::SETGT:  return X86::COND_G;
3523     case ISD::SETGE:  return X86::COND_GE;
3524     case ISD::SETLT:  return X86::COND_L;
3525     case ISD::SETLE:  return X86::COND_LE;
3526     case ISD::SETNE:  return X86::COND_NE;
3527     case ISD::SETULT: return X86::COND_B;
3528     case ISD::SETUGT: return X86::COND_A;
3529     case ISD::SETULE: return X86::COND_BE;
3530     case ISD::SETUGE: return X86::COND_AE;
3531     }
3532   }
3533
3534   // First determine if it is required or is profitable to flip the operands.
3535
3536   // If LHS is a foldable load, but RHS is not, flip the condition.
3537   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3538       !ISD::isNON_EXTLoad(RHS.getNode())) {
3539     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3540     std::swap(LHS, RHS);
3541   }
3542
3543   switch (SetCCOpcode) {
3544   default: break;
3545   case ISD::SETOLT:
3546   case ISD::SETOLE:
3547   case ISD::SETUGT:
3548   case ISD::SETUGE:
3549     std::swap(LHS, RHS);
3550     break;
3551   }
3552
3553   // On a floating point condition, the flags are set as follows:
3554   // ZF  PF  CF   op
3555   //  0 | 0 | 0 | X > Y
3556   //  0 | 0 | 1 | X < Y
3557   //  1 | 0 | 0 | X == Y
3558   //  1 | 1 | 1 | unordered
3559   switch (SetCCOpcode) {
3560   default: llvm_unreachable("Condcode should be pre-legalized away");
3561   case ISD::SETUEQ:
3562   case ISD::SETEQ:   return X86::COND_E;
3563   case ISD::SETOLT:              // flipped
3564   case ISD::SETOGT:
3565   case ISD::SETGT:   return X86::COND_A;
3566   case ISD::SETOLE:              // flipped
3567   case ISD::SETOGE:
3568   case ISD::SETGE:   return X86::COND_AE;
3569   case ISD::SETUGT:              // flipped
3570   case ISD::SETULT:
3571   case ISD::SETLT:   return X86::COND_B;
3572   case ISD::SETUGE:              // flipped
3573   case ISD::SETULE:
3574   case ISD::SETLE:   return X86::COND_BE;
3575   case ISD::SETONE:
3576   case ISD::SETNE:   return X86::COND_NE;
3577   case ISD::SETUO:   return X86::COND_P;
3578   case ISD::SETO:    return X86::COND_NP;
3579   case ISD::SETOEQ:
3580   case ISD::SETUNE:  return X86::COND_INVALID;
3581   }
3582 }
3583
3584 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3585 /// code. Current x86 isa includes the following FP cmov instructions:
3586 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3587 static bool hasFPCMov(unsigned X86CC) {
3588   switch (X86CC) {
3589   default:
3590     return false;
3591   case X86::COND_B:
3592   case X86::COND_BE:
3593   case X86::COND_E:
3594   case X86::COND_P:
3595   case X86::COND_A:
3596   case X86::COND_AE:
3597   case X86::COND_NE:
3598   case X86::COND_NP:
3599     return true;
3600   }
3601 }
3602
3603 /// isFPImmLegal - Returns true if the target can instruction select the
3604 /// specified FP immediate natively. If false, the legalizer will
3605 /// materialize the FP immediate as a load from a constant pool.
3606 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3607   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3608     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3609       return true;
3610   }
3611   return false;
3612 }
3613
3614 /// \brief Returns true if it is beneficial to convert a load of a constant
3615 /// to just the constant itself.
3616 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3617                                                           Type *Ty) const {
3618   assert(Ty->isIntegerTy());
3619
3620   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3621   if (BitSize == 0 || BitSize > 64)
3622     return false;
3623   return true;
3624 }
3625
3626 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3627 /// the specified range (L, H].
3628 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3629   return (Val < 0) || (Val >= Low && Val < Hi);
3630 }
3631
3632 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3633 /// specified value.
3634 static bool isUndefOrEqual(int Val, int CmpVal) {
3635   return (Val < 0 || Val == CmpVal);
3636 }
3637
3638 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3639 /// from position Pos and ending in Pos+Size, falls within the specified
3640 /// sequential range (L, L+Pos]. or is undef.
3641 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3642                                        unsigned Pos, unsigned Size, int Low) {
3643   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3644     if (!isUndefOrEqual(Mask[i], Low))
3645       return false;
3646   return true;
3647 }
3648
3649 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3650 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3651 /// the second operand.
3652 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3653   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3654     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3655   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3656     return (Mask[0] < 2 && Mask[1] < 2);
3657   return false;
3658 }
3659
3660 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3661 /// is suitable for input to PSHUFHW.
3662 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3663   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3664     return false;
3665
3666   // Lower quadword copied in order or undef.
3667   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3668     return false;
3669
3670   // Upper quadword shuffled.
3671   for (unsigned i = 4; i != 8; ++i)
3672     if (!isUndefOrInRange(Mask[i], 4, 8))
3673       return false;
3674
3675   if (VT == MVT::v16i16) {
3676     // Lower quadword copied in order or undef.
3677     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3678       return false;
3679
3680     // Upper quadword shuffled.
3681     for (unsigned i = 12; i != 16; ++i)
3682       if (!isUndefOrInRange(Mask[i], 12, 16))
3683         return false;
3684   }
3685
3686   return true;
3687 }
3688
3689 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3690 /// is suitable for input to PSHUFLW.
3691 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3692   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3693     return false;
3694
3695   // Upper quadword copied in order.
3696   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3697     return false;
3698
3699   // Lower quadword shuffled.
3700   for (unsigned i = 0; i != 4; ++i)
3701     if (!isUndefOrInRange(Mask[i], 0, 4))
3702       return false;
3703
3704   if (VT == MVT::v16i16) {
3705     // Upper quadword copied in order.
3706     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3707       return false;
3708
3709     // Lower quadword shuffled.
3710     for (unsigned i = 8; i != 12; ++i)
3711       if (!isUndefOrInRange(Mask[i], 8, 12))
3712         return false;
3713   }
3714
3715   return true;
3716 }
3717
3718 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3719 /// is suitable for input to PALIGNR.
3720 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3721                           const X86Subtarget *Subtarget) {
3722   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3723       (VT.is256BitVector() && !Subtarget->hasInt256()))
3724     return false;
3725
3726   unsigned NumElts = VT.getVectorNumElements();
3727   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3728   unsigned NumLaneElts = NumElts/NumLanes;
3729
3730   // Do not handle 64-bit element shuffles with palignr.
3731   if (NumLaneElts == 2)
3732     return false;
3733
3734   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3735     unsigned i;
3736     for (i = 0; i != NumLaneElts; ++i) {
3737       if (Mask[i+l] >= 0)
3738         break;
3739     }
3740
3741     // Lane is all undef, go to next lane
3742     if (i == NumLaneElts)
3743       continue;
3744
3745     int Start = Mask[i+l];
3746
3747     // Make sure its in this lane in one of the sources
3748     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3749         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3750       return false;
3751
3752     // If not lane 0, then we must match lane 0
3753     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3754       return false;
3755
3756     // Correct second source to be contiguous with first source
3757     if (Start >= (int)NumElts)
3758       Start -= NumElts - NumLaneElts;
3759
3760     // Make sure we're shifting in the right direction.
3761     if (Start <= (int)(i+l))
3762       return false;
3763
3764     Start -= i;
3765
3766     // Check the rest of the elements to see if they are consecutive.
3767     for (++i; i != NumLaneElts; ++i) {
3768       int Idx = Mask[i+l];
3769
3770       // Make sure its in this lane
3771       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3772           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3773         return false;
3774
3775       // If not lane 0, then we must match lane 0
3776       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3777         return false;
3778
3779       if (Idx >= (int)NumElts)
3780         Idx -= NumElts - NumLaneElts;
3781
3782       if (!isUndefOrEqual(Idx, Start+i))
3783         return false;
3784
3785     }
3786   }
3787
3788   return true;
3789 }
3790
3791 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3792 /// the two vector operands have swapped position.
3793 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3794                                      unsigned NumElems) {
3795   for (unsigned i = 0; i != NumElems; ++i) {
3796     int idx = Mask[i];
3797     if (idx < 0)
3798       continue;
3799     else if (idx < (int)NumElems)
3800       Mask[i] = idx + NumElems;
3801     else
3802       Mask[i] = idx - NumElems;
3803   }
3804 }
3805
3806 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3807 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3808 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3809 /// reverse of what x86 shuffles want.
3810 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3811
3812   unsigned NumElems = VT.getVectorNumElements();
3813   unsigned NumLanes = VT.getSizeInBits()/128;
3814   unsigned NumLaneElems = NumElems/NumLanes;
3815
3816   if (NumLaneElems != 2 && NumLaneElems != 4)
3817     return false;
3818
3819   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3820   bool symetricMaskRequired =
3821     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3822
3823   // VSHUFPSY divides the resulting vector into 4 chunks.
3824   // The sources are also splitted into 4 chunks, and each destination
3825   // chunk must come from a different source chunk.
3826   //
3827   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3828   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3829   //
3830   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3831   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3832   //
3833   // VSHUFPDY divides the resulting vector into 4 chunks.
3834   // The sources are also splitted into 4 chunks, and each destination
3835   // chunk must come from a different source chunk.
3836   //
3837   //  SRC1 =>      X3       X2       X1       X0
3838   //  SRC2 =>      Y3       Y2       Y1       Y0
3839   //
3840   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3841   //
3842   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3843   unsigned HalfLaneElems = NumLaneElems/2;
3844   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3845     for (unsigned i = 0; i != NumLaneElems; ++i) {
3846       int Idx = Mask[i+l];
3847       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3848       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3849         return false;
3850       // For VSHUFPSY, the mask of the second half must be the same as the
3851       // first but with the appropriate offsets. This works in the same way as
3852       // VPERMILPS works with masks.
3853       if (!symetricMaskRequired || Idx < 0)
3854         continue;
3855       if (MaskVal[i] < 0) {
3856         MaskVal[i] = Idx - l;
3857         continue;
3858       }
3859       if ((signed)(Idx - l) != MaskVal[i])
3860         return false;
3861     }
3862   }
3863
3864   return true;
3865 }
3866
3867 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3868 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3869 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3870   if (!VT.is128BitVector())
3871     return false;
3872
3873   unsigned NumElems = VT.getVectorNumElements();
3874
3875   if (NumElems != 4)
3876     return false;
3877
3878   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3879   return isUndefOrEqual(Mask[0], 6) &&
3880          isUndefOrEqual(Mask[1], 7) &&
3881          isUndefOrEqual(Mask[2], 2) &&
3882          isUndefOrEqual(Mask[3], 3);
3883 }
3884
3885 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3886 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3887 /// <2, 3, 2, 3>
3888 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3889   if (!VT.is128BitVector())
3890     return false;
3891
3892   unsigned NumElems = VT.getVectorNumElements();
3893
3894   if (NumElems != 4)
3895     return false;
3896
3897   return isUndefOrEqual(Mask[0], 2) &&
3898          isUndefOrEqual(Mask[1], 3) &&
3899          isUndefOrEqual(Mask[2], 2) &&
3900          isUndefOrEqual(Mask[3], 3);
3901 }
3902
3903 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3905 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3906   if (!VT.is128BitVector())
3907     return false;
3908
3909   unsigned NumElems = VT.getVectorNumElements();
3910
3911   if (NumElems != 2 && NumElems != 4)
3912     return false;
3913
3914   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3915     if (!isUndefOrEqual(Mask[i], i + NumElems))
3916       return false;
3917
3918   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3919     if (!isUndefOrEqual(Mask[i], i))
3920       return false;
3921
3922   return true;
3923 }
3924
3925 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3926 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3927 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3928   if (!VT.is128BitVector())
3929     return false;
3930
3931   unsigned NumElems = VT.getVectorNumElements();
3932
3933   if (NumElems != 2 && NumElems != 4)
3934     return false;
3935
3936   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3937     if (!isUndefOrEqual(Mask[i], i))
3938       return false;
3939
3940   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3941     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3942       return false;
3943
3944   return true;
3945 }
3946
3947 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3948 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3949 /// i. e: If all but one element come from the same vector.
3950 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3951   // TODO: Deal with AVX's VINSERTPS
3952   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3953     return false;
3954
3955   unsigned CorrectPosV1 = 0;
3956   unsigned CorrectPosV2 = 0;
3957   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3958     if (Mask[i] == i)
3959       ++CorrectPosV1;
3960     else if (Mask[i] == i + 4)
3961       ++CorrectPosV2;
3962
3963   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3964     // We have 3 elements from one vector, and one from another.
3965     return true;
3966
3967   return false;
3968 }
3969
3970 //
3971 // Some special combinations that can be optimized.
3972 //
3973 static
3974 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3975                                SelectionDAG &DAG) {
3976   MVT VT = SVOp->getSimpleValueType(0);
3977   SDLoc dl(SVOp);
3978
3979   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3980     return SDValue();
3981
3982   ArrayRef<int> Mask = SVOp->getMask();
3983
3984   // These are the special masks that may be optimized.
3985   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3986   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3987   bool MatchEvenMask = true;
3988   bool MatchOddMask  = true;
3989   for (int i=0; i<8; ++i) {
3990     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3991       MatchEvenMask = false;
3992     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3993       MatchOddMask = false;
3994   }
3995
3996   if (!MatchEvenMask && !MatchOddMask)
3997     return SDValue();
3998
3999   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4000
4001   SDValue Op0 = SVOp->getOperand(0);
4002   SDValue Op1 = SVOp->getOperand(1);
4003
4004   if (MatchEvenMask) {
4005     // Shift the second operand right to 32 bits.
4006     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4007     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4008   } else {
4009     // Shift the first operand left to 32 bits.
4010     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4011     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4012   }
4013   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4014   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4015 }
4016
4017 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4018 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4019 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4020                          bool HasInt256, bool V2IsSplat = false) {
4021
4022   assert(VT.getSizeInBits() >= 128 &&
4023          "Unsupported vector type for unpckl");
4024
4025   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4026   unsigned NumLanes;
4027   unsigned NumOf256BitLanes;
4028   unsigned NumElts = VT.getVectorNumElements();
4029   if (VT.is256BitVector()) {
4030     if (NumElts != 4 && NumElts != 8 &&
4031         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4032     return false;
4033     NumLanes = 2;
4034     NumOf256BitLanes = 1;
4035   } else if (VT.is512BitVector()) {
4036     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4037            "Unsupported vector type for unpckh");
4038     NumLanes = 2;
4039     NumOf256BitLanes = 2;
4040   } else {
4041     NumLanes = 1;
4042     NumOf256BitLanes = 1;
4043   }
4044
4045   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4046   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4047
4048   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4049     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4050       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4051         int BitI  = Mask[l256*NumEltsInStride+l+i];
4052         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4053         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4054           return false;
4055         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4056           return false;
4057         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4058           return false;
4059       }
4060     }
4061   }
4062   return true;
4063 }
4064
4065 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4066 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4067 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4068                          bool HasInt256, bool V2IsSplat = false) {
4069   assert(VT.getSizeInBits() >= 128 &&
4070          "Unsupported vector type for unpckh");
4071
4072   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4073   unsigned NumLanes;
4074   unsigned NumOf256BitLanes;
4075   unsigned NumElts = VT.getVectorNumElements();
4076   if (VT.is256BitVector()) {
4077     if (NumElts != 4 && NumElts != 8 &&
4078         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4079     return false;
4080     NumLanes = 2;
4081     NumOf256BitLanes = 1;
4082   } else if (VT.is512BitVector()) {
4083     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4084            "Unsupported vector type for unpckh");
4085     NumLanes = 2;
4086     NumOf256BitLanes = 2;
4087   } else {
4088     NumLanes = 1;
4089     NumOf256BitLanes = 1;
4090   }
4091
4092   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4093   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4094
4095   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4096     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4097       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4098         int BitI  = Mask[l256*NumEltsInStride+l+i];
4099         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4100         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4101           return false;
4102         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4103           return false;
4104         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4105           return false;
4106       }
4107     }
4108   }
4109   return true;
4110 }
4111
4112 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4113 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4114 /// <0, 0, 1, 1>
4115 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4116   unsigned NumElts = VT.getVectorNumElements();
4117   bool Is256BitVec = VT.is256BitVector();
4118
4119   if (VT.is512BitVector())
4120     return false;
4121   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4122          "Unsupported vector type for unpckh");
4123
4124   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4125       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4126     return false;
4127
4128   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4129   // FIXME: Need a better way to get rid of this, there's no latency difference
4130   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4131   // the former later. We should also remove the "_undef" special mask.
4132   if (NumElts == 4 && Is256BitVec)
4133     return false;
4134
4135   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4136   // independently on 128-bit lanes.
4137   unsigned NumLanes = VT.getSizeInBits()/128;
4138   unsigned NumLaneElts = NumElts/NumLanes;
4139
4140   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4141     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4142       int BitI  = Mask[l+i];
4143       int BitI1 = Mask[l+i+1];
4144
4145       if (!isUndefOrEqual(BitI, j))
4146         return false;
4147       if (!isUndefOrEqual(BitI1, j))
4148         return false;
4149     }
4150   }
4151
4152   return true;
4153 }
4154
4155 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4156 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4157 /// <2, 2, 3, 3>
4158 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4159   unsigned NumElts = VT.getVectorNumElements();
4160
4161   if (VT.is512BitVector())
4162     return false;
4163
4164   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4165          "Unsupported vector type for unpckh");
4166
4167   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4168       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4169     return false;
4170
4171   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4172   // independently on 128-bit lanes.
4173   unsigned NumLanes = VT.getSizeInBits()/128;
4174   unsigned NumLaneElts = NumElts/NumLanes;
4175
4176   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4177     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4178       int BitI  = Mask[l+i];
4179       int BitI1 = Mask[l+i+1];
4180       if (!isUndefOrEqual(BitI, j))
4181         return false;
4182       if (!isUndefOrEqual(BitI1, j))
4183         return false;
4184     }
4185   }
4186   return true;
4187 }
4188
4189 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4190 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4191 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4192   if (!VT.is512BitVector())
4193     return false;
4194
4195   unsigned NumElts = VT.getVectorNumElements();
4196   unsigned HalfSize = NumElts/2;
4197   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4198     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4199       *Imm = 1;
4200       return true;
4201     }
4202   }
4203   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4204     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4205       *Imm = 0;
4206       return true;
4207     }
4208   }
4209   return false;
4210 }
4211
4212 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4213 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4214 /// MOVSD, and MOVD, i.e. setting the lowest element.
4215 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4216   if (VT.getVectorElementType().getSizeInBits() < 32)
4217     return false;
4218   if (!VT.is128BitVector())
4219     return false;
4220
4221   unsigned NumElts = VT.getVectorNumElements();
4222
4223   if (!isUndefOrEqual(Mask[0], NumElts))
4224     return false;
4225
4226   for (unsigned i = 1; i != NumElts; ++i)
4227     if (!isUndefOrEqual(Mask[i], i))
4228       return false;
4229
4230   return true;
4231 }
4232
4233 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4234 /// as permutations between 128-bit chunks or halves. As an example: this
4235 /// shuffle bellow:
4236 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4237 /// The first half comes from the second half of V1 and the second half from the
4238 /// the second half of V2.
4239 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4240   if (!HasFp256 || !VT.is256BitVector())
4241     return false;
4242
4243   // The shuffle result is divided into half A and half B. In total the two
4244   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4245   // B must come from C, D, E or F.
4246   unsigned HalfSize = VT.getVectorNumElements()/2;
4247   bool MatchA = false, MatchB = false;
4248
4249   // Check if A comes from one of C, D, E, F.
4250   for (unsigned Half = 0; Half != 4; ++Half) {
4251     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4252       MatchA = true;
4253       break;
4254     }
4255   }
4256
4257   // Check if B comes from one of C, D, E, F.
4258   for (unsigned Half = 0; Half != 4; ++Half) {
4259     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4260       MatchB = true;
4261       break;
4262     }
4263   }
4264
4265   return MatchA && MatchB;
4266 }
4267
4268 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4269 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4270 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4271   MVT VT = SVOp->getSimpleValueType(0);
4272
4273   unsigned HalfSize = VT.getVectorNumElements()/2;
4274
4275   unsigned FstHalf = 0, SndHalf = 0;
4276   for (unsigned i = 0; i < HalfSize; ++i) {
4277     if (SVOp->getMaskElt(i) > 0) {
4278       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4279       break;
4280     }
4281   }
4282   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4283     if (SVOp->getMaskElt(i) > 0) {
4284       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4285       break;
4286     }
4287   }
4288
4289   return (FstHalf | (SndHalf << 4));
4290 }
4291
4292 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4293 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4294   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4295   if (EltSize < 32)
4296     return false;
4297
4298   unsigned NumElts = VT.getVectorNumElements();
4299   Imm8 = 0;
4300   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4301     for (unsigned i = 0; i != NumElts; ++i) {
4302       if (Mask[i] < 0)
4303         continue;
4304       Imm8 |= Mask[i] << (i*2);
4305     }
4306     return true;
4307   }
4308
4309   unsigned LaneSize = 4;
4310   SmallVector<int, 4> MaskVal(LaneSize, -1);
4311
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 (Mask[i+l] < 0)
4317         continue;
4318       if (MaskVal[i] < 0) {
4319         MaskVal[i] = Mask[i+l] - l;
4320         Imm8 |= MaskVal[i] << (i*2);
4321         continue;
4322       }
4323       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4324         return false;
4325     }
4326   }
4327   return true;
4328 }
4329
4330 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4331 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4332 /// Note that VPERMIL mask matching is different depending whether theunderlying
4333 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4334 /// to the same elements of the low, but to the higher half of the source.
4335 /// In VPERMILPD the two lanes could be shuffled independently of each other
4336 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4337 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4338   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4339   if (VT.getSizeInBits() < 256 || EltSize < 32)
4340     return false;
4341   bool symetricMaskRequired = (EltSize == 32);
4342   unsigned NumElts = VT.getVectorNumElements();
4343
4344   unsigned NumLanes = VT.getSizeInBits()/128;
4345   unsigned LaneSize = NumElts/NumLanes;
4346   // 2 or 4 elements in one lane
4347
4348   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4349   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4350     for (unsigned i = 0; i != LaneSize; ++i) {
4351       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4352         return false;
4353       if (symetricMaskRequired) {
4354         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4355           ExpectedMaskVal[i] = Mask[i+l] - l;
4356           continue;
4357         }
4358         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4359           return false;
4360       }
4361     }
4362   }
4363   return true;
4364 }
4365
4366 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4367 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4368 /// element of vector 2 and the other elements to come from vector 1 in order.
4369 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4370                                bool V2IsSplat = false, bool V2IsUndef = false) {
4371   if (!VT.is128BitVector())
4372     return false;
4373
4374   unsigned NumOps = VT.getVectorNumElements();
4375   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4376     return false;
4377
4378   if (!isUndefOrEqual(Mask[0], 0))
4379     return false;
4380
4381   for (unsigned i = 1; i != NumOps; ++i)
4382     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4383           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4384           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4385       return false;
4386
4387   return true;
4388 }
4389
4390 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4391 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4392 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4393 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4394                            const X86Subtarget *Subtarget) {
4395   if (!Subtarget->hasSSE3())
4396     return false;
4397
4398   unsigned NumElems = VT.getVectorNumElements();
4399
4400   if ((VT.is128BitVector() && NumElems != 4) ||
4401       (VT.is256BitVector() && NumElems != 8) ||
4402       (VT.is512BitVector() && NumElems != 16))
4403     return false;
4404
4405   // "i+1" is the value the indexed mask element must have
4406   for (unsigned i = 0; i != NumElems; i += 2)
4407     if (!isUndefOrEqual(Mask[i], i+1) ||
4408         !isUndefOrEqual(Mask[i+1], i+1))
4409       return false;
4410
4411   return true;
4412 }
4413
4414 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4415 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4416 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4417 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4418                            const X86Subtarget *Subtarget) {
4419   if (!Subtarget->hasSSE3())
4420     return false;
4421
4422   unsigned NumElems = VT.getVectorNumElements();
4423
4424   if ((VT.is128BitVector() && NumElems != 4) ||
4425       (VT.is256BitVector() && NumElems != 8) ||
4426       (VT.is512BitVector() && NumElems != 16))
4427     return false;
4428
4429   // "i" is the value the indexed mask element must have
4430   for (unsigned i = 0; i != NumElems; i += 2)
4431     if (!isUndefOrEqual(Mask[i], i) ||
4432         !isUndefOrEqual(Mask[i+1], i))
4433       return false;
4434
4435   return true;
4436 }
4437
4438 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4439 /// specifies a shuffle of elements that is suitable for input to 256-bit
4440 /// version of MOVDDUP.
4441 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4442   if (!HasFp256 || !VT.is256BitVector())
4443     return false;
4444
4445   unsigned NumElts = VT.getVectorNumElements();
4446   if (NumElts != 4)
4447     return false;
4448
4449   for (unsigned i = 0; i != NumElts/2; ++i)
4450     if (!isUndefOrEqual(Mask[i], 0))
4451       return false;
4452   for (unsigned i = NumElts/2; i != NumElts; ++i)
4453     if (!isUndefOrEqual(Mask[i], NumElts/2))
4454       return false;
4455   return true;
4456 }
4457
4458 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4459 /// specifies a shuffle of elements that is suitable for input to 128-bit
4460 /// version of MOVDDUP.
4461 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4462   if (!VT.is128BitVector())
4463     return false;
4464
4465   unsigned e = VT.getVectorNumElements() / 2;
4466   for (unsigned i = 0; i != e; ++i)
4467     if (!isUndefOrEqual(Mask[i], i))
4468       return false;
4469   for (unsigned i = 0; i != e; ++i)
4470     if (!isUndefOrEqual(Mask[e+i], i))
4471       return false;
4472   return true;
4473 }
4474
4475 /// isVEXTRACTIndex - Return true if the specified
4476 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4477 /// suitable for instruction that extract 128 or 256 bit vectors
4478 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4479   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4480   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4481     return false;
4482
4483   // The index should be aligned on a vecWidth-bit boundary.
4484   uint64_t Index =
4485     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4486
4487   MVT VT = N->getSimpleValueType(0);
4488   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4489   bool Result = (Index * ElSize) % vecWidth == 0;
4490
4491   return Result;
4492 }
4493
4494 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4495 /// operand specifies a subvector insert that is suitable for input to
4496 /// insertion of 128 or 256-bit subvectors
4497 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4498   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4499   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4500     return false;
4501   // The index should be aligned on a vecWidth-bit boundary.
4502   uint64_t Index =
4503     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4504
4505   MVT VT = N->getSimpleValueType(0);
4506   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4507   bool Result = (Index * ElSize) % vecWidth == 0;
4508
4509   return Result;
4510 }
4511
4512 bool X86::isVINSERT128Index(SDNode *N) {
4513   return isVINSERTIndex(N, 128);
4514 }
4515
4516 bool X86::isVINSERT256Index(SDNode *N) {
4517   return isVINSERTIndex(N, 256);
4518 }
4519
4520 bool X86::isVEXTRACT128Index(SDNode *N) {
4521   return isVEXTRACTIndex(N, 128);
4522 }
4523
4524 bool X86::isVEXTRACT256Index(SDNode *N) {
4525   return isVEXTRACTIndex(N, 256);
4526 }
4527
4528 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4529 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4530 /// Handles 128-bit and 256-bit.
4531 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4532   MVT VT = N->getSimpleValueType(0);
4533
4534   assert((VT.getSizeInBits() >= 128) &&
4535          "Unsupported vector type for PSHUF/SHUFP");
4536
4537   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4538   // independently on 128-bit lanes.
4539   unsigned NumElts = VT.getVectorNumElements();
4540   unsigned NumLanes = VT.getSizeInBits()/128;
4541   unsigned NumLaneElts = NumElts/NumLanes;
4542
4543   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4544          "Only supports 2, 4 or 8 elements per lane");
4545
4546   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4547   unsigned Mask = 0;
4548   for (unsigned i = 0; i != NumElts; ++i) {
4549     int Elt = N->getMaskElt(i);
4550     if (Elt < 0) continue;
4551     Elt &= NumLaneElts - 1;
4552     unsigned ShAmt = (i << Shift) % 8;
4553     Mask |= Elt << ShAmt;
4554   }
4555
4556   return Mask;
4557 }
4558
4559 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4560 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4561 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4562   MVT VT = N->getSimpleValueType(0);
4563
4564   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4565          "Unsupported vector type for PSHUFHW");
4566
4567   unsigned NumElts = VT.getVectorNumElements();
4568
4569   unsigned Mask = 0;
4570   for (unsigned l = 0; l != NumElts; l += 8) {
4571     // 8 nodes per lane, but we only care about the last 4.
4572     for (unsigned i = 0; i < 4; ++i) {
4573       int Elt = N->getMaskElt(l+i+4);
4574       if (Elt < 0) continue;
4575       Elt &= 0x3; // only 2-bits.
4576       Mask |= Elt << (i * 2);
4577     }
4578   }
4579
4580   return Mask;
4581 }
4582
4583 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4584 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4585 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4586   MVT VT = N->getSimpleValueType(0);
4587
4588   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4589          "Unsupported vector type for PSHUFHW");
4590
4591   unsigned NumElts = VT.getVectorNumElements();
4592
4593   unsigned Mask = 0;
4594   for (unsigned l = 0; l != NumElts; l += 8) {
4595     // 8 nodes per lane, but we only care about the first 4.
4596     for (unsigned i = 0; i < 4; ++i) {
4597       int Elt = N->getMaskElt(l+i);
4598       if (Elt < 0) continue;
4599       Elt &= 0x3; // only 2-bits
4600       Mask |= Elt << (i * 2);
4601     }
4602   }
4603
4604   return Mask;
4605 }
4606
4607 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4608 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4609 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4610   MVT VT = SVOp->getSimpleValueType(0);
4611   unsigned EltSize = VT.is512BitVector() ? 1 :
4612     VT.getVectorElementType().getSizeInBits() >> 3;
4613
4614   unsigned NumElts = VT.getVectorNumElements();
4615   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4616   unsigned NumLaneElts = NumElts/NumLanes;
4617
4618   int Val = 0;
4619   unsigned i;
4620   for (i = 0; i != NumElts; ++i) {
4621     Val = SVOp->getMaskElt(i);
4622     if (Val >= 0)
4623       break;
4624   }
4625   if (Val >= (int)NumElts)
4626     Val -= NumElts - NumLaneElts;
4627
4628   assert(Val - i > 0 && "PALIGNR imm should be positive");
4629   return (Val - i) * EltSize;
4630 }
4631
4632 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4633   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4634   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4635     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4636
4637   uint64_t Index =
4638     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4639
4640   MVT VecVT = N->getOperand(0).getSimpleValueType();
4641   MVT ElVT = VecVT.getVectorElementType();
4642
4643   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4644   return Index / NumElemsPerChunk;
4645 }
4646
4647 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4648   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4649   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4650     llvm_unreachable("Illegal insert subvector for VINSERT");
4651
4652   uint64_t Index =
4653     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4654
4655   MVT VecVT = N->getSimpleValueType(0);
4656   MVT ElVT = VecVT.getVectorElementType();
4657
4658   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4659   return Index / NumElemsPerChunk;
4660 }
4661
4662 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4663 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4664 /// and VINSERTI128 instructions.
4665 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4666   return getExtractVEXTRACTImmediate(N, 128);
4667 }
4668
4669 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4670 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4671 /// and VINSERTI64x4 instructions.
4672 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4673   return getExtractVEXTRACTImmediate(N, 256);
4674 }
4675
4676 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4677 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4678 /// and VINSERTI128 instructions.
4679 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4680   return getInsertVINSERTImmediate(N, 128);
4681 }
4682
4683 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4684 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4685 /// and VINSERTI64x4 instructions.
4686 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4687   return getInsertVINSERTImmediate(N, 256);
4688 }
4689
4690 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4691 /// constant +0.0.
4692 bool X86::isZeroNode(SDValue Elt) {
4693   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4694     return CN->isNullValue();
4695   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4696     return CFP->getValueAPF().isPosZero();
4697   return false;
4698 }
4699
4700 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4701 /// their permute mask.
4702 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4703                                     SelectionDAG &DAG) {
4704   MVT VT = SVOp->getSimpleValueType(0);
4705   unsigned NumElems = VT.getVectorNumElements();
4706   SmallVector<int, 8> MaskVec;
4707
4708   for (unsigned i = 0; i != NumElems; ++i) {
4709     int Idx = SVOp->getMaskElt(i);
4710     if (Idx >= 0) {
4711       if (Idx < (int)NumElems)
4712         Idx += NumElems;
4713       else
4714         Idx -= NumElems;
4715     }
4716     MaskVec.push_back(Idx);
4717   }
4718   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4719                               SVOp->getOperand(0), &MaskVec[0]);
4720 }
4721
4722 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4723 /// match movhlps. The lower half elements should come from upper half of
4724 /// V1 (and in order), and the upper half elements should come from the upper
4725 /// half of V2 (and in order).
4726 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4727   if (!VT.is128BitVector())
4728     return false;
4729   if (VT.getVectorNumElements() != 4)
4730     return false;
4731   for (unsigned i = 0, e = 2; i != e; ++i)
4732     if (!isUndefOrEqual(Mask[i], i+2))
4733       return false;
4734   for (unsigned i = 2; i != 4; ++i)
4735     if (!isUndefOrEqual(Mask[i], i+4))
4736       return false;
4737   return true;
4738 }
4739
4740 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4741 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4742 /// required.
4743 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4744   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4745     return false;
4746   N = N->getOperand(0).getNode();
4747   if (!ISD::isNON_EXTLoad(N))
4748     return false;
4749   if (LD)
4750     *LD = cast<LoadSDNode>(N);
4751   return true;
4752 }
4753
4754 // Test whether the given value is a vector value which will be legalized
4755 // into a load.
4756 static bool WillBeConstantPoolLoad(SDNode *N) {
4757   if (N->getOpcode() != ISD::BUILD_VECTOR)
4758     return false;
4759
4760   // Check for any non-constant elements.
4761   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4762     switch (N->getOperand(i).getNode()->getOpcode()) {
4763     case ISD::UNDEF:
4764     case ISD::ConstantFP:
4765     case ISD::Constant:
4766       break;
4767     default:
4768       return false;
4769     }
4770
4771   // Vectors of all-zeros and all-ones are materialized with special
4772   // instructions rather than being loaded.
4773   return !ISD::isBuildVectorAllZeros(N) &&
4774          !ISD::isBuildVectorAllOnes(N);
4775 }
4776
4777 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4778 /// match movlp{s|d}. The lower half elements should come from lower half of
4779 /// V1 (and in order), and the upper half elements should come from the upper
4780 /// half of V2 (and in order). And since V1 will become the source of the
4781 /// MOVLP, it must be either a vector load or a scalar load to vector.
4782 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4783                                ArrayRef<int> Mask, MVT VT) {
4784   if (!VT.is128BitVector())
4785     return false;
4786
4787   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4788     return false;
4789   // Is V2 is a vector load, don't do this transformation. We will try to use
4790   // load folding shufps op.
4791   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4792     return false;
4793
4794   unsigned NumElems = VT.getVectorNumElements();
4795
4796   if (NumElems != 2 && NumElems != 4)
4797     return false;
4798   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4799     if (!isUndefOrEqual(Mask[i], i))
4800       return false;
4801   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4802     if (!isUndefOrEqual(Mask[i], i+NumElems))
4803       return false;
4804   return true;
4805 }
4806
4807 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4808 /// all the same.
4809 static bool isSplatVector(SDNode *N) {
4810   if (N->getOpcode() != ISD::BUILD_VECTOR)
4811     return false;
4812
4813   SDValue SplatValue = N->getOperand(0);
4814   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4815     if (N->getOperand(i) != SplatValue)
4816       return false;
4817   return true;
4818 }
4819
4820 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4821 /// to an zero vector.
4822 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4823 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4824   SDValue V1 = N->getOperand(0);
4825   SDValue V2 = N->getOperand(1);
4826   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4827   for (unsigned i = 0; i != NumElems; ++i) {
4828     int Idx = N->getMaskElt(i);
4829     if (Idx >= (int)NumElems) {
4830       unsigned Opc = V2.getOpcode();
4831       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4832         continue;
4833       if (Opc != ISD::BUILD_VECTOR ||
4834           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4835         return false;
4836     } else if (Idx >= 0) {
4837       unsigned Opc = V1.getOpcode();
4838       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4839         continue;
4840       if (Opc != ISD::BUILD_VECTOR ||
4841           !X86::isZeroNode(V1.getOperand(Idx)))
4842         return false;
4843     }
4844   }
4845   return true;
4846 }
4847
4848 /// getZeroVector - Returns a vector of specified type with all zero elements.
4849 ///
4850 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4851                              SelectionDAG &DAG, SDLoc dl) {
4852   assert(VT.isVector() && "Expected a vector type");
4853
4854   // Always build SSE zero vectors as <4 x i32> bitcasted
4855   // to their dest type. This ensures they get CSE'd.
4856   SDValue Vec;
4857   if (VT.is128BitVector()) {  // SSE
4858     if (Subtarget->hasSSE2()) {  // SSE2
4859       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4860       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4861     } else { // SSE1
4862       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4863       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4864     }
4865   } else if (VT.is256BitVector()) { // AVX
4866     if (Subtarget->hasInt256()) { // AVX2
4867       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4868       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4869       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4870     } else {
4871       // 256-bit logic and arithmetic instructions in AVX are all
4872       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4873       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4874       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4875       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4876     }
4877   } else if (VT.is512BitVector()) { // AVX-512
4878       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4879       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4880                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4881       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4882   } else if (VT.getScalarType() == MVT::i1) {
4883     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4884     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4885     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4886     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4887   } else
4888     llvm_unreachable("Unexpected vector type");
4889
4890   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4891 }
4892
4893 /// getOnesVector - Returns a vector of specified type with all bits set.
4894 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4895 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4896 /// Then bitcast to their original type, ensuring they get CSE'd.
4897 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4898                              SDLoc dl) {
4899   assert(VT.isVector() && "Expected a vector type");
4900
4901   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4902   SDValue Vec;
4903   if (VT.is256BitVector()) {
4904     if (HasInt256) { // AVX2
4905       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4906       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4907     } else { // AVX
4908       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4909       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4910     }
4911   } else if (VT.is128BitVector()) {
4912     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4913   } else
4914     llvm_unreachable("Unexpected vector type");
4915
4916   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4917 }
4918
4919 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4920 /// that point to V2 points to its first element.
4921 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4922   for (unsigned i = 0; i != NumElems; ++i) {
4923     if (Mask[i] > (int)NumElems) {
4924       Mask[i] = NumElems;
4925     }
4926   }
4927 }
4928
4929 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4930 /// operation of specified width.
4931 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4932                        SDValue V2) {
4933   unsigned NumElems = VT.getVectorNumElements();
4934   SmallVector<int, 8> Mask;
4935   Mask.push_back(NumElems);
4936   for (unsigned i = 1; i != NumElems; ++i)
4937     Mask.push_back(i);
4938   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4939 }
4940
4941 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4942 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4943                           SDValue V2) {
4944   unsigned NumElems = VT.getVectorNumElements();
4945   SmallVector<int, 8> Mask;
4946   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4947     Mask.push_back(i);
4948     Mask.push_back(i + NumElems);
4949   }
4950   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4951 }
4952
4953 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4954 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4955                           SDValue V2) {
4956   unsigned NumElems = VT.getVectorNumElements();
4957   SmallVector<int, 8> Mask;
4958   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4959     Mask.push_back(i + Half);
4960     Mask.push_back(i + NumElems + Half);
4961   }
4962   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4963 }
4964
4965 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4966 // a generic shuffle instruction because the target has no such instructions.
4967 // Generate shuffles which repeat i16 and i8 several times until they can be
4968 // represented by v4f32 and then be manipulated by target suported shuffles.
4969 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4970   MVT VT = V.getSimpleValueType();
4971   int NumElems = VT.getVectorNumElements();
4972   SDLoc dl(V);
4973
4974   while (NumElems > 4) {
4975     if (EltNo < NumElems/2) {
4976       V = getUnpackl(DAG, dl, VT, V, V);
4977     } else {
4978       V = getUnpackh(DAG, dl, VT, V, V);
4979       EltNo -= NumElems/2;
4980     }
4981     NumElems >>= 1;
4982   }
4983   return V;
4984 }
4985
4986 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4987 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4988   MVT VT = V.getSimpleValueType();
4989   SDLoc dl(V);
4990
4991   if (VT.is128BitVector()) {
4992     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4993     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4994     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4995                              &SplatMask[0]);
4996   } else if (VT.is256BitVector()) {
4997     // To use VPERMILPS to splat scalars, the second half of indicies must
4998     // refer to the higher part, which is a duplication of the lower one,
4999     // because VPERMILPS can only handle in-lane permutations.
5000     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5001                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5002
5003     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5004     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5005                              &SplatMask[0]);
5006   } else
5007     llvm_unreachable("Vector size not supported");
5008
5009   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5010 }
5011
5012 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5013 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5014   MVT SrcVT = SV->getSimpleValueType(0);
5015   SDValue V1 = SV->getOperand(0);
5016   SDLoc dl(SV);
5017
5018   int EltNo = SV->getSplatIndex();
5019   int NumElems = SrcVT.getVectorNumElements();
5020   bool Is256BitVec = SrcVT.is256BitVector();
5021
5022   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5023          "Unknown how to promote splat for type");
5024
5025   // Extract the 128-bit part containing the splat element and update
5026   // the splat element index when it refers to the higher register.
5027   if (Is256BitVec) {
5028     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5029     if (EltNo >= NumElems/2)
5030       EltNo -= NumElems/2;
5031   }
5032
5033   // All i16 and i8 vector types can't be used directly by a generic shuffle
5034   // instruction because the target has no such instruction. Generate shuffles
5035   // which repeat i16 and i8 several times until they fit in i32, and then can
5036   // be manipulated by target suported shuffles.
5037   MVT EltVT = SrcVT.getVectorElementType();
5038   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5039     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5040
5041   // Recreate the 256-bit vector and place the same 128-bit vector
5042   // into the low and high part. This is necessary because we want
5043   // to use VPERM* to shuffle the vectors
5044   if (Is256BitVec) {
5045     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5046   }
5047
5048   return getLegalSplat(DAG, V1, EltNo);
5049 }
5050
5051 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5052 /// vector of zero or undef vector.  This produces a shuffle where the low
5053 /// element of V2 is swizzled into the zero/undef vector, landing at element
5054 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5055 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5056                                            bool IsZero,
5057                                            const X86Subtarget *Subtarget,
5058                                            SelectionDAG &DAG) {
5059   MVT VT = V2.getSimpleValueType();
5060   SDValue V1 = IsZero
5061     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5062   unsigned NumElems = VT.getVectorNumElements();
5063   SmallVector<int, 16> MaskVec;
5064   for (unsigned i = 0; i != NumElems; ++i)
5065     // If this is the insertion idx, put the low elt of V2 here.
5066     MaskVec.push_back(i == Idx ? NumElems : i);
5067   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5068 }
5069
5070 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5071 /// target specific opcode. Returns true if the Mask could be calculated.
5072 /// Sets IsUnary to true if only uses one source.
5073 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5074                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5075   unsigned NumElems = VT.getVectorNumElements();
5076   SDValue ImmN;
5077
5078   IsUnary = false;
5079   switch(N->getOpcode()) {
5080   case X86ISD::SHUFP:
5081     ImmN = N->getOperand(N->getNumOperands()-1);
5082     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5083     break;
5084   case X86ISD::UNPCKH:
5085     DecodeUNPCKHMask(VT, Mask);
5086     break;
5087   case X86ISD::UNPCKL:
5088     DecodeUNPCKLMask(VT, Mask);
5089     break;
5090   case X86ISD::MOVHLPS:
5091     DecodeMOVHLPSMask(NumElems, Mask);
5092     break;
5093   case X86ISD::MOVLHPS:
5094     DecodeMOVLHPSMask(NumElems, Mask);
5095     break;
5096   case X86ISD::PALIGNR:
5097     ImmN = N->getOperand(N->getNumOperands()-1);
5098     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5099     break;
5100   case X86ISD::PSHUFD:
5101   case X86ISD::VPERMILP:
5102     ImmN = N->getOperand(N->getNumOperands()-1);
5103     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5104     IsUnary = true;
5105     break;
5106   case X86ISD::PSHUFHW:
5107     ImmN = N->getOperand(N->getNumOperands()-1);
5108     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5109     IsUnary = true;
5110     break;
5111   case X86ISD::PSHUFLW:
5112     ImmN = N->getOperand(N->getNumOperands()-1);
5113     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5114     IsUnary = true;
5115     break;
5116   case X86ISD::VPERMI:
5117     ImmN = N->getOperand(N->getNumOperands()-1);
5118     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5119     IsUnary = true;
5120     break;
5121   case X86ISD::MOVSS:
5122   case X86ISD::MOVSD: {
5123     // The index 0 always comes from the first element of the second source,
5124     // this is why MOVSS and MOVSD are used in the first place. The other
5125     // elements come from the other positions of the first source vector
5126     Mask.push_back(NumElems);
5127     for (unsigned i = 1; i != NumElems; ++i) {
5128       Mask.push_back(i);
5129     }
5130     break;
5131   }
5132   case X86ISD::VPERM2X128:
5133     ImmN = N->getOperand(N->getNumOperands()-1);
5134     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5135     if (Mask.empty()) return false;
5136     break;
5137   case X86ISD::MOVDDUP:
5138   case X86ISD::MOVLHPD:
5139   case X86ISD::MOVLPD:
5140   case X86ISD::MOVLPS:
5141   case X86ISD::MOVSHDUP:
5142   case X86ISD::MOVSLDUP:
5143     // Not yet implemented
5144     return false;
5145   default: llvm_unreachable("unknown target shuffle node");
5146   }
5147
5148   return true;
5149 }
5150
5151 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5152 /// element of the result of the vector shuffle.
5153 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5154                                    unsigned Depth) {
5155   if (Depth == 6)
5156     return SDValue();  // Limit search depth.
5157
5158   SDValue V = SDValue(N, 0);
5159   EVT VT = V.getValueType();
5160   unsigned Opcode = V.getOpcode();
5161
5162   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5163   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5164     int Elt = SV->getMaskElt(Index);
5165
5166     if (Elt < 0)
5167       return DAG.getUNDEF(VT.getVectorElementType());
5168
5169     unsigned NumElems = VT.getVectorNumElements();
5170     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5171                                          : SV->getOperand(1);
5172     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5173   }
5174
5175   // Recurse into target specific vector shuffles to find scalars.
5176   if (isTargetShuffle(Opcode)) {
5177     MVT ShufVT = V.getSimpleValueType();
5178     unsigned NumElems = ShufVT.getVectorNumElements();
5179     SmallVector<int, 16> ShuffleMask;
5180     bool IsUnary;
5181
5182     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5183       return SDValue();
5184
5185     int Elt = ShuffleMask[Index];
5186     if (Elt < 0)
5187       return DAG.getUNDEF(ShufVT.getVectorElementType());
5188
5189     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5190                                          : N->getOperand(1);
5191     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5192                                Depth+1);
5193   }
5194
5195   // Actual nodes that may contain scalar elements
5196   if (Opcode == ISD::BITCAST) {
5197     V = V.getOperand(0);
5198     EVT SrcVT = V.getValueType();
5199     unsigned NumElems = VT.getVectorNumElements();
5200
5201     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5202       return SDValue();
5203   }
5204
5205   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5206     return (Index == 0) ? V.getOperand(0)
5207                         : DAG.getUNDEF(VT.getVectorElementType());
5208
5209   if (V.getOpcode() == ISD::BUILD_VECTOR)
5210     return V.getOperand(Index);
5211
5212   return SDValue();
5213 }
5214
5215 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5216 /// shuffle operation which come from a consecutively from a zero. The
5217 /// search can start in two different directions, from left or right.
5218 /// We count undefs as zeros until PreferredNum is reached.
5219 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5220                                          unsigned NumElems, bool ZerosFromLeft,
5221                                          SelectionDAG &DAG,
5222                                          unsigned PreferredNum = -1U) {
5223   unsigned NumZeros = 0;
5224   for (unsigned i = 0; i != NumElems; ++i) {
5225     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5226     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5227     if (!Elt.getNode())
5228       break;
5229
5230     if (X86::isZeroNode(Elt))
5231       ++NumZeros;
5232     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5233       NumZeros = std::min(NumZeros + 1, PreferredNum);
5234     else
5235       break;
5236   }
5237
5238   return NumZeros;
5239 }
5240
5241 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5242 /// correspond consecutively to elements from one of the vector operands,
5243 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5244 static
5245 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5246                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5247                               unsigned NumElems, unsigned &OpNum) {
5248   bool SeenV1 = false;
5249   bool SeenV2 = false;
5250
5251   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5252     int Idx = SVOp->getMaskElt(i);
5253     // Ignore undef indicies
5254     if (Idx < 0)
5255       continue;
5256
5257     if (Idx < (int)NumElems)
5258       SeenV1 = true;
5259     else
5260       SeenV2 = true;
5261
5262     // Only accept consecutive elements from the same vector
5263     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5264       return false;
5265   }
5266
5267   OpNum = SeenV1 ? 0 : 1;
5268   return true;
5269 }
5270
5271 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5272 /// logical left shift of a vector.
5273 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5274                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5275   unsigned NumElems =
5276     SVOp->getSimpleValueType(0).getVectorNumElements();
5277   unsigned NumZeros = getNumOfConsecutiveZeros(
5278       SVOp, NumElems, false /* check zeros from right */, DAG,
5279       SVOp->getMaskElt(0));
5280   unsigned OpSrc;
5281
5282   if (!NumZeros)
5283     return false;
5284
5285   // Considering the elements in the mask that are not consecutive zeros,
5286   // check if they consecutively come from only one of the source vectors.
5287   //
5288   //               V1 = {X, A, B, C}     0
5289   //                         \  \  \    /
5290   //   vector_shuffle V1, V2 <1, 2, 3, X>
5291   //
5292   if (!isShuffleMaskConsecutive(SVOp,
5293             0,                   // Mask Start Index
5294             NumElems-NumZeros,   // Mask End Index(exclusive)
5295             NumZeros,            // Where to start looking in the src vector
5296             NumElems,            // Number of elements in vector
5297             OpSrc))              // Which source operand ?
5298     return false;
5299
5300   isLeft = false;
5301   ShAmt = NumZeros;
5302   ShVal = SVOp->getOperand(OpSrc);
5303   return true;
5304 }
5305
5306 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5307 /// logical left shift of a vector.
5308 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5309                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5310   unsigned NumElems =
5311     SVOp->getSimpleValueType(0).getVectorNumElements();
5312   unsigned NumZeros = getNumOfConsecutiveZeros(
5313       SVOp, NumElems, true /* check zeros from left */, DAG,
5314       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5315   unsigned OpSrc;
5316
5317   if (!NumZeros)
5318     return false;
5319
5320   // Considering the elements in the mask that are not consecutive zeros,
5321   // check if they consecutively come from only one of the source vectors.
5322   //
5323   //                           0    { A, B, X, X } = V2
5324   //                          / \    /  /
5325   //   vector_shuffle V1, V2 <X, X, 4, 5>
5326   //
5327   if (!isShuffleMaskConsecutive(SVOp,
5328             NumZeros,     // Mask Start Index
5329             NumElems,     // Mask End Index(exclusive)
5330             0,            // Where to start looking in the src vector
5331             NumElems,     // Number of elements in vector
5332             OpSrc))       // Which source operand ?
5333     return false;
5334
5335   isLeft = true;
5336   ShAmt = NumZeros;
5337   ShVal = SVOp->getOperand(OpSrc);
5338   return true;
5339 }
5340
5341 /// isVectorShift - Returns true if the shuffle can be implemented as a
5342 /// logical left or right shift of a vector.
5343 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5344                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5345   // Although the logic below support any bitwidth size, there are no
5346   // shift instructions which handle more than 128-bit vectors.
5347   if (!SVOp->getSimpleValueType(0).is128BitVector())
5348     return false;
5349
5350   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5351       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5352     return true;
5353
5354   return false;
5355 }
5356
5357 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5358 ///
5359 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5360                                        unsigned NumNonZero, unsigned NumZero,
5361                                        SelectionDAG &DAG,
5362                                        const X86Subtarget* Subtarget,
5363                                        const TargetLowering &TLI) {
5364   if (NumNonZero > 8)
5365     return SDValue();
5366
5367   SDLoc dl(Op);
5368   SDValue V;
5369   bool First = true;
5370   for (unsigned i = 0; i < 16; ++i) {
5371     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5372     if (ThisIsNonZero && First) {
5373       if (NumZero)
5374         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5375       else
5376         V = DAG.getUNDEF(MVT::v8i16);
5377       First = false;
5378     }
5379
5380     if ((i & 1) != 0) {
5381       SDValue ThisElt, LastElt;
5382       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5383       if (LastIsNonZero) {
5384         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5385                               MVT::i16, Op.getOperand(i-1));
5386       }
5387       if (ThisIsNonZero) {
5388         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5389         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5390                               ThisElt, DAG.getConstant(8, MVT::i8));
5391         if (LastIsNonZero)
5392           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5393       } else
5394         ThisElt = LastElt;
5395
5396       if (ThisElt.getNode())
5397         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5398                         DAG.getIntPtrConstant(i/2));
5399     }
5400   }
5401
5402   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5403 }
5404
5405 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5406 ///
5407 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5408                                      unsigned NumNonZero, unsigned NumZero,
5409                                      SelectionDAG &DAG,
5410                                      const X86Subtarget* Subtarget,
5411                                      const TargetLowering &TLI) {
5412   if (NumNonZero > 4)
5413     return SDValue();
5414
5415   SDLoc dl(Op);
5416   SDValue V;
5417   bool First = true;
5418   for (unsigned i = 0; i < 8; ++i) {
5419     bool isNonZero = (NonZeros & (1 << i)) != 0;
5420     if (isNonZero) {
5421       if (First) {
5422         if (NumZero)
5423           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5424         else
5425           V = DAG.getUNDEF(MVT::v8i16);
5426         First = false;
5427       }
5428       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5429                       MVT::v8i16, V, Op.getOperand(i),
5430                       DAG.getIntPtrConstant(i));
5431     }
5432   }
5433
5434   return V;
5435 }
5436
5437 /// getVShift - Return a vector logical shift node.
5438 ///
5439 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5440                          unsigned NumBits, SelectionDAG &DAG,
5441                          const TargetLowering &TLI, SDLoc dl) {
5442   assert(VT.is128BitVector() && "Unknown type for VShift");
5443   EVT ShVT = MVT::v2i64;
5444   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5445   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5446   return DAG.getNode(ISD::BITCAST, dl, VT,
5447                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5448                              DAG.getConstant(NumBits,
5449                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5450 }
5451
5452 static SDValue
5453 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5454
5455   // Check if the scalar load can be widened into a vector load. And if
5456   // the address is "base + cst" see if the cst can be "absorbed" into
5457   // the shuffle mask.
5458   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5459     SDValue Ptr = LD->getBasePtr();
5460     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5461       return SDValue();
5462     EVT PVT = LD->getValueType(0);
5463     if (PVT != MVT::i32 && PVT != MVT::f32)
5464       return SDValue();
5465
5466     int FI = -1;
5467     int64_t Offset = 0;
5468     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5469       FI = FINode->getIndex();
5470       Offset = 0;
5471     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5472                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5473       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5474       Offset = Ptr.getConstantOperandVal(1);
5475       Ptr = Ptr.getOperand(0);
5476     } else {
5477       return SDValue();
5478     }
5479
5480     // FIXME: 256-bit vector instructions don't require a strict alignment,
5481     // improve this code to support it better.
5482     unsigned RequiredAlign = VT.getSizeInBits()/8;
5483     SDValue Chain = LD->getChain();
5484     // Make sure the stack object alignment is at least 16 or 32.
5485     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5486     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5487       if (MFI->isFixedObjectIndex(FI)) {
5488         // Can't change the alignment. FIXME: It's possible to compute
5489         // the exact stack offset and reference FI + adjust offset instead.
5490         // If someone *really* cares about this. That's the way to implement it.
5491         return SDValue();
5492       } else {
5493         MFI->setObjectAlignment(FI, RequiredAlign);
5494       }
5495     }
5496
5497     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5498     // Ptr + (Offset & ~15).
5499     if (Offset < 0)
5500       return SDValue();
5501     if ((Offset % RequiredAlign) & 3)
5502       return SDValue();
5503     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5504     if (StartOffset)
5505       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5506                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5507
5508     int EltNo = (Offset - StartOffset) >> 2;
5509     unsigned NumElems = VT.getVectorNumElements();
5510
5511     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5512     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5513                              LD->getPointerInfo().getWithOffset(StartOffset),
5514                              false, false, false, 0);
5515
5516     SmallVector<int, 8> Mask;
5517     for (unsigned i = 0; i != NumElems; ++i)
5518       Mask.push_back(EltNo);
5519
5520     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5521   }
5522
5523   return SDValue();
5524 }
5525
5526 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5527 /// vector of type 'VT', see if the elements can be replaced by a single large
5528 /// load which has the same value as a build_vector whose operands are 'elts'.
5529 ///
5530 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5531 ///
5532 /// FIXME: we'd also like to handle the case where the last elements are zero
5533 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5534 /// There's even a handy isZeroNode for that purpose.
5535 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5536                                         SDLoc &DL, SelectionDAG &DAG,
5537                                         bool isAfterLegalize) {
5538   EVT EltVT = VT.getVectorElementType();
5539   unsigned NumElems = Elts.size();
5540
5541   LoadSDNode *LDBase = nullptr;
5542   unsigned LastLoadedElt = -1U;
5543
5544   // For each element in the initializer, see if we've found a load or an undef.
5545   // If we don't find an initial load element, or later load elements are
5546   // non-consecutive, bail out.
5547   for (unsigned i = 0; i < NumElems; ++i) {
5548     SDValue Elt = Elts[i];
5549
5550     if (!Elt.getNode() ||
5551         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5552       return SDValue();
5553     if (!LDBase) {
5554       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5555         return SDValue();
5556       LDBase = cast<LoadSDNode>(Elt.getNode());
5557       LastLoadedElt = i;
5558       continue;
5559     }
5560     if (Elt.getOpcode() == ISD::UNDEF)
5561       continue;
5562
5563     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5564     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5565       return SDValue();
5566     LastLoadedElt = i;
5567   }
5568
5569   // If we have found an entire vector of loads and undefs, then return a large
5570   // load of the entire vector width starting at the base pointer.  If we found
5571   // consecutive loads for the low half, generate a vzext_load node.
5572   if (LastLoadedElt == NumElems - 1) {
5573
5574     if (isAfterLegalize &&
5575         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5576       return SDValue();
5577
5578     SDValue NewLd = SDValue();
5579
5580     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5581       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5582                           LDBase->getPointerInfo(),
5583                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5584                           LDBase->isInvariant(), 0);
5585     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5586                         LDBase->getPointerInfo(),
5587                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5588                         LDBase->isInvariant(), LDBase->getAlignment());
5589
5590     if (LDBase->hasAnyUseOfValue(1)) {
5591       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5592                                      SDValue(LDBase, 1),
5593                                      SDValue(NewLd.getNode(), 1));
5594       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5595       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5596                              SDValue(NewLd.getNode(), 1));
5597     }
5598
5599     return NewLd;
5600   }
5601   if (NumElems == 4 && LastLoadedElt == 1 &&
5602       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5603     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5604     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5605     SDValue ResNode =
5606         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5607                                 LDBase->getPointerInfo(),
5608                                 LDBase->getAlignment(),
5609                                 false/*isVolatile*/, true/*ReadMem*/,
5610                                 false/*WriteMem*/);
5611
5612     // Make sure the newly-created LOAD is in the same position as LDBase in
5613     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5614     // update uses of LDBase's output chain to use the TokenFactor.
5615     if (LDBase->hasAnyUseOfValue(1)) {
5616       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5617                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5618       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5619       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5620                              SDValue(ResNode.getNode(), 1));
5621     }
5622
5623     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5624   }
5625   return SDValue();
5626 }
5627
5628 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5629 /// to generate a splat value for the following cases:
5630 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5631 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5632 /// a scalar load, or a constant.
5633 /// The VBROADCAST node is returned when a pattern is found,
5634 /// or SDValue() otherwise.
5635 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5636                                     SelectionDAG &DAG) {
5637   if (!Subtarget->hasFp256())
5638     return SDValue();
5639
5640   MVT VT = Op.getSimpleValueType();
5641   SDLoc dl(Op);
5642
5643   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5644          "Unsupported vector type for broadcast.");
5645
5646   SDValue Ld;
5647   bool ConstSplatVal;
5648
5649   switch (Op.getOpcode()) {
5650     default:
5651       // Unknown pattern found.
5652       return SDValue();
5653
5654     case ISD::BUILD_VECTOR: {
5655       // The BUILD_VECTOR node must be a splat.
5656       if (!isSplatVector(Op.getNode()))
5657         return SDValue();
5658
5659       Ld = Op.getOperand(0);
5660       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5661                      Ld.getOpcode() == ISD::ConstantFP);
5662
5663       // The suspected load node has several users. Make sure that all
5664       // of its users are from the BUILD_VECTOR node.
5665       // Constants may have multiple users.
5666       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5667         return SDValue();
5668       break;
5669     }
5670
5671     case ISD::VECTOR_SHUFFLE: {
5672       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5673
5674       // Shuffles must have a splat mask where the first element is
5675       // broadcasted.
5676       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5677         return SDValue();
5678
5679       SDValue Sc = Op.getOperand(0);
5680       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5681           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5682
5683         if (!Subtarget->hasInt256())
5684           return SDValue();
5685
5686         // Use the register form of the broadcast instruction available on AVX2.
5687         if (VT.getSizeInBits() >= 256)
5688           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5689         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5690       }
5691
5692       Ld = Sc.getOperand(0);
5693       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5694                        Ld.getOpcode() == ISD::ConstantFP);
5695
5696       // The scalar_to_vector node and the suspected
5697       // load node must have exactly one user.
5698       // Constants may have multiple users.
5699
5700       // AVX-512 has register version of the broadcast
5701       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5702         Ld.getValueType().getSizeInBits() >= 32;
5703       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5704           !hasRegVer))
5705         return SDValue();
5706       break;
5707     }
5708   }
5709
5710   bool IsGE256 = (VT.getSizeInBits() >= 256);
5711
5712   // Handle the broadcasting a single constant scalar from the constant pool
5713   // into a vector. On Sandybridge it is still better to load a constant vector
5714   // from the constant pool and not to broadcast it from a scalar.
5715   if (ConstSplatVal && Subtarget->hasInt256()) {
5716     EVT CVT = Ld.getValueType();
5717     assert(!CVT.isVector() && "Must not broadcast a vector type");
5718     unsigned ScalarSize = CVT.getSizeInBits();
5719
5720     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5721       const Constant *C = nullptr;
5722       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5723         C = CI->getConstantIntValue();
5724       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5725         C = CF->getConstantFPValue();
5726
5727       assert(C && "Invalid constant type");
5728
5729       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5730       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5731       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5732       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5733                        MachinePointerInfo::getConstantPool(),
5734                        false, false, false, Alignment);
5735
5736       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5737     }
5738   }
5739
5740   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5741   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5742
5743   // Handle AVX2 in-register broadcasts.
5744   if (!IsLoad && Subtarget->hasInt256() &&
5745       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5746     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5747
5748   // The scalar source must be a normal load.
5749   if (!IsLoad)
5750     return SDValue();
5751
5752   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5753     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5754
5755   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5756   // double since there is no vbroadcastsd xmm
5757   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5758     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5759       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5760   }
5761
5762   // Unsupported broadcast.
5763   return SDValue();
5764 }
5765
5766 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5767 /// underlying vector and index.
5768 ///
5769 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5770 /// index.
5771 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5772                                          SDValue ExtIdx) {
5773   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5774   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5775     return Idx;
5776
5777   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5778   // lowered this:
5779   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5780   // to:
5781   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5782   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5783   //                           undef)
5784   //                       Constant<0>)
5785   // In this case the vector is the extract_subvector expression and the index
5786   // is 2, as specified by the shuffle.
5787   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5788   SDValue ShuffleVec = SVOp->getOperand(0);
5789   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5790   assert(ShuffleVecVT.getVectorElementType() ==
5791          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5792
5793   int ShuffleIdx = SVOp->getMaskElt(Idx);
5794   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5795     ExtractedFromVec = ShuffleVec;
5796     return ShuffleIdx;
5797   }
5798   return Idx;
5799 }
5800
5801 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5802   MVT VT = Op.getSimpleValueType();
5803
5804   // Skip if insert_vec_elt is not supported.
5805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5806   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5807     return SDValue();
5808
5809   SDLoc DL(Op);
5810   unsigned NumElems = Op.getNumOperands();
5811
5812   SDValue VecIn1;
5813   SDValue VecIn2;
5814   SmallVector<unsigned, 4> InsertIndices;
5815   SmallVector<int, 8> Mask(NumElems, -1);
5816
5817   for (unsigned i = 0; i != NumElems; ++i) {
5818     unsigned Opc = Op.getOperand(i).getOpcode();
5819
5820     if (Opc == ISD::UNDEF)
5821       continue;
5822
5823     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5824       // Quit if more than 1 elements need inserting.
5825       if (InsertIndices.size() > 1)
5826         return SDValue();
5827
5828       InsertIndices.push_back(i);
5829       continue;
5830     }
5831
5832     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5833     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5834     // Quit if non-constant index.
5835     if (!isa<ConstantSDNode>(ExtIdx))
5836       return SDValue();
5837     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5838
5839     // Quit if extracted from vector of different type.
5840     if (ExtractedFromVec.getValueType() != VT)
5841       return SDValue();
5842
5843     if (!VecIn1.getNode())
5844       VecIn1 = ExtractedFromVec;
5845     else if (VecIn1 != ExtractedFromVec) {
5846       if (!VecIn2.getNode())
5847         VecIn2 = ExtractedFromVec;
5848       else if (VecIn2 != ExtractedFromVec)
5849         // Quit if more than 2 vectors to shuffle
5850         return SDValue();
5851     }
5852
5853     if (ExtractedFromVec == VecIn1)
5854       Mask[i] = Idx;
5855     else if (ExtractedFromVec == VecIn2)
5856       Mask[i] = Idx + NumElems;
5857   }
5858
5859   if (!VecIn1.getNode())
5860     return SDValue();
5861
5862   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5863   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5864   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5865     unsigned Idx = InsertIndices[i];
5866     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5867                      DAG.getIntPtrConstant(Idx));
5868   }
5869
5870   return NV;
5871 }
5872
5873 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5874 SDValue
5875 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5876
5877   MVT VT = Op.getSimpleValueType();
5878   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5879          "Unexpected type in LowerBUILD_VECTORvXi1!");
5880
5881   SDLoc dl(Op);
5882   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5883     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5884     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5885     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5886   }
5887
5888   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5889     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5890     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5891     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5892   }
5893
5894   bool AllContants = true;
5895   uint64_t Immediate = 0;
5896   int NonConstIdx = -1;
5897   bool IsSplat = true;
5898   unsigned NumNonConsts = 0;
5899   unsigned NumConsts = 0;
5900   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5901     SDValue In = Op.getOperand(idx);
5902     if (In.getOpcode() == ISD::UNDEF)
5903       continue;
5904     if (!isa<ConstantSDNode>(In)) {
5905       AllContants = false;
5906       NonConstIdx = idx;
5907       NumNonConsts++;
5908     }
5909     else {
5910       NumConsts++;
5911       if (cast<ConstantSDNode>(In)->getZExtValue())
5912       Immediate |= (1ULL << idx);
5913     }
5914     if (In != Op.getOperand(0))
5915       IsSplat = false;
5916   }
5917
5918   if (AllContants) {
5919     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5920       DAG.getConstant(Immediate, MVT::i16));
5921     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5922                        DAG.getIntPtrConstant(0));
5923   }
5924
5925   if (NumNonConsts == 1 && NonConstIdx != 0) {
5926     SDValue DstVec;
5927     if (NumConsts) {
5928       SDValue VecAsImm = DAG.getConstant(Immediate,
5929                                          MVT::getIntegerVT(VT.getSizeInBits()));
5930       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5931     }
5932     else 
5933       DstVec = DAG.getUNDEF(VT);
5934     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5935                        Op.getOperand(NonConstIdx),
5936                        DAG.getIntPtrConstant(NonConstIdx));
5937   }
5938   if (!IsSplat && (NonConstIdx != 0))
5939     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5940   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5941   SDValue Select;
5942   if (IsSplat)
5943     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5944                           DAG.getConstant(-1, SelectVT),
5945                           DAG.getConstant(0, SelectVT));
5946   else
5947     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5948                          DAG.getConstant((Immediate | 1), SelectVT),
5949                          DAG.getConstant(Immediate, SelectVT));
5950   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5951 }
5952
5953 SDValue
5954 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5955   SDLoc dl(Op);
5956
5957   MVT VT = Op.getSimpleValueType();
5958   MVT ExtVT = VT.getVectorElementType();
5959   unsigned NumElems = Op.getNumOperands();
5960
5961   // Generate vectors for predicate vectors.
5962   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5963     return LowerBUILD_VECTORvXi1(Op, DAG);
5964
5965   // Vectors containing all zeros can be matched by pxor and xorps later
5966   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5967     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5968     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5969     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5970       return Op;
5971
5972     return getZeroVector(VT, Subtarget, DAG, dl);
5973   }
5974
5975   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5976   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5977   // vpcmpeqd on 256-bit vectors.
5978   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5979     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5980       return Op;
5981
5982     if (!VT.is512BitVector())
5983       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5984   }
5985
5986   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5987   if (Broadcast.getNode())
5988     return Broadcast;
5989
5990   unsigned EVTBits = ExtVT.getSizeInBits();
5991
5992   unsigned NumZero  = 0;
5993   unsigned NumNonZero = 0;
5994   unsigned NonZeros = 0;
5995   bool IsAllConstants = true;
5996   SmallSet<SDValue, 8> Values;
5997   for (unsigned i = 0; i < NumElems; ++i) {
5998     SDValue Elt = Op.getOperand(i);
5999     if (Elt.getOpcode() == ISD::UNDEF)
6000       continue;
6001     Values.insert(Elt);
6002     if (Elt.getOpcode() != ISD::Constant &&
6003         Elt.getOpcode() != ISD::ConstantFP)
6004       IsAllConstants = false;
6005     if (X86::isZeroNode(Elt))
6006       NumZero++;
6007     else {
6008       NonZeros |= (1 << i);
6009       NumNonZero++;
6010     }
6011   }
6012
6013   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6014   if (NumNonZero == 0)
6015     return DAG.getUNDEF(VT);
6016
6017   // Special case for single non-zero, non-undef, element.
6018   if (NumNonZero == 1) {
6019     unsigned Idx = countTrailingZeros(NonZeros);
6020     SDValue Item = Op.getOperand(Idx);
6021
6022     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6023     // the value are obviously zero, truncate the value to i32 and do the
6024     // insertion that way.  Only do this if the value is non-constant or if the
6025     // value is a constant being inserted into element 0.  It is cheaper to do
6026     // a constant pool load than it is to do a movd + shuffle.
6027     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6028         (!IsAllConstants || Idx == 0)) {
6029       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6030         // Handle SSE only.
6031         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6032         EVT VecVT = MVT::v4i32;
6033         unsigned VecElts = 4;
6034
6035         // Truncate the value (which may itself be a constant) to i32, and
6036         // convert it to a vector with movd (S2V+shuffle to zero extend).
6037         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6038         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6039         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6040
6041         // Now we have our 32-bit value zero extended in the low element of
6042         // a vector.  If Idx != 0, swizzle it into place.
6043         if (Idx != 0) {
6044           SmallVector<int, 4> Mask;
6045           Mask.push_back(Idx);
6046           for (unsigned i = 1; i != VecElts; ++i)
6047             Mask.push_back(i);
6048           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6049                                       &Mask[0]);
6050         }
6051         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6052       }
6053     }
6054
6055     // If we have a constant or non-constant insertion into the low element of
6056     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6057     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6058     // depending on what the source datatype is.
6059     if (Idx == 0) {
6060       if (NumZero == 0)
6061         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6062
6063       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6064           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6065         if (VT.is256BitVector() || VT.is512BitVector()) {
6066           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6067           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6068                              Item, DAG.getIntPtrConstant(0));
6069         }
6070         assert(VT.is128BitVector() && "Expected an SSE value type!");
6071         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6072         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6073         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6074       }
6075
6076       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6077         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6078         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6079         if (VT.is256BitVector()) {
6080           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6081           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6082         } else {
6083           assert(VT.is128BitVector() && "Expected an SSE value type!");
6084           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6085         }
6086         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6087       }
6088     }
6089
6090     // Is it a vector logical left shift?
6091     if (NumElems == 2 && Idx == 1 &&
6092         X86::isZeroNode(Op.getOperand(0)) &&
6093         !X86::isZeroNode(Op.getOperand(1))) {
6094       unsigned NumBits = VT.getSizeInBits();
6095       return getVShift(true, VT,
6096                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6097                                    VT, Op.getOperand(1)),
6098                        NumBits/2, DAG, *this, dl);
6099     }
6100
6101     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6102       return SDValue();
6103
6104     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6105     // is a non-constant being inserted into an element other than the low one,
6106     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6107     // movd/movss) to move this into the low element, then shuffle it into
6108     // place.
6109     if (EVTBits == 32) {
6110       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6111
6112       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6113       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6114       SmallVector<int, 8> MaskVec;
6115       for (unsigned i = 0; i != NumElems; ++i)
6116         MaskVec.push_back(i == Idx ? 0 : 1);
6117       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6118     }
6119   }
6120
6121   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6122   if (Values.size() == 1) {
6123     if (EVTBits == 32) {
6124       // Instead of a shuffle like this:
6125       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6126       // Check if it's possible to issue this instead.
6127       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6128       unsigned Idx = countTrailingZeros(NonZeros);
6129       SDValue Item = Op.getOperand(Idx);
6130       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6131         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6132     }
6133     return SDValue();
6134   }
6135
6136   // A vector full of immediates; various special cases are already
6137   // handled, so this is best done with a single constant-pool load.
6138   if (IsAllConstants)
6139     return SDValue();
6140
6141   // For AVX-length vectors, build the individual 128-bit pieces and use
6142   // shuffles to put them in place.
6143   if (VT.is256BitVector() || VT.is512BitVector()) {
6144     SmallVector<SDValue, 64> V;
6145     for (unsigned i = 0; i != NumElems; ++i)
6146       V.push_back(Op.getOperand(i));
6147
6148     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6149
6150     // Build both the lower and upper subvector.
6151     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6152                                 makeArrayRef(&V[0], NumElems/2));
6153     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6154                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6155
6156     // Recreate the wider vector with the lower and upper part.
6157     if (VT.is256BitVector())
6158       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6159     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6160   }
6161
6162   // Let legalizer expand 2-wide build_vectors.
6163   if (EVTBits == 64) {
6164     if (NumNonZero == 1) {
6165       // One half is zero or undef.
6166       unsigned Idx = countTrailingZeros(NonZeros);
6167       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6168                                  Op.getOperand(Idx));
6169       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6170     }
6171     return SDValue();
6172   }
6173
6174   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6175   if (EVTBits == 8 && NumElems == 16) {
6176     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6177                                         Subtarget, *this);
6178     if (V.getNode()) return V;
6179   }
6180
6181   if (EVTBits == 16 && NumElems == 8) {
6182     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6183                                       Subtarget, *this);
6184     if (V.getNode()) return V;
6185   }
6186
6187   // If element VT is == 32 bits, turn it into a number of shuffles.
6188   SmallVector<SDValue, 8> V(NumElems);
6189   if (NumElems == 4 && NumZero > 0) {
6190     for (unsigned i = 0; i < 4; ++i) {
6191       bool isZero = !(NonZeros & (1 << i));
6192       if (isZero)
6193         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6194       else
6195         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6196     }
6197
6198     for (unsigned i = 0; i < 2; ++i) {
6199       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6200         default: break;
6201         case 0:
6202           V[i] = V[i*2];  // Must be a zero vector.
6203           break;
6204         case 1:
6205           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6206           break;
6207         case 2:
6208           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6209           break;
6210         case 3:
6211           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6212           break;
6213       }
6214     }
6215
6216     bool Reverse1 = (NonZeros & 0x3) == 2;
6217     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6218     int MaskVec[] = {
6219       Reverse1 ? 1 : 0,
6220       Reverse1 ? 0 : 1,
6221       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6222       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6223     };
6224     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6225   }
6226
6227   if (Values.size() > 1 && VT.is128BitVector()) {
6228     // Check for a build vector of consecutive loads.
6229     for (unsigned i = 0; i < NumElems; ++i)
6230       V[i] = Op.getOperand(i);
6231
6232     // Check for elements which are consecutive loads.
6233     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6234     if (LD.getNode())
6235       return LD;
6236
6237     // Check for a build vector from mostly shuffle plus few inserting.
6238     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6239     if (Sh.getNode())
6240       return Sh;
6241
6242     // For SSE 4.1, use insertps to put the high elements into the low element.
6243     if (getSubtarget()->hasSSE41()) {
6244       SDValue Result;
6245       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6246         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6247       else
6248         Result = DAG.getUNDEF(VT);
6249
6250       for (unsigned i = 1; i < NumElems; ++i) {
6251         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6252         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6253                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6254       }
6255       return Result;
6256     }
6257
6258     // Otherwise, expand into a number of unpckl*, start by extending each of
6259     // our (non-undef) elements to the full vector width with the element in the
6260     // bottom slot of the vector (which generates no code for SSE).
6261     for (unsigned i = 0; i < NumElems; ++i) {
6262       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6263         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6264       else
6265         V[i] = DAG.getUNDEF(VT);
6266     }
6267
6268     // Next, we iteratively mix elements, e.g. for v4f32:
6269     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6270     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6271     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6272     unsigned EltStride = NumElems >> 1;
6273     while (EltStride != 0) {
6274       for (unsigned i = 0; i < EltStride; ++i) {
6275         // If V[i+EltStride] is undef and this is the first round of mixing,
6276         // then it is safe to just drop this shuffle: V[i] is already in the
6277         // right place, the one element (since it's the first round) being
6278         // inserted as undef can be dropped.  This isn't safe for successive
6279         // rounds because they will permute elements within both vectors.
6280         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6281             EltStride == NumElems/2)
6282           continue;
6283
6284         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6285       }
6286       EltStride >>= 1;
6287     }
6288     return V[0];
6289   }
6290   return SDValue();
6291 }
6292
6293 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6294 // to create 256-bit vectors from two other 128-bit ones.
6295 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6296   SDLoc dl(Op);
6297   MVT ResVT = Op.getSimpleValueType();
6298
6299   assert((ResVT.is256BitVector() ||
6300           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6301
6302   SDValue V1 = Op.getOperand(0);
6303   SDValue V2 = Op.getOperand(1);
6304   unsigned NumElems = ResVT.getVectorNumElements();
6305   if(ResVT.is256BitVector())
6306     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6307
6308   if (Op.getNumOperands() == 4) {
6309     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6310                                 ResVT.getVectorNumElements()/2);
6311     SDValue V3 = Op.getOperand(2);
6312     SDValue V4 = Op.getOperand(3);
6313     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6314       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6315   }
6316   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6317 }
6318
6319 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6320   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6321   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6322          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6323           Op.getNumOperands() == 4)));
6324
6325   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6326   // from two other 128-bit ones.
6327
6328   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6329   return LowerAVXCONCAT_VECTORS(Op, DAG);
6330 }
6331
6332 // Try to lower a shuffle node into a simple blend instruction.
6333 static SDValue
6334 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6335                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6336   SDValue V1 = SVOp->getOperand(0);
6337   SDValue V2 = SVOp->getOperand(1);
6338   SDLoc dl(SVOp);
6339   MVT VT = SVOp->getSimpleValueType(0);
6340   MVT EltVT = VT.getVectorElementType();
6341   unsigned NumElems = VT.getVectorNumElements();
6342
6343   // There is no blend with immediate in AVX-512.
6344   if (VT.is512BitVector())
6345     return SDValue();
6346
6347   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6348     return SDValue();
6349   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6350     return SDValue();
6351
6352   // Check the mask for BLEND and build the value.
6353   unsigned MaskValue = 0;
6354   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6355   unsigned NumLanes = (NumElems-1)/8 + 1;
6356   unsigned NumElemsInLane = NumElems / NumLanes;
6357
6358   // Blend for v16i16 should be symetric for the both lanes.
6359   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6360
6361     int SndLaneEltIdx = (NumLanes == 2) ?
6362       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6363     int EltIdx = SVOp->getMaskElt(i);
6364
6365     if ((EltIdx < 0 || EltIdx == (int)i) &&
6366         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6367       continue;
6368
6369     if (((unsigned)EltIdx == (i + NumElems)) &&
6370         (SndLaneEltIdx < 0 ||
6371          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6372       MaskValue |= (1<<i);
6373     else
6374       return SDValue();
6375   }
6376
6377   // Convert i32 vectors to floating point if it is not AVX2.
6378   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6379   MVT BlendVT = VT;
6380   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6381     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6382                                NumElems);
6383     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6384     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6385   }
6386
6387   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6388                             DAG.getConstant(MaskValue, MVT::i32));
6389   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6390 }
6391
6392 /// In vector type \p VT, return true if the element at index \p InputIdx
6393 /// falls on a different 128-bit lane than \p OutputIdx.
6394 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6395                                      unsigned OutputIdx) {
6396   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6397   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6398 }
6399
6400 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6401 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6402 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6403 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6404 /// zero.
6405 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6406                          SelectionDAG &DAG) {
6407   MVT VT = V1.getSimpleValueType();
6408   assert(VT.is128BitVector() || VT.is256BitVector());
6409
6410   MVT EltVT = VT.getVectorElementType();
6411   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6412   unsigned NumElts = VT.getVectorNumElements();
6413
6414   SmallVector<SDValue, 32> PshufbMask;
6415   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6416     int InputIdx = MaskVals[OutputIdx];
6417     unsigned InputByteIdx;
6418
6419     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6420       InputByteIdx = 0x80;
6421     else {
6422       // Cross lane is not allowed.
6423       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6424         return SDValue();
6425       InputByteIdx = InputIdx * EltSizeInBytes;
6426       // Index is an byte offset within the 128-bit lane.
6427       InputByteIdx &= 0xf;
6428     }
6429
6430     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6431       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6432       if (InputByteIdx != 0x80)
6433         ++InputByteIdx;
6434     }
6435   }
6436
6437   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6438   if (ShufVT != VT)
6439     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6440   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6441                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6442 }
6443
6444 // v8i16 shuffles - Prefer shuffles in the following order:
6445 // 1. [all]   pshuflw, pshufhw, optional move
6446 // 2. [ssse3] 1 x pshufb
6447 // 3. [ssse3] 2 x pshufb + 1 x por
6448 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6449 static SDValue
6450 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6451                          SelectionDAG &DAG) {
6452   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6453   SDValue V1 = SVOp->getOperand(0);
6454   SDValue V2 = SVOp->getOperand(1);
6455   SDLoc dl(SVOp);
6456   SmallVector<int, 8> MaskVals;
6457
6458   // Determine if more than 1 of the words in each of the low and high quadwords
6459   // of the result come from the same quadword of one of the two inputs.  Undef
6460   // mask values count as coming from any quadword, for better codegen.
6461   //
6462   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6463   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6464   unsigned LoQuad[] = { 0, 0, 0, 0 };
6465   unsigned HiQuad[] = { 0, 0, 0, 0 };
6466   // Indices of quads used.
6467   std::bitset<4> InputQuads;
6468   for (unsigned i = 0; i < 8; ++i) {
6469     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6470     int EltIdx = SVOp->getMaskElt(i);
6471     MaskVals.push_back(EltIdx);
6472     if (EltIdx < 0) {
6473       ++Quad[0];
6474       ++Quad[1];
6475       ++Quad[2];
6476       ++Quad[3];
6477       continue;
6478     }
6479     ++Quad[EltIdx / 4];
6480     InputQuads.set(EltIdx / 4);
6481   }
6482
6483   int BestLoQuad = -1;
6484   unsigned MaxQuad = 1;
6485   for (unsigned i = 0; i < 4; ++i) {
6486     if (LoQuad[i] > MaxQuad) {
6487       BestLoQuad = i;
6488       MaxQuad = LoQuad[i];
6489     }
6490   }
6491
6492   int BestHiQuad = -1;
6493   MaxQuad = 1;
6494   for (unsigned i = 0; i < 4; ++i) {
6495     if (HiQuad[i] > MaxQuad) {
6496       BestHiQuad = i;
6497       MaxQuad = HiQuad[i];
6498     }
6499   }
6500
6501   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6502   // of the two input vectors, shuffle them into one input vector so only a
6503   // single pshufb instruction is necessary. If there are more than 2 input
6504   // quads, disable the next transformation since it does not help SSSE3.
6505   bool V1Used = InputQuads[0] || InputQuads[1];
6506   bool V2Used = InputQuads[2] || InputQuads[3];
6507   if (Subtarget->hasSSSE3()) {
6508     if (InputQuads.count() == 2 && V1Used && V2Used) {
6509       BestLoQuad = InputQuads[0] ? 0 : 1;
6510       BestHiQuad = InputQuads[2] ? 2 : 3;
6511     }
6512     if (InputQuads.count() > 2) {
6513       BestLoQuad = -1;
6514       BestHiQuad = -1;
6515     }
6516   }
6517
6518   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6519   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6520   // words from all 4 input quadwords.
6521   SDValue NewV;
6522   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6523     int MaskV[] = {
6524       BestLoQuad < 0 ? 0 : BestLoQuad,
6525       BestHiQuad < 0 ? 1 : BestHiQuad
6526     };
6527     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6528                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6529                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6530     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6531
6532     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6533     // source words for the shuffle, to aid later transformations.
6534     bool AllWordsInNewV = true;
6535     bool InOrder[2] = { true, true };
6536     for (unsigned i = 0; i != 8; ++i) {
6537       int idx = MaskVals[i];
6538       if (idx != (int)i)
6539         InOrder[i/4] = false;
6540       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6541         continue;
6542       AllWordsInNewV = false;
6543       break;
6544     }
6545
6546     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6547     if (AllWordsInNewV) {
6548       for (int i = 0; i != 8; ++i) {
6549         int idx = MaskVals[i];
6550         if (idx < 0)
6551           continue;
6552         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6553         if ((idx != i) && idx < 4)
6554           pshufhw = false;
6555         if ((idx != i) && idx > 3)
6556           pshuflw = false;
6557       }
6558       V1 = NewV;
6559       V2Used = false;
6560       BestLoQuad = 0;
6561       BestHiQuad = 1;
6562     }
6563
6564     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6565     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6566     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6567       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6568       unsigned TargetMask = 0;
6569       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6570                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6571       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6572       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6573                              getShufflePSHUFLWImmediate(SVOp);
6574       V1 = NewV.getOperand(0);
6575       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6576     }
6577   }
6578
6579   // Promote splats to a larger type which usually leads to more efficient code.
6580   // FIXME: Is this true if pshufb is available?
6581   if (SVOp->isSplat())
6582     return PromoteSplat(SVOp, DAG);
6583
6584   // If we have SSSE3, and all words of the result are from 1 input vector,
6585   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6586   // is present, fall back to case 4.
6587   if (Subtarget->hasSSSE3()) {
6588     SmallVector<SDValue,16> pshufbMask;
6589
6590     // If we have elements from both input vectors, set the high bit of the
6591     // shuffle mask element to zero out elements that come from V2 in the V1
6592     // mask, and elements that come from V1 in the V2 mask, so that the two
6593     // results can be OR'd together.
6594     bool TwoInputs = V1Used && V2Used;
6595     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6596     if (!TwoInputs)
6597       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6598
6599     // Calculate the shuffle mask for the second input, shuffle it, and
6600     // OR it with the first shuffled input.
6601     CommuteVectorShuffleMask(MaskVals, 8);
6602     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6603     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6604     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6605   }
6606
6607   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6608   // and update MaskVals with new element order.
6609   std::bitset<8> InOrder;
6610   if (BestLoQuad >= 0) {
6611     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6612     for (int i = 0; i != 4; ++i) {
6613       int idx = MaskVals[i];
6614       if (idx < 0) {
6615         InOrder.set(i);
6616       } else if ((idx / 4) == BestLoQuad) {
6617         MaskV[i] = idx & 3;
6618         InOrder.set(i);
6619       }
6620     }
6621     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6622                                 &MaskV[0]);
6623
6624     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6625       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6626       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6627                                   NewV.getOperand(0),
6628                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6629     }
6630   }
6631
6632   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6633   // and update MaskVals with the new element order.
6634   if (BestHiQuad >= 0) {
6635     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6636     for (unsigned i = 4; i != 8; ++i) {
6637       int idx = MaskVals[i];
6638       if (idx < 0) {
6639         InOrder.set(i);
6640       } else if ((idx / 4) == BestHiQuad) {
6641         MaskV[i] = (idx & 3) + 4;
6642         InOrder.set(i);
6643       }
6644     }
6645     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6646                                 &MaskV[0]);
6647
6648     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6649       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6650       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6651                                   NewV.getOperand(0),
6652                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6653     }
6654   }
6655
6656   // In case BestHi & BestLo were both -1, which means each quadword has a word
6657   // from each of the four input quadwords, calculate the InOrder bitvector now
6658   // before falling through to the insert/extract cleanup.
6659   if (BestLoQuad == -1 && BestHiQuad == -1) {
6660     NewV = V1;
6661     for (int i = 0; i != 8; ++i)
6662       if (MaskVals[i] < 0 || MaskVals[i] == i)
6663         InOrder.set(i);
6664   }
6665
6666   // The other elements are put in the right place using pextrw and pinsrw.
6667   for (unsigned i = 0; i != 8; ++i) {
6668     if (InOrder[i])
6669       continue;
6670     int EltIdx = MaskVals[i];
6671     if (EltIdx < 0)
6672       continue;
6673     SDValue ExtOp = (EltIdx < 8) ?
6674       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6675                   DAG.getIntPtrConstant(EltIdx)) :
6676       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6677                   DAG.getIntPtrConstant(EltIdx - 8));
6678     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6679                        DAG.getIntPtrConstant(i));
6680   }
6681   return NewV;
6682 }
6683
6684 /// \brief v16i16 shuffles
6685 ///
6686 /// FIXME: We only support generation of a single pshufb currently.  We can
6687 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6688 /// well (e.g 2 x pshufb + 1 x por).
6689 static SDValue
6690 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6691   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6692   SDValue V1 = SVOp->getOperand(0);
6693   SDValue V2 = SVOp->getOperand(1);
6694   SDLoc dl(SVOp);
6695
6696   if (V2.getOpcode() != ISD::UNDEF)
6697     return SDValue();
6698
6699   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6700   return getPSHUFB(MaskVals, V1, dl, DAG);
6701 }
6702
6703 // v16i8 shuffles - Prefer shuffles in the following order:
6704 // 1. [ssse3] 1 x pshufb
6705 // 2. [ssse3] 2 x pshufb + 1 x por
6706 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6707 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6708                                         const X86Subtarget* Subtarget,
6709                                         SelectionDAG &DAG) {
6710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6711   SDValue V1 = SVOp->getOperand(0);
6712   SDValue V2 = SVOp->getOperand(1);
6713   SDLoc dl(SVOp);
6714   ArrayRef<int> MaskVals = SVOp->getMask();
6715
6716   // Promote splats to a larger type which usually leads to more efficient code.
6717   // FIXME: Is this true if pshufb is available?
6718   if (SVOp->isSplat())
6719     return PromoteSplat(SVOp, DAG);
6720
6721   // If we have SSSE3, case 1 is generated when all result bytes come from
6722   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6723   // present, fall back to case 3.
6724
6725   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6726   if (Subtarget->hasSSSE3()) {
6727     SmallVector<SDValue,16> pshufbMask;
6728
6729     // If all result elements are from one input vector, then only translate
6730     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6731     //
6732     // Otherwise, we have elements from both input vectors, and must zero out
6733     // elements that come from V2 in the first mask, and V1 in the second mask
6734     // so that we can OR them together.
6735     for (unsigned i = 0; i != 16; ++i) {
6736       int EltIdx = MaskVals[i];
6737       if (EltIdx < 0 || EltIdx >= 16)
6738         EltIdx = 0x80;
6739       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6740     }
6741     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6742                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6743                                  MVT::v16i8, pshufbMask));
6744
6745     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6746     // the 2nd operand if it's undefined or zero.
6747     if (V2.getOpcode() == ISD::UNDEF ||
6748         ISD::isBuildVectorAllZeros(V2.getNode()))
6749       return V1;
6750
6751     // Calculate the shuffle mask for the second input, shuffle it, and
6752     // OR it with the first shuffled input.
6753     pshufbMask.clear();
6754     for (unsigned i = 0; i != 16; ++i) {
6755       int EltIdx = MaskVals[i];
6756       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6757       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6758     }
6759     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6760                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6761                                  MVT::v16i8, pshufbMask));
6762     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6763   }
6764
6765   // No SSSE3 - Calculate in place words and then fix all out of place words
6766   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6767   // the 16 different words that comprise the two doublequadword input vectors.
6768   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6769   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6770   SDValue NewV = V1;
6771   for (int i = 0; i != 8; ++i) {
6772     int Elt0 = MaskVals[i*2];
6773     int Elt1 = MaskVals[i*2+1];
6774
6775     // This word of the result is all undef, skip it.
6776     if (Elt0 < 0 && Elt1 < 0)
6777       continue;
6778
6779     // This word of the result is already in the correct place, skip it.
6780     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6781       continue;
6782
6783     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6784     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6785     SDValue InsElt;
6786
6787     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6788     // using a single extract together, load it and store it.
6789     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6790       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6791                            DAG.getIntPtrConstant(Elt1 / 2));
6792       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6793                         DAG.getIntPtrConstant(i));
6794       continue;
6795     }
6796
6797     // If Elt1 is defined, extract it from the appropriate source.  If the
6798     // source byte is not also odd, shift the extracted word left 8 bits
6799     // otherwise clear the bottom 8 bits if we need to do an or.
6800     if (Elt1 >= 0) {
6801       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6802                            DAG.getIntPtrConstant(Elt1 / 2));
6803       if ((Elt1 & 1) == 0)
6804         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6805                              DAG.getConstant(8,
6806                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6807       else if (Elt0 >= 0)
6808         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6809                              DAG.getConstant(0xFF00, MVT::i16));
6810     }
6811     // If Elt0 is defined, extract it from the appropriate source.  If the
6812     // source byte is not also even, shift the extracted word right 8 bits. If
6813     // Elt1 was also defined, OR the extracted values together before
6814     // inserting them in the result.
6815     if (Elt0 >= 0) {
6816       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6817                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6818       if ((Elt0 & 1) != 0)
6819         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6820                               DAG.getConstant(8,
6821                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6822       else if (Elt1 >= 0)
6823         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6824                              DAG.getConstant(0x00FF, MVT::i16));
6825       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6826                          : InsElt0;
6827     }
6828     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6829                        DAG.getIntPtrConstant(i));
6830   }
6831   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6832 }
6833
6834 // v32i8 shuffles - Translate to VPSHUFB if possible.
6835 static
6836 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6837                                  const X86Subtarget *Subtarget,
6838                                  SelectionDAG &DAG) {
6839   MVT VT = SVOp->getSimpleValueType(0);
6840   SDValue V1 = SVOp->getOperand(0);
6841   SDValue V2 = SVOp->getOperand(1);
6842   SDLoc dl(SVOp);
6843   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6844
6845   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6846   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6847   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6848
6849   // VPSHUFB may be generated if
6850   // (1) one of input vector is undefined or zeroinitializer.
6851   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6852   // And (2) the mask indexes don't cross the 128-bit lane.
6853   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6854       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6855     return SDValue();
6856
6857   if (V1IsAllZero && !V2IsAllZero) {
6858     CommuteVectorShuffleMask(MaskVals, 32);
6859     V1 = V2;
6860   }
6861   return getPSHUFB(MaskVals, V1, dl, DAG);
6862 }
6863
6864 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6865 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6866 /// done when every pair / quad of shuffle mask elements point to elements in
6867 /// the right sequence. e.g.
6868 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6869 static
6870 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6871                                  SelectionDAG &DAG) {
6872   MVT VT = SVOp->getSimpleValueType(0);
6873   SDLoc dl(SVOp);
6874   unsigned NumElems = VT.getVectorNumElements();
6875   MVT NewVT;
6876   unsigned Scale;
6877   switch (VT.SimpleTy) {
6878   default: llvm_unreachable("Unexpected!");
6879   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6880   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6881   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6882   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6883   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6884   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6885   }
6886
6887   SmallVector<int, 8> MaskVec;
6888   for (unsigned i = 0; i != NumElems; i += Scale) {
6889     int StartIdx = -1;
6890     for (unsigned j = 0; j != Scale; ++j) {
6891       int EltIdx = SVOp->getMaskElt(i+j);
6892       if (EltIdx < 0)
6893         continue;
6894       if (StartIdx < 0)
6895         StartIdx = (EltIdx / Scale);
6896       if (EltIdx != (int)(StartIdx*Scale + j))
6897         return SDValue();
6898     }
6899     MaskVec.push_back(StartIdx);
6900   }
6901
6902   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6903   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6904   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6905 }
6906
6907 /// getVZextMovL - Return a zero-extending vector move low node.
6908 ///
6909 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6910                             SDValue SrcOp, SelectionDAG &DAG,
6911                             const X86Subtarget *Subtarget, SDLoc dl) {
6912   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6913     LoadSDNode *LD = nullptr;
6914     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6915       LD = dyn_cast<LoadSDNode>(SrcOp);
6916     if (!LD) {
6917       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6918       // instead.
6919       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6920       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6921           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6922           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6923           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6924         // PR2108
6925         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6926         return DAG.getNode(ISD::BITCAST, dl, VT,
6927                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6928                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6929                                                    OpVT,
6930                                                    SrcOp.getOperand(0)
6931                                                           .getOperand(0))));
6932       }
6933     }
6934   }
6935
6936   return DAG.getNode(ISD::BITCAST, dl, VT,
6937                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6938                                  DAG.getNode(ISD::BITCAST, dl,
6939                                              OpVT, SrcOp)));
6940 }
6941
6942 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6943 /// which could not be matched by any known target speficic shuffle
6944 static SDValue
6945 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6946
6947   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6948   if (NewOp.getNode())
6949     return NewOp;
6950
6951   MVT VT = SVOp->getSimpleValueType(0);
6952
6953   unsigned NumElems = VT.getVectorNumElements();
6954   unsigned NumLaneElems = NumElems / 2;
6955
6956   SDLoc dl(SVOp);
6957   MVT EltVT = VT.getVectorElementType();
6958   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6959   SDValue Output[2];
6960
6961   SmallVector<int, 16> Mask;
6962   for (unsigned l = 0; l < 2; ++l) {
6963     // Build a shuffle mask for the output, discovering on the fly which
6964     // input vectors to use as shuffle operands (recorded in InputUsed).
6965     // If building a suitable shuffle vector proves too hard, then bail
6966     // out with UseBuildVector set.
6967     bool UseBuildVector = false;
6968     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6969     unsigned LaneStart = l * NumLaneElems;
6970     for (unsigned i = 0; i != NumLaneElems; ++i) {
6971       // The mask element.  This indexes into the input.
6972       int Idx = SVOp->getMaskElt(i+LaneStart);
6973       if (Idx < 0) {
6974         // the mask element does not index into any input vector.
6975         Mask.push_back(-1);
6976         continue;
6977       }
6978
6979       // The input vector this mask element indexes into.
6980       int Input = Idx / NumLaneElems;
6981
6982       // Turn the index into an offset from the start of the input vector.
6983       Idx -= Input * NumLaneElems;
6984
6985       // Find or create a shuffle vector operand to hold this input.
6986       unsigned OpNo;
6987       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6988         if (InputUsed[OpNo] == Input)
6989           // This input vector is already an operand.
6990           break;
6991         if (InputUsed[OpNo] < 0) {
6992           // Create a new operand for this input vector.
6993           InputUsed[OpNo] = Input;
6994           break;
6995         }
6996       }
6997
6998       if (OpNo >= array_lengthof(InputUsed)) {
6999         // More than two input vectors used!  Give up on trying to create a
7000         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7001         UseBuildVector = true;
7002         break;
7003       }
7004
7005       // Add the mask index for the new shuffle vector.
7006       Mask.push_back(Idx + OpNo * NumLaneElems);
7007     }
7008
7009     if (UseBuildVector) {
7010       SmallVector<SDValue, 16> SVOps;
7011       for (unsigned i = 0; i != NumLaneElems; ++i) {
7012         // The mask element.  This indexes into the input.
7013         int Idx = SVOp->getMaskElt(i+LaneStart);
7014         if (Idx < 0) {
7015           SVOps.push_back(DAG.getUNDEF(EltVT));
7016           continue;
7017         }
7018
7019         // The input vector this mask element indexes into.
7020         int Input = Idx / NumElems;
7021
7022         // Turn the index into an offset from the start of the input vector.
7023         Idx -= Input * NumElems;
7024
7025         // Extract the vector element by hand.
7026         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7027                                     SVOp->getOperand(Input),
7028                                     DAG.getIntPtrConstant(Idx)));
7029       }
7030
7031       // Construct the output using a BUILD_VECTOR.
7032       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7033     } else if (InputUsed[0] < 0) {
7034       // No input vectors were used! The result is undefined.
7035       Output[l] = DAG.getUNDEF(NVT);
7036     } else {
7037       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7038                                         (InputUsed[0] % 2) * NumLaneElems,
7039                                         DAG, dl);
7040       // If only one input was used, use an undefined vector for the other.
7041       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7042         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7043                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7044       // At least one input vector was used. Create a new shuffle vector.
7045       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7046     }
7047
7048     Mask.clear();
7049   }
7050
7051   // Concatenate the result back
7052   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7053 }
7054
7055 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7056 /// 4 elements, and match them with several different shuffle types.
7057 static SDValue
7058 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7059   SDValue V1 = SVOp->getOperand(0);
7060   SDValue V2 = SVOp->getOperand(1);
7061   SDLoc dl(SVOp);
7062   MVT VT = SVOp->getSimpleValueType(0);
7063
7064   assert(VT.is128BitVector() && "Unsupported vector size");
7065
7066   std::pair<int, int> Locs[4];
7067   int Mask1[] = { -1, -1, -1, -1 };
7068   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7069
7070   unsigned NumHi = 0;
7071   unsigned NumLo = 0;
7072   for (unsigned i = 0; i != 4; ++i) {
7073     int Idx = PermMask[i];
7074     if (Idx < 0) {
7075       Locs[i] = std::make_pair(-1, -1);
7076     } else {
7077       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7078       if (Idx < 4) {
7079         Locs[i] = std::make_pair(0, NumLo);
7080         Mask1[NumLo] = Idx;
7081         NumLo++;
7082       } else {
7083         Locs[i] = std::make_pair(1, NumHi);
7084         if (2+NumHi < 4)
7085           Mask1[2+NumHi] = Idx;
7086         NumHi++;
7087       }
7088     }
7089   }
7090
7091   if (NumLo <= 2 && NumHi <= 2) {
7092     // If no more than two elements come from either vector. This can be
7093     // implemented with two shuffles. First shuffle gather the elements.
7094     // The second shuffle, which takes the first shuffle as both of its
7095     // vector operands, put the elements into the right order.
7096     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7097
7098     int Mask2[] = { -1, -1, -1, -1 };
7099
7100     for (unsigned i = 0; i != 4; ++i)
7101       if (Locs[i].first != -1) {
7102         unsigned Idx = (i < 2) ? 0 : 4;
7103         Idx += Locs[i].first * 2 + Locs[i].second;
7104         Mask2[i] = Idx;
7105       }
7106
7107     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7108   }
7109
7110   if (NumLo == 3 || NumHi == 3) {
7111     // Otherwise, we must have three elements from one vector, call it X, and
7112     // one element from the other, call it Y.  First, use a shufps to build an
7113     // intermediate vector with the one element from Y and the element from X
7114     // that will be in the same half in the final destination (the indexes don't
7115     // matter). Then, use a shufps to build the final vector, taking the half
7116     // containing the element from Y from the intermediate, and the other half
7117     // from X.
7118     if (NumHi == 3) {
7119       // Normalize it so the 3 elements come from V1.
7120       CommuteVectorShuffleMask(PermMask, 4);
7121       std::swap(V1, V2);
7122     }
7123
7124     // Find the element from V2.
7125     unsigned HiIndex;
7126     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7127       int Val = PermMask[HiIndex];
7128       if (Val < 0)
7129         continue;
7130       if (Val >= 4)
7131         break;
7132     }
7133
7134     Mask1[0] = PermMask[HiIndex];
7135     Mask1[1] = -1;
7136     Mask1[2] = PermMask[HiIndex^1];
7137     Mask1[3] = -1;
7138     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7139
7140     if (HiIndex >= 2) {
7141       Mask1[0] = PermMask[0];
7142       Mask1[1] = PermMask[1];
7143       Mask1[2] = HiIndex & 1 ? 6 : 4;
7144       Mask1[3] = HiIndex & 1 ? 4 : 6;
7145       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7146     }
7147
7148     Mask1[0] = HiIndex & 1 ? 2 : 0;
7149     Mask1[1] = HiIndex & 1 ? 0 : 2;
7150     Mask1[2] = PermMask[2];
7151     Mask1[3] = PermMask[3];
7152     if (Mask1[2] >= 0)
7153       Mask1[2] += 4;
7154     if (Mask1[3] >= 0)
7155       Mask1[3] += 4;
7156     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7157   }
7158
7159   // Break it into (shuffle shuffle_hi, shuffle_lo).
7160   int LoMask[] = { -1, -1, -1, -1 };
7161   int HiMask[] = { -1, -1, -1, -1 };
7162
7163   int *MaskPtr = LoMask;
7164   unsigned MaskIdx = 0;
7165   unsigned LoIdx = 0;
7166   unsigned HiIdx = 2;
7167   for (unsigned i = 0; i != 4; ++i) {
7168     if (i == 2) {
7169       MaskPtr = HiMask;
7170       MaskIdx = 1;
7171       LoIdx = 0;
7172       HiIdx = 2;
7173     }
7174     int Idx = PermMask[i];
7175     if (Idx < 0) {
7176       Locs[i] = std::make_pair(-1, -1);
7177     } else if (Idx < 4) {
7178       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7179       MaskPtr[LoIdx] = Idx;
7180       LoIdx++;
7181     } else {
7182       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7183       MaskPtr[HiIdx] = Idx;
7184       HiIdx++;
7185     }
7186   }
7187
7188   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7189   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7190   int MaskOps[] = { -1, -1, -1, -1 };
7191   for (unsigned i = 0; i != 4; ++i)
7192     if (Locs[i].first != -1)
7193       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7194   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7195 }
7196
7197 static bool MayFoldVectorLoad(SDValue V) {
7198   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7199     V = V.getOperand(0);
7200
7201   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7202     V = V.getOperand(0);
7203   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7204       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7205     // BUILD_VECTOR (load), undef
7206     V = V.getOperand(0);
7207
7208   return MayFoldLoad(V);
7209 }
7210
7211 static
7212 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7213   MVT VT = Op.getSimpleValueType();
7214
7215   // Canonizalize to v2f64.
7216   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7217   return DAG.getNode(ISD::BITCAST, dl, VT,
7218                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7219                                           V1, DAG));
7220 }
7221
7222 static
7223 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7224                         bool HasSSE2) {
7225   SDValue V1 = Op.getOperand(0);
7226   SDValue V2 = Op.getOperand(1);
7227   MVT VT = Op.getSimpleValueType();
7228
7229   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7230
7231   if (HasSSE2 && VT == MVT::v2f64)
7232     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7233
7234   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7235   return DAG.getNode(ISD::BITCAST, dl, VT,
7236                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7237                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7238                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7239 }
7240
7241 static
7242 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7243   SDValue V1 = Op.getOperand(0);
7244   SDValue V2 = Op.getOperand(1);
7245   MVT VT = Op.getSimpleValueType();
7246
7247   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7248          "unsupported shuffle type");
7249
7250   if (V2.getOpcode() == ISD::UNDEF)
7251     V2 = V1;
7252
7253   // v4i32 or v4f32
7254   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7255 }
7256
7257 static
7258 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7259   SDValue V1 = Op.getOperand(0);
7260   SDValue V2 = Op.getOperand(1);
7261   MVT VT = Op.getSimpleValueType();
7262   unsigned NumElems = VT.getVectorNumElements();
7263
7264   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7265   // operand of these instructions is only memory, so check if there's a
7266   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7267   // same masks.
7268   bool CanFoldLoad = false;
7269
7270   // Trivial case, when V2 comes from a load.
7271   if (MayFoldVectorLoad(V2))
7272     CanFoldLoad = true;
7273
7274   // When V1 is a load, it can be folded later into a store in isel, example:
7275   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7276   //    turns into:
7277   //  (MOVLPSmr addr:$src1, VR128:$src2)
7278   // So, recognize this potential and also use MOVLPS or MOVLPD
7279   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7280     CanFoldLoad = true;
7281
7282   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7283   if (CanFoldLoad) {
7284     if (HasSSE2 && NumElems == 2)
7285       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7286
7287     if (NumElems == 4)
7288       // If we don't care about the second element, proceed to use movss.
7289       if (SVOp->getMaskElt(1) != -1)
7290         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7291   }
7292
7293   // movl and movlp will both match v2i64, but v2i64 is never matched by
7294   // movl earlier because we make it strict to avoid messing with the movlp load
7295   // folding logic (see the code above getMOVLP call). Match it here then,
7296   // this is horrible, but will stay like this until we move all shuffle
7297   // matching to x86 specific nodes. Note that for the 1st condition all
7298   // types are matched with movsd.
7299   if (HasSSE2) {
7300     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7301     // as to remove this logic from here, as much as possible
7302     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7303       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7304     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7305   }
7306
7307   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7308
7309   // Invert the operand order and use SHUFPS to match it.
7310   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7311                               getShuffleSHUFImmediate(SVOp), DAG);
7312 }
7313
7314 // It is only safe to call this function if isINSERTPSMask is true for
7315 // this shufflevector mask.
7316 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7317                            SelectionDAG &DAG) {
7318   // Generate an insertps instruction when inserting an f32 from memory onto a
7319   // v4f32 or when copying a member from one v4f32 to another.
7320   // We also use it for transferring i32 from one register to another,
7321   // since it simply copies the same bits.
7322   // If we're transfering an i32 from memory to a specific element in a
7323   // register, we output a generic DAG that will match the PINSRD
7324   // instruction.
7325   // TODO: Optimize for AVX cases too (VINSERTPS)
7326   MVT VT = SVOp->getSimpleValueType(0);
7327   MVT EVT = VT.getVectorElementType();
7328   SDValue V1 = SVOp->getOperand(0);
7329   SDValue V2 = SVOp->getOperand(1);
7330   auto Mask = SVOp->getMask();
7331   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7332          "unsupported vector type for insertps/pinsrd");
7333
7334   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7335                              [](const int &i) { return i < 4; });
7336
7337   SDValue From;
7338   SDValue To;
7339   unsigned DestIndex;
7340   if (FromV1 == 1) {
7341     From = V1;
7342     To = V2;
7343     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7344                              [](const int &i) { return i < 4; }) -
7345                 Mask.begin();
7346   } else {
7347     From = V2;
7348     To = V1;
7349     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7350                              [](const int &i) { return i >= 4; }) -
7351                 Mask.begin();
7352   }
7353
7354   if (MayFoldLoad(From)) {
7355     // Trivial case, when From comes from a load and is only used by the
7356     // shuffle. Make it use insertps from the vector that we need from that
7357     // load.
7358     SDValue Addr = From.getOperand(1);
7359     SDValue NewAddr =
7360         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7361                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7362                                     Addr.getSimpleValueType()));
7363
7364     LoadSDNode *Load = cast<LoadSDNode>(From);
7365     SDValue NewLoad =
7366         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7367                     DAG.getMachineFunction().getMachineMemOperand(
7368                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7369
7370     if (EVT == MVT::f32) {
7371       // Create this as a scalar to vector to match the instruction pattern.
7372       SDValue LoadScalarToVector =
7373           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7374       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7375       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7376                          InsertpsMask);
7377     } else { // EVT == MVT::i32
7378       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7379       // instruction, to match the PINSRD instruction, which loads an i32 to a
7380       // certain vector element.
7381       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7382                          DAG.getConstant(DestIndex, MVT::i32));
7383     }
7384   }
7385
7386   // Vector-element-to-vector
7387   unsigned SrcIndex = Mask[DestIndex] % 4;
7388   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7389   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7390 }
7391
7392 // Reduce a vector shuffle to zext.
7393 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7394                                     SelectionDAG &DAG) {
7395   // PMOVZX is only available from SSE41.
7396   if (!Subtarget->hasSSE41())
7397     return SDValue();
7398
7399   MVT VT = Op.getSimpleValueType();
7400
7401   // Only AVX2 support 256-bit vector integer extending.
7402   if (!Subtarget->hasInt256() && VT.is256BitVector())
7403     return SDValue();
7404
7405   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7406   SDLoc DL(Op);
7407   SDValue V1 = Op.getOperand(0);
7408   SDValue V2 = Op.getOperand(1);
7409   unsigned NumElems = VT.getVectorNumElements();
7410
7411   // Extending is an unary operation and the element type of the source vector
7412   // won't be equal to or larger than i64.
7413   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7414       VT.getVectorElementType() == MVT::i64)
7415     return SDValue();
7416
7417   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7418   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7419   while ((1U << Shift) < NumElems) {
7420     if (SVOp->getMaskElt(1U << Shift) == 1)
7421       break;
7422     Shift += 1;
7423     // The maximal ratio is 8, i.e. from i8 to i64.
7424     if (Shift > 3)
7425       return SDValue();
7426   }
7427
7428   // Check the shuffle mask.
7429   unsigned Mask = (1U << Shift) - 1;
7430   for (unsigned i = 0; i != NumElems; ++i) {
7431     int EltIdx = SVOp->getMaskElt(i);
7432     if ((i & Mask) != 0 && EltIdx != -1)
7433       return SDValue();
7434     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7435       return SDValue();
7436   }
7437
7438   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7439   MVT NeVT = MVT::getIntegerVT(NBits);
7440   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7441
7442   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7443     return SDValue();
7444
7445   // Simplify the operand as it's prepared to be fed into shuffle.
7446   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7447   if (V1.getOpcode() == ISD::BITCAST &&
7448       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7449       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7450       V1.getOperand(0).getOperand(0)
7451         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7452     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7453     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7454     ConstantSDNode *CIdx =
7455       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7456     // If it's foldable, i.e. normal load with single use, we will let code
7457     // selection to fold it. Otherwise, we will short the conversion sequence.
7458     if (CIdx && CIdx->getZExtValue() == 0 &&
7459         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7460       MVT FullVT = V.getSimpleValueType();
7461       MVT V1VT = V1.getSimpleValueType();
7462       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7463         // The "ext_vec_elt" node is wider than the result node.
7464         // In this case we should extract subvector from V.
7465         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7466         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7467         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7468                                         FullVT.getVectorNumElements()/Ratio);
7469         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7470                         DAG.getIntPtrConstant(0));
7471       }
7472       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7473     }
7474   }
7475
7476   return DAG.getNode(ISD::BITCAST, DL, VT,
7477                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7478 }
7479
7480 static SDValue
7481 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7482                        SelectionDAG &DAG) {
7483   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7484   MVT VT = Op.getSimpleValueType();
7485   SDLoc dl(Op);
7486   SDValue V1 = Op.getOperand(0);
7487   SDValue V2 = Op.getOperand(1);
7488
7489   if (isZeroShuffle(SVOp))
7490     return getZeroVector(VT, Subtarget, DAG, dl);
7491
7492   // Handle splat operations
7493   if (SVOp->isSplat()) {
7494     // Use vbroadcast whenever the splat comes from a foldable load
7495     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7496     if (Broadcast.getNode())
7497       return Broadcast;
7498   }
7499
7500   // Check integer expanding shuffles.
7501   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7502   if (NewOp.getNode())
7503     return NewOp;
7504
7505   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7506   // do it!
7507   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7508       VT == MVT::v16i16 || VT == MVT::v32i8) {
7509     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7510     if (NewOp.getNode())
7511       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7512   } else if ((VT == MVT::v4i32 ||
7513              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7514     // FIXME: Figure out a cleaner way to do this.
7515     // Try to make use of movq to zero out the top part.
7516     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7517       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7518       if (NewOp.getNode()) {
7519         MVT NewVT = NewOp.getSimpleValueType();
7520         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7521                                NewVT, true, false))
7522           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7523                               DAG, Subtarget, dl);
7524       }
7525     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7526       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7527       if (NewOp.getNode()) {
7528         MVT NewVT = NewOp.getSimpleValueType();
7529         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7530           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7531                               DAG, Subtarget, dl);
7532       }
7533     }
7534   }
7535   return SDValue();
7536 }
7537
7538 SDValue
7539 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7540   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7541   SDValue V1 = Op.getOperand(0);
7542   SDValue V2 = Op.getOperand(1);
7543   MVT VT = Op.getSimpleValueType();
7544   SDLoc dl(Op);
7545   unsigned NumElems = VT.getVectorNumElements();
7546   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7547   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7548   bool V1IsSplat = false;
7549   bool V2IsSplat = false;
7550   bool HasSSE2 = Subtarget->hasSSE2();
7551   bool HasFp256    = Subtarget->hasFp256();
7552   bool HasInt256   = Subtarget->hasInt256();
7553   MachineFunction &MF = DAG.getMachineFunction();
7554   bool OptForSize = MF.getFunction()->getAttributes().
7555     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7556
7557   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7558
7559   if (V1IsUndef && V2IsUndef)
7560     return DAG.getUNDEF(VT);
7561
7562   // When we create a shuffle node we put the UNDEF node to second operand,
7563   // but in some cases the first operand may be transformed to UNDEF.
7564   // In this case we should just commute the node.
7565   if (V1IsUndef)
7566     return CommuteVectorShuffle(SVOp, DAG);
7567
7568   // Vector shuffle lowering takes 3 steps:
7569   //
7570   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7571   //    narrowing and commutation of operands should be handled.
7572   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7573   //    shuffle nodes.
7574   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7575   //    so the shuffle can be broken into other shuffles and the legalizer can
7576   //    try the lowering again.
7577   //
7578   // The general idea is that no vector_shuffle operation should be left to
7579   // be matched during isel, all of them must be converted to a target specific
7580   // node here.
7581
7582   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7583   // narrowing and commutation of operands should be handled. The actual code
7584   // doesn't include all of those, work in progress...
7585   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7586   if (NewOp.getNode())
7587     return NewOp;
7588
7589   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7590
7591   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7592   // unpckh_undef). Only use pshufd if speed is more important than size.
7593   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7594     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7595   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7596     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7597
7598   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7599       V2IsUndef && MayFoldVectorLoad(V1))
7600     return getMOVDDup(Op, dl, V1, DAG);
7601
7602   if (isMOVHLPS_v_undef_Mask(M, VT))
7603     return getMOVHighToLow(Op, dl, DAG);
7604
7605   // Use to match splats
7606   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7607       (VT == MVT::v2f64 || VT == MVT::v2i64))
7608     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7609
7610   if (isPSHUFDMask(M, VT)) {
7611     // The actual implementation will match the mask in the if above and then
7612     // during isel it can match several different instructions, not only pshufd
7613     // as its name says, sad but true, emulate the behavior for now...
7614     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7615       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7616
7617     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7618
7619     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7620       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7621
7622     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7623       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7624                                   DAG);
7625
7626     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7627                                 TargetMask, DAG);
7628   }
7629
7630   if (isPALIGNRMask(M, VT, Subtarget))
7631     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7632                                 getShufflePALIGNRImmediate(SVOp),
7633                                 DAG);
7634
7635   // Check if this can be converted into a logical shift.
7636   bool isLeft = false;
7637   unsigned ShAmt = 0;
7638   SDValue ShVal;
7639   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7640   if (isShift && ShVal.hasOneUse()) {
7641     // If the shifted value has multiple uses, it may be cheaper to use
7642     // v_set0 + movlhps or movhlps, etc.
7643     MVT EltVT = VT.getVectorElementType();
7644     ShAmt *= EltVT.getSizeInBits();
7645     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7646   }
7647
7648   if (isMOVLMask(M, VT)) {
7649     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7650       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7651     if (!isMOVLPMask(M, VT)) {
7652       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7653         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7654
7655       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7656         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7657     }
7658   }
7659
7660   // FIXME: fold these into legal mask.
7661   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7662     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7663
7664   if (isMOVHLPSMask(M, VT))
7665     return getMOVHighToLow(Op, dl, DAG);
7666
7667   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7668     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7669
7670   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7671     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7672
7673   if (isMOVLPMask(M, VT))
7674     return getMOVLP(Op, dl, DAG, HasSSE2);
7675
7676   if (ShouldXformToMOVHLPS(M, VT) ||
7677       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7678     return CommuteVectorShuffle(SVOp, DAG);
7679
7680   if (isShift) {
7681     // No better options. Use a vshldq / vsrldq.
7682     MVT EltVT = VT.getVectorElementType();
7683     ShAmt *= EltVT.getSizeInBits();
7684     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7685   }
7686
7687   bool Commuted = false;
7688   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7689   // 1,1,1,1 -> v8i16 though.
7690   V1IsSplat = isSplatVector(V1.getNode());
7691   V2IsSplat = isSplatVector(V2.getNode());
7692
7693   // Canonicalize the splat or undef, if present, to be on the RHS.
7694   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7695     CommuteVectorShuffleMask(M, NumElems);
7696     std::swap(V1, V2);
7697     std::swap(V1IsSplat, V2IsSplat);
7698     Commuted = true;
7699   }
7700
7701   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7702     // Shuffling low element of v1 into undef, just return v1.
7703     if (V2IsUndef)
7704       return V1;
7705     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7706     // the instruction selector will not match, so get a canonical MOVL with
7707     // swapped operands to undo the commute.
7708     return getMOVL(DAG, dl, VT, V2, V1);
7709   }
7710
7711   if (isUNPCKLMask(M, VT, HasInt256))
7712     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7713
7714   if (isUNPCKHMask(M, VT, HasInt256))
7715     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7716
7717   if (V2IsSplat) {
7718     // Normalize mask so all entries that point to V2 points to its first
7719     // element then try to match unpck{h|l} again. If match, return a
7720     // new vector_shuffle with the corrected mask.p
7721     SmallVector<int, 8> NewMask(M.begin(), M.end());
7722     NormalizeMask(NewMask, NumElems);
7723     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7724       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7725     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7726       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7727   }
7728
7729   if (Commuted) {
7730     // Commute is back and try unpck* again.
7731     // FIXME: this seems wrong.
7732     CommuteVectorShuffleMask(M, NumElems);
7733     std::swap(V1, V2);
7734     std::swap(V1IsSplat, V2IsSplat);
7735
7736     if (isUNPCKLMask(M, VT, HasInt256))
7737       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7738
7739     if (isUNPCKHMask(M, VT, HasInt256))
7740       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7741   }
7742
7743   // Normalize the node to match x86 shuffle ops if needed
7744   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7745     return CommuteVectorShuffle(SVOp, DAG);
7746
7747   // The checks below are all present in isShuffleMaskLegal, but they are
7748   // inlined here right now to enable us to directly emit target specific
7749   // nodes, and remove one by one until they don't return Op anymore.
7750
7751   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7752       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7753     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7754       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7755   }
7756
7757   if (isPSHUFHWMask(M, VT, HasInt256))
7758     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7759                                 getShufflePSHUFHWImmediate(SVOp),
7760                                 DAG);
7761
7762   if (isPSHUFLWMask(M, VT, HasInt256))
7763     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7764                                 getShufflePSHUFLWImmediate(SVOp),
7765                                 DAG);
7766
7767   if (isSHUFPMask(M, VT))
7768     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7769                                 getShuffleSHUFImmediate(SVOp), DAG);
7770
7771   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7772     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7773   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7774     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7775
7776   //===--------------------------------------------------------------------===//
7777   // Generate target specific nodes for 128 or 256-bit shuffles only
7778   // supported in the AVX instruction set.
7779   //
7780
7781   // Handle VMOVDDUPY permutations
7782   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7783     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7784
7785   // Handle VPERMILPS/D* permutations
7786   if (isVPERMILPMask(M, VT)) {
7787     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7788       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7789                                   getShuffleSHUFImmediate(SVOp), DAG);
7790     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7791                                 getShuffleSHUFImmediate(SVOp), DAG);
7792   }
7793
7794   unsigned Idx;
7795   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7796     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7797                               Idx*(NumElems/2), DAG, dl);
7798
7799   // Handle VPERM2F128/VPERM2I128 permutations
7800   if (isVPERM2X128Mask(M, VT, HasFp256))
7801     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7802                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7803
7804   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7805   if (BlendOp.getNode())
7806     return BlendOp;
7807
7808   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7809     return getINSERTPS(SVOp, dl, DAG);
7810
7811   unsigned Imm8;
7812   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7813     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7814
7815   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7816       VT.is512BitVector()) {
7817     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7818     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7819     SmallVector<SDValue, 16> permclMask;
7820     for (unsigned i = 0; i != NumElems; ++i) {
7821       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7822     }
7823
7824     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7825     if (V2IsUndef)
7826       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7827       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7828                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7829     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7830                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7831   }
7832
7833   //===--------------------------------------------------------------------===//
7834   // Since no target specific shuffle was selected for this generic one,
7835   // lower it into other known shuffles. FIXME: this isn't true yet, but
7836   // this is the plan.
7837   //
7838
7839   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7840   if (VT == MVT::v8i16) {
7841     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7842     if (NewOp.getNode())
7843       return NewOp;
7844   }
7845
7846   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7847     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7848     if (NewOp.getNode())
7849       return NewOp;
7850   }
7851
7852   if (VT == MVT::v16i8) {
7853     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7854     if (NewOp.getNode())
7855       return NewOp;
7856   }
7857
7858   if (VT == MVT::v32i8) {
7859     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7860     if (NewOp.getNode())
7861       return NewOp;
7862   }
7863
7864   // Handle all 128-bit wide vectors with 4 elements, and match them with
7865   // several different shuffle types.
7866   if (NumElems == 4 && VT.is128BitVector())
7867     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7868
7869   // Handle general 256-bit shuffles
7870   if (VT.is256BitVector())
7871     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7872
7873   return SDValue();
7874 }
7875
7876 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7877   MVT VT = Op.getSimpleValueType();
7878   SDLoc dl(Op);
7879
7880   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7881     return SDValue();
7882
7883   if (VT.getSizeInBits() == 8) {
7884     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7885                                   Op.getOperand(0), Op.getOperand(1));
7886     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7887                                   DAG.getValueType(VT));
7888     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7889   }
7890
7891   if (VT.getSizeInBits() == 16) {
7892     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7893     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7894     if (Idx == 0)
7895       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7896                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7897                                      DAG.getNode(ISD::BITCAST, dl,
7898                                                  MVT::v4i32,
7899                                                  Op.getOperand(0)),
7900                                      Op.getOperand(1)));
7901     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7902                                   Op.getOperand(0), Op.getOperand(1));
7903     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7904                                   DAG.getValueType(VT));
7905     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7906   }
7907
7908   if (VT == MVT::f32) {
7909     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7910     // the result back to FR32 register. It's only worth matching if the
7911     // result has a single use which is a store or a bitcast to i32.  And in
7912     // the case of a store, it's not worth it if the index is a constant 0,
7913     // because a MOVSSmr can be used instead, which is smaller and faster.
7914     if (!Op.hasOneUse())
7915       return SDValue();
7916     SDNode *User = *Op.getNode()->use_begin();
7917     if ((User->getOpcode() != ISD::STORE ||
7918          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7919           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7920         (User->getOpcode() != ISD::BITCAST ||
7921          User->getValueType(0) != MVT::i32))
7922       return SDValue();
7923     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7924                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7925                                               Op.getOperand(0)),
7926                                               Op.getOperand(1));
7927     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7928   }
7929
7930   if (VT == MVT::i32 || VT == MVT::i64) {
7931     // ExtractPS/pextrq works with constant index.
7932     if (isa<ConstantSDNode>(Op.getOperand(1)))
7933       return Op;
7934   }
7935   return SDValue();
7936 }
7937
7938 /// Extract one bit from mask vector, like v16i1 or v8i1.
7939 /// AVX-512 feature.
7940 SDValue
7941 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7942   SDValue Vec = Op.getOperand(0);
7943   SDLoc dl(Vec);
7944   MVT VecVT = Vec.getSimpleValueType();
7945   SDValue Idx = Op.getOperand(1);
7946   MVT EltVT = Op.getSimpleValueType();
7947
7948   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7949
7950   // variable index can't be handled in mask registers,
7951   // extend vector to VR512
7952   if (!isa<ConstantSDNode>(Idx)) {
7953     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7954     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7955     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7956                               ExtVT.getVectorElementType(), Ext, Idx);
7957     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7958   }
7959
7960   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7961   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7962   unsigned MaxSift = rc->getSize()*8 - 1;
7963   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7964                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7965   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7966                     DAG.getConstant(MaxSift, MVT::i8));
7967   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7968                        DAG.getIntPtrConstant(0));
7969 }
7970
7971 SDValue
7972 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7973                                            SelectionDAG &DAG) const {
7974   SDLoc dl(Op);
7975   SDValue Vec = Op.getOperand(0);
7976   MVT VecVT = Vec.getSimpleValueType();
7977   SDValue Idx = Op.getOperand(1);
7978
7979   if (Op.getSimpleValueType() == MVT::i1)
7980     return ExtractBitFromMaskVector(Op, DAG);
7981
7982   if (!isa<ConstantSDNode>(Idx)) {
7983     if (VecVT.is512BitVector() ||
7984         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7985          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7986
7987       MVT MaskEltVT =
7988         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7989       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7990                                     MaskEltVT.getSizeInBits());
7991
7992       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7993       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7994                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7995                                 Idx, DAG.getConstant(0, getPointerTy()));
7996       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7997       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7998                         Perm, DAG.getConstant(0, getPointerTy()));
7999     }
8000     return SDValue();
8001   }
8002
8003   // If this is a 256-bit vector result, first extract the 128-bit vector and
8004   // then extract the element from the 128-bit vector.
8005   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8006
8007     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8008     // Get the 128-bit vector.
8009     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8010     MVT EltVT = VecVT.getVectorElementType();
8011
8012     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8013
8014     //if (IdxVal >= NumElems/2)
8015     //  IdxVal -= NumElems/2;
8016     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8017     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8018                        DAG.getConstant(IdxVal, MVT::i32));
8019   }
8020
8021   assert(VecVT.is128BitVector() && "Unexpected vector length");
8022
8023   if (Subtarget->hasSSE41()) {
8024     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8025     if (Res.getNode())
8026       return Res;
8027   }
8028
8029   MVT VT = Op.getSimpleValueType();
8030   // TODO: handle v16i8.
8031   if (VT.getSizeInBits() == 16) {
8032     SDValue Vec = Op.getOperand(0);
8033     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8034     if (Idx == 0)
8035       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8036                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8037                                      DAG.getNode(ISD::BITCAST, dl,
8038                                                  MVT::v4i32, Vec),
8039                                      Op.getOperand(1)));
8040     // Transform it so it match pextrw which produces a 32-bit result.
8041     MVT EltVT = MVT::i32;
8042     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8043                                   Op.getOperand(0), Op.getOperand(1));
8044     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8045                                   DAG.getValueType(VT));
8046     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8047   }
8048
8049   if (VT.getSizeInBits() == 32) {
8050     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8051     if (Idx == 0)
8052       return Op;
8053
8054     // SHUFPS the element to the lowest double word, then movss.
8055     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8056     MVT VVT = Op.getOperand(0).getSimpleValueType();
8057     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8058                                        DAG.getUNDEF(VVT), Mask);
8059     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8060                        DAG.getIntPtrConstant(0));
8061   }
8062
8063   if (VT.getSizeInBits() == 64) {
8064     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8065     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8066     //        to match extract_elt for f64.
8067     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8068     if (Idx == 0)
8069       return Op;
8070
8071     // UNPCKHPD the element to the lowest double word, then movsd.
8072     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8073     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8074     int Mask[2] = { 1, -1 };
8075     MVT VVT = Op.getOperand(0).getSimpleValueType();
8076     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8077                                        DAG.getUNDEF(VVT), Mask);
8078     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8079                        DAG.getIntPtrConstant(0));
8080   }
8081
8082   return SDValue();
8083 }
8084
8085 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8086   MVT VT = Op.getSimpleValueType();
8087   MVT EltVT = VT.getVectorElementType();
8088   SDLoc dl(Op);
8089
8090   SDValue N0 = Op.getOperand(0);
8091   SDValue N1 = Op.getOperand(1);
8092   SDValue N2 = Op.getOperand(2);
8093
8094   if (!VT.is128BitVector())
8095     return SDValue();
8096
8097   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8098       isa<ConstantSDNode>(N2)) {
8099     unsigned Opc;
8100     if (VT == MVT::v8i16)
8101       Opc = X86ISD::PINSRW;
8102     else if (VT == MVT::v16i8)
8103       Opc = X86ISD::PINSRB;
8104     else
8105       Opc = X86ISD::PINSRB;
8106
8107     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8108     // argument.
8109     if (N1.getValueType() != MVT::i32)
8110       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8111     if (N2.getValueType() != MVT::i32)
8112       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8113     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8114   }
8115
8116   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8117     // Bits [7:6] of the constant are the source select.  This will always be
8118     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8119     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8120     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8121     // Bits [5:4] of the constant are the destination select.  This is the
8122     //  value of the incoming immediate.
8123     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8124     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8125     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8126     // Create this as a scalar to vector..
8127     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8128     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8129   }
8130
8131   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8132     // PINSR* works with constant index.
8133     return Op;
8134   }
8135   return SDValue();
8136 }
8137
8138 /// Insert one bit to mask vector, like v16i1 or v8i1.
8139 /// AVX-512 feature.
8140 SDValue 
8141 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8142   SDLoc dl(Op);
8143   SDValue Vec = Op.getOperand(0);
8144   SDValue Elt = Op.getOperand(1);
8145   SDValue Idx = Op.getOperand(2);
8146   MVT VecVT = Vec.getSimpleValueType();
8147
8148   if (!isa<ConstantSDNode>(Idx)) {
8149     // Non constant index. Extend source and destination,
8150     // insert element and then truncate the result.
8151     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8152     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8153     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8154       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8155       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8156     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8157   }
8158
8159   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8160   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8161   if (Vec.getOpcode() == ISD::UNDEF)
8162     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8163                        DAG.getConstant(IdxVal, MVT::i8));
8164   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8165   unsigned MaxSift = rc->getSize()*8 - 1;
8166   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8167                     DAG.getConstant(MaxSift, MVT::i8));
8168   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8169                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8170   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8171 }
8172 SDValue
8173 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8174   MVT VT = Op.getSimpleValueType();
8175   MVT EltVT = VT.getVectorElementType();
8176   
8177   if (EltVT == MVT::i1)
8178     return InsertBitToMaskVector(Op, DAG);
8179
8180   SDLoc dl(Op);
8181   SDValue N0 = Op.getOperand(0);
8182   SDValue N1 = Op.getOperand(1);
8183   SDValue N2 = Op.getOperand(2);
8184
8185   // If this is a 256-bit vector result, first extract the 128-bit vector,
8186   // insert the element into the extracted half and then place it back.
8187   if (VT.is256BitVector() || VT.is512BitVector()) {
8188     if (!isa<ConstantSDNode>(N2))
8189       return SDValue();
8190
8191     // Get the desired 128-bit vector half.
8192     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8193     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8194
8195     // Insert the element into the desired half.
8196     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8197     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8198
8199     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8200                     DAG.getConstant(IdxIn128, MVT::i32));
8201
8202     // Insert the changed part back to the 256-bit vector
8203     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8204   }
8205
8206   if (Subtarget->hasSSE41())
8207     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8208
8209   if (EltVT == MVT::i8)
8210     return SDValue();
8211
8212   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8213     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8214     // as its second argument.
8215     if (N1.getValueType() != MVT::i32)
8216       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8217     if (N2.getValueType() != MVT::i32)
8218       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8219     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8220   }
8221   return SDValue();
8222 }
8223
8224 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8225   SDLoc dl(Op);
8226   MVT OpVT = Op.getSimpleValueType();
8227
8228   // If this is a 256-bit vector result, first insert into a 128-bit
8229   // vector and then insert into the 256-bit vector.
8230   if (!OpVT.is128BitVector()) {
8231     // Insert into a 128-bit vector.
8232     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8233     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8234                                  OpVT.getVectorNumElements() / SizeFactor);
8235
8236     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8237
8238     // Insert the 128-bit vector.
8239     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8240   }
8241
8242   if (OpVT == MVT::v1i64 &&
8243       Op.getOperand(0).getValueType() == MVT::i64)
8244     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8245
8246   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8247   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8248   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8249                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8250 }
8251
8252 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8253 // a simple subregister reference or explicit instructions to grab
8254 // upper bits of a vector.
8255 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8256                                       SelectionDAG &DAG) {
8257   SDLoc dl(Op);
8258   SDValue In =  Op.getOperand(0);
8259   SDValue Idx = Op.getOperand(1);
8260   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8261   MVT ResVT   = Op.getSimpleValueType();
8262   MVT InVT    = In.getSimpleValueType();
8263
8264   if (Subtarget->hasFp256()) {
8265     if (ResVT.is128BitVector() &&
8266         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8267         isa<ConstantSDNode>(Idx)) {
8268       return Extract128BitVector(In, IdxVal, DAG, dl);
8269     }
8270     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8271         isa<ConstantSDNode>(Idx)) {
8272       return Extract256BitVector(In, IdxVal, DAG, dl);
8273     }
8274   }
8275   return SDValue();
8276 }
8277
8278 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8279 // simple superregister reference or explicit instructions to insert
8280 // the upper bits of a vector.
8281 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8282                                      SelectionDAG &DAG) {
8283   if (Subtarget->hasFp256()) {
8284     SDLoc dl(Op.getNode());
8285     SDValue Vec = Op.getNode()->getOperand(0);
8286     SDValue SubVec = Op.getNode()->getOperand(1);
8287     SDValue Idx = Op.getNode()->getOperand(2);
8288
8289     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8290          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8291         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8292         isa<ConstantSDNode>(Idx)) {
8293       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8294       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8295     }
8296
8297     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8298         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8299         isa<ConstantSDNode>(Idx)) {
8300       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8301       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8302     }
8303   }
8304   return SDValue();
8305 }
8306
8307 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8308 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8309 // one of the above mentioned nodes. It has to be wrapped because otherwise
8310 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8311 // be used to form addressing mode. These wrapped nodes will be selected
8312 // into MOV32ri.
8313 SDValue
8314 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8315   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8316
8317   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8318   // global base reg.
8319   unsigned char OpFlag = 0;
8320   unsigned WrapperKind = X86ISD::Wrapper;
8321   CodeModel::Model M = getTargetMachine().getCodeModel();
8322
8323   if (Subtarget->isPICStyleRIPRel() &&
8324       (M == CodeModel::Small || M == CodeModel::Kernel))
8325     WrapperKind = X86ISD::WrapperRIP;
8326   else if (Subtarget->isPICStyleGOT())
8327     OpFlag = X86II::MO_GOTOFF;
8328   else if (Subtarget->isPICStyleStubPIC())
8329     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8330
8331   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8332                                              CP->getAlignment(),
8333                                              CP->getOffset(), OpFlag);
8334   SDLoc DL(CP);
8335   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8336   // With PIC, the address is actually $g + Offset.
8337   if (OpFlag) {
8338     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8339                          DAG.getNode(X86ISD::GlobalBaseReg,
8340                                      SDLoc(), getPointerTy()),
8341                          Result);
8342   }
8343
8344   return Result;
8345 }
8346
8347 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8348   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8349
8350   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8351   // global base reg.
8352   unsigned char OpFlag = 0;
8353   unsigned WrapperKind = X86ISD::Wrapper;
8354   CodeModel::Model M = getTargetMachine().getCodeModel();
8355
8356   if (Subtarget->isPICStyleRIPRel() &&
8357       (M == CodeModel::Small || M == CodeModel::Kernel))
8358     WrapperKind = X86ISD::WrapperRIP;
8359   else if (Subtarget->isPICStyleGOT())
8360     OpFlag = X86II::MO_GOTOFF;
8361   else if (Subtarget->isPICStyleStubPIC())
8362     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8363
8364   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8365                                           OpFlag);
8366   SDLoc DL(JT);
8367   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8368
8369   // With PIC, the address is actually $g + Offset.
8370   if (OpFlag)
8371     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8372                          DAG.getNode(X86ISD::GlobalBaseReg,
8373                                      SDLoc(), getPointerTy()),
8374                          Result);
8375
8376   return Result;
8377 }
8378
8379 SDValue
8380 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8381   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8382
8383   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8384   // global base reg.
8385   unsigned char OpFlag = 0;
8386   unsigned WrapperKind = X86ISD::Wrapper;
8387   CodeModel::Model M = getTargetMachine().getCodeModel();
8388
8389   if (Subtarget->isPICStyleRIPRel() &&
8390       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8391     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8392       OpFlag = X86II::MO_GOTPCREL;
8393     WrapperKind = X86ISD::WrapperRIP;
8394   } else if (Subtarget->isPICStyleGOT()) {
8395     OpFlag = X86II::MO_GOT;
8396   } else if (Subtarget->isPICStyleStubPIC()) {
8397     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8398   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8399     OpFlag = X86II::MO_DARWIN_NONLAZY;
8400   }
8401
8402   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8403
8404   SDLoc DL(Op);
8405   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8406
8407   // With PIC, the address is actually $g + Offset.
8408   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8409       !Subtarget->is64Bit()) {
8410     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8411                          DAG.getNode(X86ISD::GlobalBaseReg,
8412                                      SDLoc(), getPointerTy()),
8413                          Result);
8414   }
8415
8416   // For symbols that require a load from a stub to get the address, emit the
8417   // load.
8418   if (isGlobalStubReference(OpFlag))
8419     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8420                          MachinePointerInfo::getGOT(), false, false, false, 0);
8421
8422   return Result;
8423 }
8424
8425 SDValue
8426 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8427   // Create the TargetBlockAddressAddress node.
8428   unsigned char OpFlags =
8429     Subtarget->ClassifyBlockAddressReference();
8430   CodeModel::Model M = getTargetMachine().getCodeModel();
8431   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8432   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8433   SDLoc dl(Op);
8434   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8435                                              OpFlags);
8436
8437   if (Subtarget->isPICStyleRIPRel() &&
8438       (M == CodeModel::Small || M == CodeModel::Kernel))
8439     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8440   else
8441     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8442
8443   // With PIC, the address is actually $g + Offset.
8444   if (isGlobalRelativeToPICBase(OpFlags)) {
8445     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8446                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8447                          Result);
8448   }
8449
8450   return Result;
8451 }
8452
8453 SDValue
8454 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8455                                       int64_t Offset, SelectionDAG &DAG) const {
8456   // Create the TargetGlobalAddress node, folding in the constant
8457   // offset if it is legal.
8458   unsigned char OpFlags =
8459     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8460   CodeModel::Model M = getTargetMachine().getCodeModel();
8461   SDValue Result;
8462   if (OpFlags == X86II::MO_NO_FLAG &&
8463       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8464     // A direct static reference to a global.
8465     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8466     Offset = 0;
8467   } else {
8468     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8469   }
8470
8471   if (Subtarget->isPICStyleRIPRel() &&
8472       (M == CodeModel::Small || M == CodeModel::Kernel))
8473     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8474   else
8475     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8476
8477   // With PIC, the address is actually $g + Offset.
8478   if (isGlobalRelativeToPICBase(OpFlags)) {
8479     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8480                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8481                          Result);
8482   }
8483
8484   // For globals that require a load from a stub to get the address, emit the
8485   // load.
8486   if (isGlobalStubReference(OpFlags))
8487     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8488                          MachinePointerInfo::getGOT(), false, false, false, 0);
8489
8490   // If there was a non-zero offset that we didn't fold, create an explicit
8491   // addition for it.
8492   if (Offset != 0)
8493     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8494                          DAG.getConstant(Offset, getPointerTy()));
8495
8496   return Result;
8497 }
8498
8499 SDValue
8500 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8501   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8502   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8503   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8504 }
8505
8506 static SDValue
8507 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8508            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8509            unsigned char OperandFlags, bool LocalDynamic = false) {
8510   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8511   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8512   SDLoc dl(GA);
8513   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8514                                            GA->getValueType(0),
8515                                            GA->getOffset(),
8516                                            OperandFlags);
8517
8518   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8519                                            : X86ISD::TLSADDR;
8520
8521   if (InFlag) {
8522     SDValue Ops[] = { Chain,  TGA, *InFlag };
8523     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8524   } else {
8525     SDValue Ops[]  = { Chain, TGA };
8526     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8527   }
8528
8529   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8530   MFI->setAdjustsStack(true);
8531
8532   SDValue Flag = Chain.getValue(1);
8533   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8534 }
8535
8536 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8537 static SDValue
8538 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8539                                 const EVT PtrVT) {
8540   SDValue InFlag;
8541   SDLoc dl(GA);  // ? function entry point might be better
8542   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8543                                    DAG.getNode(X86ISD::GlobalBaseReg,
8544                                                SDLoc(), PtrVT), InFlag);
8545   InFlag = Chain.getValue(1);
8546
8547   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8548 }
8549
8550 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8551 static SDValue
8552 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8553                                 const EVT PtrVT) {
8554   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8555                     X86::RAX, X86II::MO_TLSGD);
8556 }
8557
8558 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8559                                            SelectionDAG &DAG,
8560                                            const EVT PtrVT,
8561                                            bool is64Bit) {
8562   SDLoc dl(GA);
8563
8564   // Get the start address of the TLS block for this module.
8565   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8566       .getInfo<X86MachineFunctionInfo>();
8567   MFI->incNumLocalDynamicTLSAccesses();
8568
8569   SDValue Base;
8570   if (is64Bit) {
8571     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8572                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8573   } else {
8574     SDValue InFlag;
8575     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8576         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8577     InFlag = Chain.getValue(1);
8578     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8579                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8580   }
8581
8582   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8583   // of Base.
8584
8585   // Build x@dtpoff.
8586   unsigned char OperandFlags = X86II::MO_DTPOFF;
8587   unsigned WrapperKind = X86ISD::Wrapper;
8588   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8589                                            GA->getValueType(0),
8590                                            GA->getOffset(), OperandFlags);
8591   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8592
8593   // Add x@dtpoff with the base.
8594   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8595 }
8596
8597 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8598 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8599                                    const EVT PtrVT, TLSModel::Model model,
8600                                    bool is64Bit, bool isPIC) {
8601   SDLoc dl(GA);
8602
8603   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8604   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8605                                                          is64Bit ? 257 : 256));
8606
8607   SDValue ThreadPointer =
8608       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8609                   MachinePointerInfo(Ptr), false, false, false, 0);
8610
8611   unsigned char OperandFlags = 0;
8612   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8613   // initialexec.
8614   unsigned WrapperKind = X86ISD::Wrapper;
8615   if (model == TLSModel::LocalExec) {
8616     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8617   } else if (model == TLSModel::InitialExec) {
8618     if (is64Bit) {
8619       OperandFlags = X86II::MO_GOTTPOFF;
8620       WrapperKind = X86ISD::WrapperRIP;
8621     } else {
8622       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8623     }
8624   } else {
8625     llvm_unreachable("Unexpected model");
8626   }
8627
8628   // emit "addl x@ntpoff,%eax" (local exec)
8629   // or "addl x@indntpoff,%eax" (initial exec)
8630   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8631   SDValue TGA =
8632       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8633                                  GA->getOffset(), OperandFlags);
8634   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8635
8636   if (model == TLSModel::InitialExec) {
8637     if (isPIC && !is64Bit) {
8638       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8639                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8640                            Offset);
8641     }
8642
8643     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8644                          MachinePointerInfo::getGOT(), false, false, false, 0);
8645   }
8646
8647   // The address of the thread local variable is the add of the thread
8648   // pointer with the offset of the variable.
8649   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8650 }
8651
8652 SDValue
8653 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8654
8655   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8656   const GlobalValue *GV = GA->getGlobal();
8657
8658   if (Subtarget->isTargetELF()) {
8659     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8660
8661     switch (model) {
8662       case TLSModel::GeneralDynamic:
8663         if (Subtarget->is64Bit())
8664           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8665         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8666       case TLSModel::LocalDynamic:
8667         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8668                                            Subtarget->is64Bit());
8669       case TLSModel::InitialExec:
8670       case TLSModel::LocalExec:
8671         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8672                                    Subtarget->is64Bit(),
8673                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8674     }
8675     llvm_unreachable("Unknown TLS model.");
8676   }
8677
8678   if (Subtarget->isTargetDarwin()) {
8679     // Darwin only has one model of TLS.  Lower to that.
8680     unsigned char OpFlag = 0;
8681     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8682                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8683
8684     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8685     // global base reg.
8686     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8687                   !Subtarget->is64Bit();
8688     if (PIC32)
8689       OpFlag = X86II::MO_TLVP_PIC_BASE;
8690     else
8691       OpFlag = X86II::MO_TLVP;
8692     SDLoc DL(Op);
8693     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8694                                                 GA->getValueType(0),
8695                                                 GA->getOffset(), OpFlag);
8696     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8697
8698     // With PIC32, the address is actually $g + Offset.
8699     if (PIC32)
8700       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8701                            DAG.getNode(X86ISD::GlobalBaseReg,
8702                                        SDLoc(), getPointerTy()),
8703                            Offset);
8704
8705     // Lowering the machine isd will make sure everything is in the right
8706     // location.
8707     SDValue Chain = DAG.getEntryNode();
8708     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8709     SDValue Args[] = { Chain, Offset };
8710     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8711
8712     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8713     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8714     MFI->setAdjustsStack(true);
8715
8716     // And our return value (tls address) is in the standard call return value
8717     // location.
8718     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8719     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8720                               Chain.getValue(1));
8721   }
8722
8723   if (Subtarget->isTargetKnownWindowsMSVC() ||
8724       Subtarget->isTargetWindowsGNU()) {
8725     // Just use the implicit TLS architecture
8726     // Need to generate someting similar to:
8727     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8728     //                                  ; from TEB
8729     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8730     //   mov     rcx, qword [rdx+rcx*8]
8731     //   mov     eax, .tls$:tlsvar
8732     //   [rax+rcx] contains the address
8733     // Windows 64bit: gs:0x58
8734     // Windows 32bit: fs:__tls_array
8735
8736     // If GV is an alias then use the aliasee for determining
8737     // thread-localness.
8738     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8739       GV = GA->getAliasedGlobal();
8740     SDLoc dl(GA);
8741     SDValue Chain = DAG.getEntryNode();
8742
8743     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8744     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8745     // use its literal value of 0x2C.
8746     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8747                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8748                                                              256)
8749                                         : Type::getInt32PtrTy(*DAG.getContext(),
8750                                                               257));
8751
8752     SDValue TlsArray =
8753         Subtarget->is64Bit()
8754             ? DAG.getIntPtrConstant(0x58)
8755             : (Subtarget->isTargetWindowsGNU()
8756                    ? DAG.getIntPtrConstant(0x2C)
8757                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8758
8759     SDValue ThreadPointer =
8760         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8761                     MachinePointerInfo(Ptr), false, false, false, 0);
8762
8763     // Load the _tls_index variable
8764     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8765     if (Subtarget->is64Bit())
8766       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8767                            IDX, MachinePointerInfo(), MVT::i32,
8768                            false, false, 0);
8769     else
8770       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8771                         false, false, false, 0);
8772
8773     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8774                                     getPointerTy());
8775     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8776
8777     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8778     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8779                       false, false, false, 0);
8780
8781     // Get the offset of start of .tls section
8782     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8783                                              GA->getValueType(0),
8784                                              GA->getOffset(), X86II::MO_SECREL);
8785     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8786
8787     // The address of the thread local variable is the add of the thread
8788     // pointer with the offset of the variable.
8789     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8790   }
8791
8792   llvm_unreachable("TLS not implemented for this target.");
8793 }
8794
8795 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8796 /// and take a 2 x i32 value to shift plus a shift amount.
8797 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8798   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8799   MVT VT = Op.getSimpleValueType();
8800   unsigned VTBits = VT.getSizeInBits();
8801   SDLoc dl(Op);
8802   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8803   SDValue ShOpLo = Op.getOperand(0);
8804   SDValue ShOpHi = Op.getOperand(1);
8805   SDValue ShAmt  = Op.getOperand(2);
8806   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8807   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8808   // during isel.
8809   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8810                                   DAG.getConstant(VTBits - 1, MVT::i8));
8811   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8812                                      DAG.getConstant(VTBits - 1, MVT::i8))
8813                        : DAG.getConstant(0, VT);
8814
8815   SDValue Tmp2, Tmp3;
8816   if (Op.getOpcode() == ISD::SHL_PARTS) {
8817     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8818     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8819   } else {
8820     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8821     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8822   }
8823
8824   // If the shift amount is larger or equal than the width of a part we can't
8825   // rely on the results of shld/shrd. Insert a test and select the appropriate
8826   // values for large shift amounts.
8827   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8828                                 DAG.getConstant(VTBits, MVT::i8));
8829   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8830                              AndNode, DAG.getConstant(0, MVT::i8));
8831
8832   SDValue Hi, Lo;
8833   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8834   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8835   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8836
8837   if (Op.getOpcode() == ISD::SHL_PARTS) {
8838     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8839     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8840   } else {
8841     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8842     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8843   }
8844
8845   SDValue Ops[2] = { Lo, Hi };
8846   return DAG.getMergeValues(Ops, dl);
8847 }
8848
8849 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8850                                            SelectionDAG &DAG) const {
8851   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8852
8853   if (SrcVT.isVector())
8854     return SDValue();
8855
8856   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8857          "Unknown SINT_TO_FP to lower!");
8858
8859   // These are really Legal; return the operand so the caller accepts it as
8860   // Legal.
8861   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8862     return Op;
8863   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8864       Subtarget->is64Bit()) {
8865     return Op;
8866   }
8867
8868   SDLoc dl(Op);
8869   unsigned Size = SrcVT.getSizeInBits()/8;
8870   MachineFunction &MF = DAG.getMachineFunction();
8871   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8872   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8873   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8874                                StackSlot,
8875                                MachinePointerInfo::getFixedStack(SSFI),
8876                                false, false, 0);
8877   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8878 }
8879
8880 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8881                                      SDValue StackSlot,
8882                                      SelectionDAG &DAG) const {
8883   // Build the FILD
8884   SDLoc DL(Op);
8885   SDVTList Tys;
8886   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8887   if (useSSE)
8888     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8889   else
8890     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8891
8892   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8893
8894   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8895   MachineMemOperand *MMO;
8896   if (FI) {
8897     int SSFI = FI->getIndex();
8898     MMO =
8899       DAG.getMachineFunction()
8900       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8901                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8902   } else {
8903     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8904     StackSlot = StackSlot.getOperand(1);
8905   }
8906   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8907   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8908                                            X86ISD::FILD, DL,
8909                                            Tys, Ops, SrcVT, MMO);
8910
8911   if (useSSE) {
8912     Chain = Result.getValue(1);
8913     SDValue InFlag = Result.getValue(2);
8914
8915     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8916     // shouldn't be necessary except that RFP cannot be live across
8917     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8918     MachineFunction &MF = DAG.getMachineFunction();
8919     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8920     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8921     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8922     Tys = DAG.getVTList(MVT::Other);
8923     SDValue Ops[] = {
8924       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8925     };
8926     MachineMemOperand *MMO =
8927       DAG.getMachineFunction()
8928       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8929                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8930
8931     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8932                                     Ops, Op.getValueType(), MMO);
8933     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8934                          MachinePointerInfo::getFixedStack(SSFI),
8935                          false, false, false, 0);
8936   }
8937
8938   return Result;
8939 }
8940
8941 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8942 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8943                                                SelectionDAG &DAG) const {
8944   // This algorithm is not obvious. Here it is what we're trying to output:
8945   /*
8946      movq       %rax,  %xmm0
8947      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8948      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8949      #ifdef __SSE3__
8950        haddpd   %xmm0, %xmm0
8951      #else
8952        pshufd   $0x4e, %xmm0, %xmm1
8953        addpd    %xmm1, %xmm0
8954      #endif
8955   */
8956
8957   SDLoc dl(Op);
8958   LLVMContext *Context = DAG.getContext();
8959
8960   // Build some magic constants.
8961   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8962   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8963   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8964
8965   SmallVector<Constant*,2> CV1;
8966   CV1.push_back(
8967     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8968                                       APInt(64, 0x4330000000000000ULL))));
8969   CV1.push_back(
8970     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8971                                       APInt(64, 0x4530000000000000ULL))));
8972   Constant *C1 = ConstantVector::get(CV1);
8973   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8974
8975   // Load the 64-bit value into an XMM register.
8976   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8977                             Op.getOperand(0));
8978   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8979                               MachinePointerInfo::getConstantPool(),
8980                               false, false, false, 16);
8981   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8982                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8983                               CLod0);
8984
8985   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8986                               MachinePointerInfo::getConstantPool(),
8987                               false, false, false, 16);
8988   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8989   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8990   SDValue Result;
8991
8992   if (Subtarget->hasSSE3()) {
8993     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8994     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8995   } else {
8996     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8997     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8998                                            S2F, 0x4E, DAG);
8999     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9000                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9001                          Sub);
9002   }
9003
9004   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9005                      DAG.getIntPtrConstant(0));
9006 }
9007
9008 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9009 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9010                                                SelectionDAG &DAG) const {
9011   SDLoc dl(Op);
9012   // FP constant to bias correct the final result.
9013   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9014                                    MVT::f64);
9015
9016   // Load the 32-bit value into an XMM register.
9017   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9018                              Op.getOperand(0));
9019
9020   // Zero out the upper parts of the register.
9021   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9022
9023   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9024                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9025                      DAG.getIntPtrConstant(0));
9026
9027   // Or the load with the bias.
9028   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9029                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9030                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9031                                                    MVT::v2f64, Load)),
9032                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9033                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9034                                                    MVT::v2f64, Bias)));
9035   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9036                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9037                    DAG.getIntPtrConstant(0));
9038
9039   // Subtract the bias.
9040   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9041
9042   // Handle final rounding.
9043   EVT DestVT = Op.getValueType();
9044
9045   if (DestVT.bitsLT(MVT::f64))
9046     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9047                        DAG.getIntPtrConstant(0));
9048   if (DestVT.bitsGT(MVT::f64))
9049     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9050
9051   // Handle final rounding.
9052   return Sub;
9053 }
9054
9055 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9056                                                SelectionDAG &DAG) const {
9057   SDValue N0 = Op.getOperand(0);
9058   MVT SVT = N0.getSimpleValueType();
9059   SDLoc dl(Op);
9060
9061   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9062           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9063          "Custom UINT_TO_FP is not supported!");
9064
9065   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9066   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9067                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9068 }
9069
9070 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9071                                            SelectionDAG &DAG) const {
9072   SDValue N0 = Op.getOperand(0);
9073   SDLoc dl(Op);
9074
9075   if (Op.getValueType().isVector())
9076     return lowerUINT_TO_FP_vec(Op, DAG);
9077
9078   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9079   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9080   // the optimization here.
9081   if (DAG.SignBitIsZero(N0))
9082     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9083
9084   MVT SrcVT = N0.getSimpleValueType();
9085   MVT DstVT = Op.getSimpleValueType();
9086   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9087     return LowerUINT_TO_FP_i64(Op, DAG);
9088   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9089     return LowerUINT_TO_FP_i32(Op, DAG);
9090   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9091     return SDValue();
9092
9093   // Make a 64-bit buffer, and use it to build an FILD.
9094   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9095   if (SrcVT == MVT::i32) {
9096     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9097     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9098                                      getPointerTy(), StackSlot, WordOff);
9099     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9100                                   StackSlot, MachinePointerInfo(),
9101                                   false, false, 0);
9102     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9103                                   OffsetSlot, MachinePointerInfo(),
9104                                   false, false, 0);
9105     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9106     return Fild;
9107   }
9108
9109   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9110   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9111                                StackSlot, MachinePointerInfo(),
9112                                false, false, 0);
9113   // For i64 source, we need to add the appropriate power of 2 if the input
9114   // was negative.  This is the same as the optimization in
9115   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9116   // we must be careful to do the computation in x87 extended precision, not
9117   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9118   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9119   MachineMemOperand *MMO =
9120     DAG.getMachineFunction()
9121     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9122                           MachineMemOperand::MOLoad, 8, 8);
9123
9124   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9125   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9126   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9127                                          MVT::i64, MMO);
9128
9129   APInt FF(32, 0x5F800000ULL);
9130
9131   // Check whether the sign bit is set.
9132   SDValue SignSet = DAG.getSetCC(dl,
9133                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9134                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9135                                  ISD::SETLT);
9136
9137   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9138   SDValue FudgePtr = DAG.getConstantPool(
9139                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9140                                          getPointerTy());
9141
9142   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9143   SDValue Zero = DAG.getIntPtrConstant(0);
9144   SDValue Four = DAG.getIntPtrConstant(4);
9145   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9146                                Zero, Four);
9147   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9148
9149   // Load the value out, extending it from f32 to f80.
9150   // FIXME: Avoid the extend by constructing the right constant pool?
9151   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9152                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9153                                  MVT::f32, false, false, 4);
9154   // Extend everything to 80 bits to force it to be done on x87.
9155   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9156   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9157 }
9158
9159 std::pair<SDValue,SDValue>
9160 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9161                                     bool IsSigned, bool IsReplace) const {
9162   SDLoc DL(Op);
9163
9164   EVT DstTy = Op.getValueType();
9165
9166   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9167     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9168     DstTy = MVT::i64;
9169   }
9170
9171   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9172          DstTy.getSimpleVT() >= MVT::i16 &&
9173          "Unknown FP_TO_INT to lower!");
9174
9175   // These are really Legal.
9176   if (DstTy == MVT::i32 &&
9177       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9178     return std::make_pair(SDValue(), SDValue());
9179   if (Subtarget->is64Bit() &&
9180       DstTy == MVT::i64 &&
9181       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9182     return std::make_pair(SDValue(), SDValue());
9183
9184   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9185   // stack slot, or into the FTOL runtime function.
9186   MachineFunction &MF = DAG.getMachineFunction();
9187   unsigned MemSize = DstTy.getSizeInBits()/8;
9188   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9189   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9190
9191   unsigned Opc;
9192   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9193     Opc = X86ISD::WIN_FTOL;
9194   else
9195     switch (DstTy.getSimpleVT().SimpleTy) {
9196     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9197     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9198     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9199     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9200     }
9201
9202   SDValue Chain = DAG.getEntryNode();
9203   SDValue Value = Op.getOperand(0);
9204   EVT TheVT = Op.getOperand(0).getValueType();
9205   // FIXME This causes a redundant load/store if the SSE-class value is already
9206   // in memory, such as if it is on the callstack.
9207   if (isScalarFPTypeInSSEReg(TheVT)) {
9208     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9209     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9210                          MachinePointerInfo::getFixedStack(SSFI),
9211                          false, false, 0);
9212     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9213     SDValue Ops[] = {
9214       Chain, StackSlot, DAG.getValueType(TheVT)
9215     };
9216
9217     MachineMemOperand *MMO =
9218       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9219                               MachineMemOperand::MOLoad, MemSize, MemSize);
9220     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9221     Chain = Value.getValue(1);
9222     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9223     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9224   }
9225
9226   MachineMemOperand *MMO =
9227     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9228                             MachineMemOperand::MOStore, MemSize, MemSize);
9229
9230   if (Opc != X86ISD::WIN_FTOL) {
9231     // Build the FP_TO_INT*_IN_MEM
9232     SDValue Ops[] = { Chain, Value, StackSlot };
9233     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9234                                            Ops, DstTy, MMO);
9235     return std::make_pair(FIST, StackSlot);
9236   } else {
9237     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9238       DAG.getVTList(MVT::Other, MVT::Glue),
9239       Chain, Value);
9240     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9241       MVT::i32, ftol.getValue(1));
9242     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9243       MVT::i32, eax.getValue(2));
9244     SDValue Ops[] = { eax, edx };
9245     SDValue pair = IsReplace
9246       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9247       : DAG.getMergeValues(Ops, DL);
9248     return std::make_pair(pair, SDValue());
9249   }
9250 }
9251
9252 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9253                               const X86Subtarget *Subtarget) {
9254   MVT VT = Op->getSimpleValueType(0);
9255   SDValue In = Op->getOperand(0);
9256   MVT InVT = In.getSimpleValueType();
9257   SDLoc dl(Op);
9258
9259   // Optimize vectors in AVX mode:
9260   //
9261   //   v8i16 -> v8i32
9262   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9263   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9264   //   Concat upper and lower parts.
9265   //
9266   //   v4i32 -> v4i64
9267   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9268   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9269   //   Concat upper and lower parts.
9270   //
9271
9272   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9273       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9274       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9275     return SDValue();
9276
9277   if (Subtarget->hasInt256())
9278     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9279
9280   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9281   SDValue Undef = DAG.getUNDEF(InVT);
9282   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9283   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9284   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9285
9286   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9287                              VT.getVectorNumElements()/2);
9288
9289   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9290   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9291
9292   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9293 }
9294
9295 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9296                                         SelectionDAG &DAG) {
9297   MVT VT = Op->getSimpleValueType(0);
9298   SDValue In = Op->getOperand(0);
9299   MVT InVT = In.getSimpleValueType();
9300   SDLoc DL(Op);
9301   unsigned int NumElts = VT.getVectorNumElements();
9302   if (NumElts != 8 && NumElts != 16)
9303     return SDValue();
9304
9305   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9306     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9307
9308   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9309   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9310   // Now we have only mask extension
9311   assert(InVT.getVectorElementType() == MVT::i1);
9312   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9313   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9314   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9315   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9316   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9317                            MachinePointerInfo::getConstantPool(),
9318                            false, false, false, Alignment);
9319
9320   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9321   if (VT.is512BitVector())
9322     return Brcst;
9323   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9324 }
9325
9326 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9327                                SelectionDAG &DAG) {
9328   if (Subtarget->hasFp256()) {
9329     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9330     if (Res.getNode())
9331       return Res;
9332   }
9333
9334   return SDValue();
9335 }
9336
9337 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9338                                 SelectionDAG &DAG) {
9339   SDLoc DL(Op);
9340   MVT VT = Op.getSimpleValueType();
9341   SDValue In = Op.getOperand(0);
9342   MVT SVT = In.getSimpleValueType();
9343
9344   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9345     return LowerZERO_EXTEND_AVX512(Op, DAG);
9346
9347   if (Subtarget->hasFp256()) {
9348     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9349     if (Res.getNode())
9350       return Res;
9351   }
9352
9353   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9354          VT.getVectorNumElements() != SVT.getVectorNumElements());
9355   return SDValue();
9356 }
9357
9358 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9359   SDLoc DL(Op);
9360   MVT VT = Op.getSimpleValueType();
9361   SDValue In = Op.getOperand(0);
9362   MVT InVT = In.getSimpleValueType();
9363
9364   if (VT == MVT::i1) {
9365     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9366            "Invalid scalar TRUNCATE operation");
9367     if (InVT == MVT::i32)
9368       return SDValue();
9369     if (InVT.getSizeInBits() == 64)
9370       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9371     else if (InVT.getSizeInBits() < 32)
9372       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9373     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9374   }
9375   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9376          "Invalid TRUNCATE operation");
9377
9378   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9379     if (VT.getVectorElementType().getSizeInBits() >=8)
9380       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9381
9382     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9383     unsigned NumElts = InVT.getVectorNumElements();
9384     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9385     if (InVT.getSizeInBits() < 512) {
9386       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9387       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9388       InVT = ExtVT;
9389     }
9390     
9391     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9392     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9393     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9394     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9395     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9396                            MachinePointerInfo::getConstantPool(),
9397                            false, false, false, Alignment);
9398     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9399     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9400     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9401   }
9402
9403   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9404     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9405     if (Subtarget->hasInt256()) {
9406       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9407       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9408       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9409                                 ShufMask);
9410       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9411                          DAG.getIntPtrConstant(0));
9412     }
9413
9414     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9415                                DAG.getIntPtrConstant(0));
9416     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9417                                DAG.getIntPtrConstant(2));
9418     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9419     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9420     static const int ShufMask[] = {0, 2, 4, 6};
9421     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9422   }
9423
9424   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9425     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9426     if (Subtarget->hasInt256()) {
9427       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9428
9429       SmallVector<SDValue,32> pshufbMask;
9430       for (unsigned i = 0; i < 2; ++i) {
9431         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9432         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9433         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9434         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9435         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9436         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9437         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9438         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9439         for (unsigned j = 0; j < 8; ++j)
9440           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9441       }
9442       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9443       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9444       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9445
9446       static const int ShufMask[] = {0,  2,  -1,  -1};
9447       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9448                                 &ShufMask[0]);
9449       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9450                        DAG.getIntPtrConstant(0));
9451       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9452     }
9453
9454     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9455                                DAG.getIntPtrConstant(0));
9456
9457     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9458                                DAG.getIntPtrConstant(4));
9459
9460     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9461     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9462
9463     // The PSHUFB mask:
9464     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9465                                    -1, -1, -1, -1, -1, -1, -1, -1};
9466
9467     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9468     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9469     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9470
9471     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9472     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9473
9474     // The MOVLHPS Mask:
9475     static const int ShufMask2[] = {0, 1, 4, 5};
9476     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9477     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9478   }
9479
9480   // Handle truncation of V256 to V128 using shuffles.
9481   if (!VT.is128BitVector() || !InVT.is256BitVector())
9482     return SDValue();
9483
9484   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9485
9486   unsigned NumElems = VT.getVectorNumElements();
9487   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9488
9489   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9490   // Prepare truncation shuffle mask
9491   for (unsigned i = 0; i != NumElems; ++i)
9492     MaskVec[i] = i * 2;
9493   SDValue V = DAG.getVectorShuffle(NVT, DL,
9494                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9495                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9496   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9497                      DAG.getIntPtrConstant(0));
9498 }
9499
9500 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9501                                            SelectionDAG &DAG) const {
9502   assert(!Op.getSimpleValueType().isVector());
9503
9504   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9505     /*IsSigned=*/ true, /*IsReplace=*/ false);
9506   SDValue FIST = Vals.first, StackSlot = Vals.second;
9507   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9508   if (!FIST.getNode()) return Op;
9509
9510   if (StackSlot.getNode())
9511     // Load the result.
9512     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9513                        FIST, StackSlot, MachinePointerInfo(),
9514                        false, false, false, 0);
9515
9516   // The node is the result.
9517   return FIST;
9518 }
9519
9520 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9521                                            SelectionDAG &DAG) const {
9522   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9523     /*IsSigned=*/ false, /*IsReplace=*/ false);
9524   SDValue FIST = Vals.first, StackSlot = Vals.second;
9525   assert(FIST.getNode() && "Unexpected failure");
9526
9527   if (StackSlot.getNode())
9528     // Load the result.
9529     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9530                        FIST, StackSlot, MachinePointerInfo(),
9531                        false, false, false, 0);
9532
9533   // The node is the result.
9534   return FIST;
9535 }
9536
9537 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9538   SDLoc DL(Op);
9539   MVT VT = Op.getSimpleValueType();
9540   SDValue In = Op.getOperand(0);
9541   MVT SVT = In.getSimpleValueType();
9542
9543   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9544
9545   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9546                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9547                                  In, DAG.getUNDEF(SVT)));
9548 }
9549
9550 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9551   LLVMContext *Context = DAG.getContext();
9552   SDLoc dl(Op);
9553   MVT VT = Op.getSimpleValueType();
9554   MVT EltVT = VT;
9555   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9556   if (VT.isVector()) {
9557     EltVT = VT.getVectorElementType();
9558     NumElts = VT.getVectorNumElements();
9559   }
9560   Constant *C;
9561   if (EltVT == MVT::f64)
9562     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9563                                           APInt(64, ~(1ULL << 63))));
9564   else
9565     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9566                                           APInt(32, ~(1U << 31))));
9567   C = ConstantVector::getSplat(NumElts, C);
9568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9569   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9570   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9571   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9572                              MachinePointerInfo::getConstantPool(),
9573                              false, false, false, Alignment);
9574   if (VT.isVector()) {
9575     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9576     return DAG.getNode(ISD::BITCAST, dl, VT,
9577                        DAG.getNode(ISD::AND, dl, ANDVT,
9578                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9579                                                Op.getOperand(0)),
9580                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9581   }
9582   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9583 }
9584
9585 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9586   LLVMContext *Context = DAG.getContext();
9587   SDLoc dl(Op);
9588   MVT VT = Op.getSimpleValueType();
9589   MVT EltVT = VT;
9590   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9591   if (VT.isVector()) {
9592     EltVT = VT.getVectorElementType();
9593     NumElts = VT.getVectorNumElements();
9594   }
9595   Constant *C;
9596   if (EltVT == MVT::f64)
9597     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9598                                           APInt(64, 1ULL << 63)));
9599   else
9600     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9601                                           APInt(32, 1U << 31)));
9602   C = ConstantVector::getSplat(NumElts, C);
9603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9604   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9605   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9606   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9607                              MachinePointerInfo::getConstantPool(),
9608                              false, false, false, Alignment);
9609   if (VT.isVector()) {
9610     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9611     return DAG.getNode(ISD::BITCAST, dl, VT,
9612                        DAG.getNode(ISD::XOR, dl, XORVT,
9613                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9614                                                Op.getOperand(0)),
9615                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9616   }
9617
9618   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9619 }
9620
9621 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9623   LLVMContext *Context = DAG.getContext();
9624   SDValue Op0 = Op.getOperand(0);
9625   SDValue Op1 = Op.getOperand(1);
9626   SDLoc dl(Op);
9627   MVT VT = Op.getSimpleValueType();
9628   MVT SrcVT = Op1.getSimpleValueType();
9629
9630   // If second operand is smaller, extend it first.
9631   if (SrcVT.bitsLT(VT)) {
9632     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9633     SrcVT = VT;
9634   }
9635   // And if it is bigger, shrink it first.
9636   if (SrcVT.bitsGT(VT)) {
9637     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9638     SrcVT = VT;
9639   }
9640
9641   // At this point the operands and the result should have the same
9642   // type, and that won't be f80 since that is not custom lowered.
9643
9644   // First get the sign bit of second operand.
9645   SmallVector<Constant*,4> CV;
9646   if (SrcVT == MVT::f64) {
9647     const fltSemantics &Sem = APFloat::IEEEdouble;
9648     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9649     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9650   } else {
9651     const fltSemantics &Sem = APFloat::IEEEsingle;
9652     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9653     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9654     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9655     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9656   }
9657   Constant *C = ConstantVector::get(CV);
9658   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9659   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9660                               MachinePointerInfo::getConstantPool(),
9661                               false, false, false, 16);
9662   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9663
9664   // Shift sign bit right or left if the two operands have different types.
9665   if (SrcVT.bitsGT(VT)) {
9666     // Op0 is MVT::f32, Op1 is MVT::f64.
9667     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9668     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9669                           DAG.getConstant(32, MVT::i32));
9670     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9671     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9672                           DAG.getIntPtrConstant(0));
9673   }
9674
9675   // Clear first operand sign bit.
9676   CV.clear();
9677   if (VT == MVT::f64) {
9678     const fltSemantics &Sem = APFloat::IEEEdouble;
9679     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9680                                                    APInt(64, ~(1ULL << 63)))));
9681     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9682   } else {
9683     const fltSemantics &Sem = APFloat::IEEEsingle;
9684     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9685                                                    APInt(32, ~(1U << 31)))));
9686     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9687     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9688     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9689   }
9690   C = ConstantVector::get(CV);
9691   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9692   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9693                               MachinePointerInfo::getConstantPool(),
9694                               false, false, false, 16);
9695   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9696
9697   // Or the value with the sign bit.
9698   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9699 }
9700
9701 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9702   SDValue N0 = Op.getOperand(0);
9703   SDLoc dl(Op);
9704   MVT VT = Op.getSimpleValueType();
9705
9706   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9707   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9708                                   DAG.getConstant(1, VT));
9709   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9710 }
9711
9712 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9713 //
9714 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9715                                       SelectionDAG &DAG) {
9716   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9717
9718   if (!Subtarget->hasSSE41())
9719     return SDValue();
9720
9721   if (!Op->hasOneUse())
9722     return SDValue();
9723
9724   SDNode *N = Op.getNode();
9725   SDLoc DL(N);
9726
9727   SmallVector<SDValue, 8> Opnds;
9728   DenseMap<SDValue, unsigned> VecInMap;
9729   SmallVector<SDValue, 8> VecIns;
9730   EVT VT = MVT::Other;
9731
9732   // Recognize a special case where a vector is casted into wide integer to
9733   // test all 0s.
9734   Opnds.push_back(N->getOperand(0));
9735   Opnds.push_back(N->getOperand(1));
9736
9737   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9738     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9739     // BFS traverse all OR'd operands.
9740     if (I->getOpcode() == ISD::OR) {
9741       Opnds.push_back(I->getOperand(0));
9742       Opnds.push_back(I->getOperand(1));
9743       // Re-evaluate the number of nodes to be traversed.
9744       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9745       continue;
9746     }
9747
9748     // Quit if a non-EXTRACT_VECTOR_ELT
9749     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9750       return SDValue();
9751
9752     // Quit if without a constant index.
9753     SDValue Idx = I->getOperand(1);
9754     if (!isa<ConstantSDNode>(Idx))
9755       return SDValue();
9756
9757     SDValue ExtractedFromVec = I->getOperand(0);
9758     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9759     if (M == VecInMap.end()) {
9760       VT = ExtractedFromVec.getValueType();
9761       // Quit if not 128/256-bit vector.
9762       if (!VT.is128BitVector() && !VT.is256BitVector())
9763         return SDValue();
9764       // Quit if not the same type.
9765       if (VecInMap.begin() != VecInMap.end() &&
9766           VT != VecInMap.begin()->first.getValueType())
9767         return SDValue();
9768       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9769       VecIns.push_back(ExtractedFromVec);
9770     }
9771     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9772   }
9773
9774   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9775          "Not extracted from 128-/256-bit vector.");
9776
9777   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9778
9779   for (DenseMap<SDValue, unsigned>::const_iterator
9780         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9781     // Quit if not all elements are used.
9782     if (I->second != FullMask)
9783       return SDValue();
9784   }
9785
9786   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9787
9788   // Cast all vectors into TestVT for PTEST.
9789   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9790     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9791
9792   // If more than one full vectors are evaluated, OR them first before PTEST.
9793   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9794     // Each iteration will OR 2 nodes and append the result until there is only
9795     // 1 node left, i.e. the final OR'd value of all vectors.
9796     SDValue LHS = VecIns[Slot];
9797     SDValue RHS = VecIns[Slot + 1];
9798     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9799   }
9800
9801   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9802                      VecIns.back(), VecIns.back());
9803 }
9804
9805 /// \brief return true if \c Op has a use that doesn't just read flags.
9806 static bool hasNonFlagsUse(SDValue Op) {
9807   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9808        ++UI) {
9809     SDNode *User = *UI;
9810     unsigned UOpNo = UI.getOperandNo();
9811     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9812       // Look pass truncate.
9813       UOpNo = User->use_begin().getOperandNo();
9814       User = *User->use_begin();
9815     }
9816
9817     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9818         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9819       return true;
9820   }
9821   return false;
9822 }
9823
9824 /// Emit nodes that will be selected as "test Op0,Op0", or something
9825 /// equivalent.
9826 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9827                                     SelectionDAG &DAG) const {
9828   if (Op.getValueType() == MVT::i1)
9829     // KORTEST instruction should be selected
9830     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9831                        DAG.getConstant(0, Op.getValueType()));
9832
9833   // CF and OF aren't always set the way we want. Determine which
9834   // of these we need.
9835   bool NeedCF = false;
9836   bool NeedOF = false;
9837   switch (X86CC) {
9838   default: break;
9839   case X86::COND_A: case X86::COND_AE:
9840   case X86::COND_B: case X86::COND_BE:
9841     NeedCF = true;
9842     break;
9843   case X86::COND_G: case X86::COND_GE:
9844   case X86::COND_L: case X86::COND_LE:
9845   case X86::COND_O: case X86::COND_NO:
9846     NeedOF = true;
9847     break;
9848   }
9849   // See if we can use the EFLAGS value from the operand instead of
9850   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9851   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9852   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9853     // Emit a CMP with 0, which is the TEST pattern.
9854     //if (Op.getValueType() == MVT::i1)
9855     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9856     //                     DAG.getConstant(0, MVT::i1));
9857     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9858                        DAG.getConstant(0, Op.getValueType()));
9859   }
9860   unsigned Opcode = 0;
9861   unsigned NumOperands = 0;
9862
9863   // Truncate operations may prevent the merge of the SETCC instruction
9864   // and the arithmetic instruction before it. Attempt to truncate the operands
9865   // of the arithmetic instruction and use a reduced bit-width instruction.
9866   bool NeedTruncation = false;
9867   SDValue ArithOp = Op;
9868   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9869     SDValue Arith = Op->getOperand(0);
9870     // Both the trunc and the arithmetic op need to have one user each.
9871     if (Arith->hasOneUse())
9872       switch (Arith.getOpcode()) {
9873         default: break;
9874         case ISD::ADD:
9875         case ISD::SUB:
9876         case ISD::AND:
9877         case ISD::OR:
9878         case ISD::XOR: {
9879           NeedTruncation = true;
9880           ArithOp = Arith;
9881         }
9882       }
9883   }
9884
9885   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9886   // which may be the result of a CAST.  We use the variable 'Op', which is the
9887   // non-casted variable when we check for possible users.
9888   switch (ArithOp.getOpcode()) {
9889   case ISD::ADD:
9890     // Due to an isel shortcoming, be conservative if this add is likely to be
9891     // selected as part of a load-modify-store instruction. When the root node
9892     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9893     // uses of other nodes in the match, such as the ADD in this case. This
9894     // leads to the ADD being left around and reselected, with the result being
9895     // two adds in the output.  Alas, even if none our users are stores, that
9896     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9897     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9898     // climbing the DAG back to the root, and it doesn't seem to be worth the
9899     // effort.
9900     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9901          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9902       if (UI->getOpcode() != ISD::CopyToReg &&
9903           UI->getOpcode() != ISD::SETCC &&
9904           UI->getOpcode() != ISD::STORE)
9905         goto default_case;
9906
9907     if (ConstantSDNode *C =
9908         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9909       // An add of one will be selected as an INC.
9910       if (C->getAPIntValue() == 1) {
9911         Opcode = X86ISD::INC;
9912         NumOperands = 1;
9913         break;
9914       }
9915
9916       // An add of negative one (subtract of one) will be selected as a DEC.
9917       if (C->getAPIntValue().isAllOnesValue()) {
9918         Opcode = X86ISD::DEC;
9919         NumOperands = 1;
9920         break;
9921       }
9922     }
9923
9924     // Otherwise use a regular EFLAGS-setting add.
9925     Opcode = X86ISD::ADD;
9926     NumOperands = 2;
9927     break;
9928   case ISD::SHL:
9929   case ISD::SRL:
9930     // If we have a constant logical shift that's only used in a comparison
9931     // against zero turn it into an equivalent AND. This allows turning it into
9932     // a TEST instruction later.
9933     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9934         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9935       EVT VT = Op.getValueType();
9936       unsigned BitWidth = VT.getSizeInBits();
9937       unsigned ShAmt = Op->getConstantOperandVal(1);
9938       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9939         break;
9940       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9941                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9942                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9943       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9944         break;
9945       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9946                                 DAG.getConstant(Mask, VT));
9947       DAG.ReplaceAllUsesWith(Op, New);
9948       Op = New;
9949     }
9950     break;
9951
9952   case ISD::AND:
9953     // If the primary and result isn't used, don't bother using X86ISD::AND,
9954     // because a TEST instruction will be better.
9955     if (!hasNonFlagsUse(Op))
9956       break;
9957     // FALL THROUGH
9958   case ISD::SUB:
9959   case ISD::OR:
9960   case ISD::XOR:
9961     // Due to the ISEL shortcoming noted above, be conservative if this op is
9962     // likely to be selected as part of a load-modify-store instruction.
9963     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9964            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9965       if (UI->getOpcode() == ISD::STORE)
9966         goto default_case;
9967
9968     // Otherwise use a regular EFLAGS-setting instruction.
9969     switch (ArithOp.getOpcode()) {
9970     default: llvm_unreachable("unexpected operator!");
9971     case ISD::SUB: Opcode = X86ISD::SUB; break;
9972     case ISD::XOR: Opcode = X86ISD::XOR; break;
9973     case ISD::AND: Opcode = X86ISD::AND; break;
9974     case ISD::OR: {
9975       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9976         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9977         if (EFLAGS.getNode())
9978           return EFLAGS;
9979       }
9980       Opcode = X86ISD::OR;
9981       break;
9982     }
9983     }
9984
9985     NumOperands = 2;
9986     break;
9987   case X86ISD::ADD:
9988   case X86ISD::SUB:
9989   case X86ISD::INC:
9990   case X86ISD::DEC:
9991   case X86ISD::OR:
9992   case X86ISD::XOR:
9993   case X86ISD::AND:
9994     return SDValue(Op.getNode(), 1);
9995   default:
9996   default_case:
9997     break;
9998   }
9999
10000   // If we found that truncation is beneficial, perform the truncation and
10001   // update 'Op'.
10002   if (NeedTruncation) {
10003     EVT VT = Op.getValueType();
10004     SDValue WideVal = Op->getOperand(0);
10005     EVT WideVT = WideVal.getValueType();
10006     unsigned ConvertedOp = 0;
10007     // Use a target machine opcode to prevent further DAGCombine
10008     // optimizations that may separate the arithmetic operations
10009     // from the setcc node.
10010     switch (WideVal.getOpcode()) {
10011       default: break;
10012       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10013       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10014       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10015       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10016       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10017     }
10018
10019     if (ConvertedOp) {
10020       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10021       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10022         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10023         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10024         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10025       }
10026     }
10027   }
10028
10029   if (Opcode == 0)
10030     // Emit a CMP with 0, which is the TEST pattern.
10031     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10032                        DAG.getConstant(0, Op.getValueType()));
10033
10034   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10035   SmallVector<SDValue, 4> Ops;
10036   for (unsigned i = 0; i != NumOperands; ++i)
10037     Ops.push_back(Op.getOperand(i));
10038
10039   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10040   DAG.ReplaceAllUsesWith(Op, New);
10041   return SDValue(New.getNode(), 1);
10042 }
10043
10044 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10045 /// equivalent.
10046 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10047                                    SDLoc dl, SelectionDAG &DAG) const {
10048   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10049     if (C->getAPIntValue() == 0)
10050       return EmitTest(Op0, X86CC, dl, DAG);
10051
10052      if (Op0.getValueType() == MVT::i1)
10053        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10054   }
10055  
10056   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10057        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10058     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10059     // This avoids subregister aliasing issues. Keep the smaller reference 
10060     // if we're optimizing for size, however, as that'll allow better folding 
10061     // of memory operations.
10062     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10063         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10064              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10065         !Subtarget->isAtom()) {
10066       unsigned ExtendOp =
10067           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10068       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10069       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10070     }
10071     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10072     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10073     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10074                               Op0, Op1);
10075     return SDValue(Sub.getNode(), 1);
10076   }
10077   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10078 }
10079
10080 /// Convert a comparison if required by the subtarget.
10081 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10082                                                  SelectionDAG &DAG) const {
10083   // If the subtarget does not support the FUCOMI instruction, floating-point
10084   // comparisons have to be converted.
10085   if (Subtarget->hasCMov() ||
10086       Cmp.getOpcode() != X86ISD::CMP ||
10087       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10088       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10089     return Cmp;
10090
10091   // The instruction selector will select an FUCOM instruction instead of
10092   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10093   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10094   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10095   SDLoc dl(Cmp);
10096   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10097   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10098   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10099                             DAG.getConstant(8, MVT::i8));
10100   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10101   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10102 }
10103
10104 static bool isAllOnes(SDValue V) {
10105   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10106   return C && C->isAllOnesValue();
10107 }
10108
10109 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10110 /// if it's possible.
10111 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10112                                      SDLoc dl, SelectionDAG &DAG) const {
10113   SDValue Op0 = And.getOperand(0);
10114   SDValue Op1 = And.getOperand(1);
10115   if (Op0.getOpcode() == ISD::TRUNCATE)
10116     Op0 = Op0.getOperand(0);
10117   if (Op1.getOpcode() == ISD::TRUNCATE)
10118     Op1 = Op1.getOperand(0);
10119
10120   SDValue LHS, RHS;
10121   if (Op1.getOpcode() == ISD::SHL)
10122     std::swap(Op0, Op1);
10123   if (Op0.getOpcode() == ISD::SHL) {
10124     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10125       if (And00C->getZExtValue() == 1) {
10126         // If we looked past a truncate, check that it's only truncating away
10127         // known zeros.
10128         unsigned BitWidth = Op0.getValueSizeInBits();
10129         unsigned AndBitWidth = And.getValueSizeInBits();
10130         if (BitWidth > AndBitWidth) {
10131           APInt Zeros, Ones;
10132           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10133           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10134             return SDValue();
10135         }
10136         LHS = Op1;
10137         RHS = Op0.getOperand(1);
10138       }
10139   } else if (Op1.getOpcode() == ISD::Constant) {
10140     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10141     uint64_t AndRHSVal = AndRHS->getZExtValue();
10142     SDValue AndLHS = Op0;
10143
10144     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10145       LHS = AndLHS.getOperand(0);
10146       RHS = AndLHS.getOperand(1);
10147     }
10148
10149     // Use BT if the immediate can't be encoded in a TEST instruction.
10150     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10151       LHS = AndLHS;
10152       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10153     }
10154   }
10155
10156   if (LHS.getNode()) {
10157     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10158     // instruction.  Since the shift amount is in-range-or-undefined, we know
10159     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10160     // the encoding for the i16 version is larger than the i32 version.
10161     // Also promote i16 to i32 for performance / code size reason.
10162     if (LHS.getValueType() == MVT::i8 ||
10163         LHS.getValueType() == MVT::i16)
10164       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10165
10166     // If the operand types disagree, extend the shift amount to match.  Since
10167     // BT ignores high bits (like shifts) we can use anyextend.
10168     if (LHS.getValueType() != RHS.getValueType())
10169       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10170
10171     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10172     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10173     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10174                        DAG.getConstant(Cond, MVT::i8), BT);
10175   }
10176
10177   return SDValue();
10178 }
10179
10180 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10181 /// mask CMPs.
10182 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10183                               SDValue &Op1) {
10184   unsigned SSECC;
10185   bool Swap = false;
10186
10187   // SSE Condition code mapping:
10188   //  0 - EQ
10189   //  1 - LT
10190   //  2 - LE
10191   //  3 - UNORD
10192   //  4 - NEQ
10193   //  5 - NLT
10194   //  6 - NLE
10195   //  7 - ORD
10196   switch (SetCCOpcode) {
10197   default: llvm_unreachable("Unexpected SETCC condition");
10198   case ISD::SETOEQ:
10199   case ISD::SETEQ:  SSECC = 0; break;
10200   case ISD::SETOGT:
10201   case ISD::SETGT:  Swap = true; // Fallthrough
10202   case ISD::SETLT:
10203   case ISD::SETOLT: SSECC = 1; break;
10204   case ISD::SETOGE:
10205   case ISD::SETGE:  Swap = true; // Fallthrough
10206   case ISD::SETLE:
10207   case ISD::SETOLE: SSECC = 2; break;
10208   case ISD::SETUO:  SSECC = 3; break;
10209   case ISD::SETUNE:
10210   case ISD::SETNE:  SSECC = 4; break;
10211   case ISD::SETULE: Swap = true; // Fallthrough
10212   case ISD::SETUGE: SSECC = 5; break;
10213   case ISD::SETULT: Swap = true; // Fallthrough
10214   case ISD::SETUGT: SSECC = 6; break;
10215   case ISD::SETO:   SSECC = 7; break;
10216   case ISD::SETUEQ:
10217   case ISD::SETONE: SSECC = 8; break;
10218   }
10219   if (Swap)
10220     std::swap(Op0, Op1);
10221
10222   return SSECC;
10223 }
10224
10225 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10226 // ones, and then concatenate the result back.
10227 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10228   MVT VT = Op.getSimpleValueType();
10229
10230   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10231          "Unsupported value type for operation");
10232
10233   unsigned NumElems = VT.getVectorNumElements();
10234   SDLoc dl(Op);
10235   SDValue CC = Op.getOperand(2);
10236
10237   // Extract the LHS vectors
10238   SDValue LHS = Op.getOperand(0);
10239   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10240   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10241
10242   // Extract the RHS vectors
10243   SDValue RHS = Op.getOperand(1);
10244   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10245   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10246
10247   // Issue the operation on the smaller types and concatenate the result back
10248   MVT EltVT = VT.getVectorElementType();
10249   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10250   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10251                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10252                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10253 }
10254
10255 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10256                                      const X86Subtarget *Subtarget) {
10257   SDValue Op0 = Op.getOperand(0);
10258   SDValue Op1 = Op.getOperand(1);
10259   SDValue CC = Op.getOperand(2);
10260   MVT VT = Op.getSimpleValueType();
10261   SDLoc dl(Op);
10262
10263   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10264          Op.getValueType().getScalarType() == MVT::i1 &&
10265          "Cannot set masked compare for this operation");
10266
10267   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10268   unsigned  Opc = 0;
10269   bool Unsigned = false;
10270   bool Swap = false;
10271   unsigned SSECC;
10272   switch (SetCCOpcode) {
10273   default: llvm_unreachable("Unexpected SETCC condition");
10274   case ISD::SETNE:  SSECC = 4; break;
10275   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10276   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10277   case ISD::SETLT:  Swap = true; //fall-through
10278   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10279   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10280   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10281   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10282   case ISD::SETULE: Unsigned = true; //fall-through
10283   case ISD::SETLE:  SSECC = 2; break;
10284   }
10285
10286   if (Swap)
10287     std::swap(Op0, Op1);
10288   if (Opc)
10289     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10290   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10291   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10292                      DAG.getConstant(SSECC, MVT::i8));
10293 }
10294
10295 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10296 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10297 /// return an empty value.
10298 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10299 {
10300   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10301   if (!BV)
10302     return SDValue();
10303
10304   MVT VT = Op1.getSimpleValueType();
10305   MVT EVT = VT.getVectorElementType();
10306   unsigned n = VT.getVectorNumElements();
10307   SmallVector<SDValue, 8> ULTOp1;
10308
10309   for (unsigned i = 0; i < n; ++i) {
10310     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10311     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10312       return SDValue();
10313
10314     // Avoid underflow.
10315     APInt Val = Elt->getAPIntValue();
10316     if (Val == 0)
10317       return SDValue();
10318
10319     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10320   }
10321
10322   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10323 }
10324
10325 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10326                            SelectionDAG &DAG) {
10327   SDValue Op0 = Op.getOperand(0);
10328   SDValue Op1 = Op.getOperand(1);
10329   SDValue CC = Op.getOperand(2);
10330   MVT VT = Op.getSimpleValueType();
10331   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10332   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10333   SDLoc dl(Op);
10334
10335   if (isFP) {
10336 #ifndef NDEBUG
10337     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10338     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10339 #endif
10340
10341     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10342     unsigned Opc = X86ISD::CMPP;
10343     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10344       assert(VT.getVectorNumElements() <= 16);
10345       Opc = X86ISD::CMPM;
10346     }
10347     // In the two special cases we can't handle, emit two comparisons.
10348     if (SSECC == 8) {
10349       unsigned CC0, CC1;
10350       unsigned CombineOpc;
10351       if (SetCCOpcode == ISD::SETUEQ) {
10352         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10353       } else {
10354         assert(SetCCOpcode == ISD::SETONE);
10355         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10356       }
10357
10358       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10359                                  DAG.getConstant(CC0, MVT::i8));
10360       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10361                                  DAG.getConstant(CC1, MVT::i8));
10362       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10363     }
10364     // Handle all other FP comparisons here.
10365     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10366                        DAG.getConstant(SSECC, MVT::i8));
10367   }
10368
10369   // Break 256-bit integer vector compare into smaller ones.
10370   if (VT.is256BitVector() && !Subtarget->hasInt256())
10371     return Lower256IntVSETCC(Op, DAG);
10372
10373   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10374   EVT OpVT = Op1.getValueType();
10375   if (Subtarget->hasAVX512()) {
10376     if (Op1.getValueType().is512BitVector() ||
10377         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10378       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10379
10380     // In AVX-512 architecture setcc returns mask with i1 elements,
10381     // But there is no compare instruction for i8 and i16 elements.
10382     // We are not talking about 512-bit operands in this case, these
10383     // types are illegal.
10384     if (MaskResult &&
10385         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10386          OpVT.getVectorElementType().getSizeInBits() >= 8))
10387       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10388                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10389   }
10390
10391   // We are handling one of the integer comparisons here.  Since SSE only has
10392   // GT and EQ comparisons for integer, swapping operands and multiple
10393   // operations may be required for some comparisons.
10394   unsigned Opc;
10395   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10396   bool Subus = false;
10397
10398   switch (SetCCOpcode) {
10399   default: llvm_unreachable("Unexpected SETCC condition");
10400   case ISD::SETNE:  Invert = true;
10401   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10402   case ISD::SETLT:  Swap = true;
10403   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10404   case ISD::SETGE:  Swap = true;
10405   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10406                     Invert = true; break;
10407   case ISD::SETULT: Swap = true;
10408   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10409                     FlipSigns = true; break;
10410   case ISD::SETUGE: Swap = true;
10411   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10412                     FlipSigns = true; Invert = true; break;
10413   }
10414
10415   // Special case: Use min/max operations for SETULE/SETUGE
10416   MVT VET = VT.getVectorElementType();
10417   bool hasMinMax =
10418        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10419     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10420
10421   if (hasMinMax) {
10422     switch (SetCCOpcode) {
10423     default: break;
10424     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10425     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10426     }
10427
10428     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10429   }
10430
10431   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10432   if (!MinMax && hasSubus) {
10433     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10434     // Op0 u<= Op1:
10435     //   t = psubus Op0, Op1
10436     //   pcmpeq t, <0..0>
10437     switch (SetCCOpcode) {
10438     default: break;
10439     case ISD::SETULT: {
10440       // If the comparison is against a constant we can turn this into a
10441       // setule.  With psubus, setule does not require a swap.  This is
10442       // beneficial because the constant in the register is no longer
10443       // destructed as the destination so it can be hoisted out of a loop.
10444       // Only do this pre-AVX since vpcmp* is no longer destructive.
10445       if (Subtarget->hasAVX())
10446         break;
10447       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10448       if (ULEOp1.getNode()) {
10449         Op1 = ULEOp1;
10450         Subus = true; Invert = false; Swap = false;
10451       }
10452       break;
10453     }
10454     // Psubus is better than flip-sign because it requires no inversion.
10455     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10456     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10457     }
10458
10459     if (Subus) {
10460       Opc = X86ISD::SUBUS;
10461       FlipSigns = false;
10462     }
10463   }
10464
10465   if (Swap)
10466     std::swap(Op0, Op1);
10467
10468   // Check that the operation in question is available (most are plain SSE2,
10469   // but PCMPGTQ and PCMPEQQ have different requirements).
10470   if (VT == MVT::v2i64) {
10471     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10472       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10473
10474       // First cast everything to the right type.
10475       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10476       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10477
10478       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10479       // bits of the inputs before performing those operations. The lower
10480       // compare is always unsigned.
10481       SDValue SB;
10482       if (FlipSigns) {
10483         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10484       } else {
10485         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10486         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10487         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10488                          Sign, Zero, Sign, Zero);
10489       }
10490       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10491       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10492
10493       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10494       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10495       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10496
10497       // Create masks for only the low parts/high parts of the 64 bit integers.
10498       static const int MaskHi[] = { 1, 1, 3, 3 };
10499       static const int MaskLo[] = { 0, 0, 2, 2 };
10500       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10501       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10502       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10503
10504       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10505       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10506
10507       if (Invert)
10508         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10509
10510       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10511     }
10512
10513     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10514       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10515       // pcmpeqd + pshufd + pand.
10516       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10517
10518       // First cast everything to the right type.
10519       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10520       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10521
10522       // Do the compare.
10523       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10524
10525       // Make sure the lower and upper halves are both all-ones.
10526       static const int Mask[] = { 1, 0, 3, 2 };
10527       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10528       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10529
10530       if (Invert)
10531         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10532
10533       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10534     }
10535   }
10536
10537   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10538   // bits of the inputs before performing those operations.
10539   if (FlipSigns) {
10540     EVT EltVT = VT.getVectorElementType();
10541     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10542     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10543     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10544   }
10545
10546   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10547
10548   // If the logical-not of the result is required, perform that now.
10549   if (Invert)
10550     Result = DAG.getNOT(dl, Result, VT);
10551
10552   if (MinMax)
10553     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10554
10555   if (Subus)
10556     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10557                          getZeroVector(VT, Subtarget, DAG, dl));
10558
10559   return Result;
10560 }
10561
10562 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10563
10564   MVT VT = Op.getSimpleValueType();
10565
10566   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10567
10568   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10569          && "SetCC type must be 8-bit or 1-bit integer");
10570   SDValue Op0 = Op.getOperand(0);
10571   SDValue Op1 = Op.getOperand(1);
10572   SDLoc dl(Op);
10573   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10574
10575   // Optimize to BT if possible.
10576   // Lower (X & (1 << N)) == 0 to BT(X, N).
10577   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10578   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10579   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10580       Op1.getOpcode() == ISD::Constant &&
10581       cast<ConstantSDNode>(Op1)->isNullValue() &&
10582       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10583     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10584     if (NewSetCC.getNode())
10585       return NewSetCC;
10586   }
10587
10588   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10589   // these.
10590   if (Op1.getOpcode() == ISD::Constant &&
10591       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10592        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10593       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10594
10595     // If the input is a setcc, then reuse the input setcc or use a new one with
10596     // the inverted condition.
10597     if (Op0.getOpcode() == X86ISD::SETCC) {
10598       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10599       bool Invert = (CC == ISD::SETNE) ^
10600         cast<ConstantSDNode>(Op1)->isNullValue();
10601       if (!Invert)
10602         return Op0;
10603
10604       CCode = X86::GetOppositeBranchCondition(CCode);
10605       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10606                                   DAG.getConstant(CCode, MVT::i8),
10607                                   Op0.getOperand(1));
10608       if (VT == MVT::i1)
10609         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10610       return SetCC;
10611     }
10612   }
10613   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10614       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10615       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10616
10617     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10618     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10619   }
10620
10621   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10622   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10623   if (X86CC == X86::COND_INVALID)
10624     return SDValue();
10625
10626   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10627   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10628   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10629                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10630   if (VT == MVT::i1)
10631     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10632   return SetCC;
10633 }
10634
10635 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10636 static bool isX86LogicalCmp(SDValue Op) {
10637   unsigned Opc = Op.getNode()->getOpcode();
10638   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10639       Opc == X86ISD::SAHF)
10640     return true;
10641   if (Op.getResNo() == 1 &&
10642       (Opc == X86ISD::ADD ||
10643        Opc == X86ISD::SUB ||
10644        Opc == X86ISD::ADC ||
10645        Opc == X86ISD::SBB ||
10646        Opc == X86ISD::SMUL ||
10647        Opc == X86ISD::UMUL ||
10648        Opc == X86ISD::INC ||
10649        Opc == X86ISD::DEC ||
10650        Opc == X86ISD::OR ||
10651        Opc == X86ISD::XOR ||
10652        Opc == X86ISD::AND))
10653     return true;
10654
10655   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10656     return true;
10657
10658   return false;
10659 }
10660
10661 static bool isZero(SDValue V) {
10662   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10663   return C && C->isNullValue();
10664 }
10665
10666 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10667   if (V.getOpcode() != ISD::TRUNCATE)
10668     return false;
10669
10670   SDValue VOp0 = V.getOperand(0);
10671   unsigned InBits = VOp0.getValueSizeInBits();
10672   unsigned Bits = V.getValueSizeInBits();
10673   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10674 }
10675
10676 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10677   bool addTest = true;
10678   SDValue Cond  = Op.getOperand(0);
10679   SDValue Op1 = Op.getOperand(1);
10680   SDValue Op2 = Op.getOperand(2);
10681   SDLoc DL(Op);
10682   EVT VT = Op1.getValueType();
10683   SDValue CC;
10684
10685   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10686   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10687   // sequence later on.
10688   if (Cond.getOpcode() == ISD::SETCC &&
10689       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10690        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10691       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10692     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10693     int SSECC = translateX86FSETCC(
10694         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10695
10696     if (SSECC != 8) {
10697       if (Subtarget->hasAVX512()) {
10698         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10699                                   DAG.getConstant(SSECC, MVT::i8));
10700         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10701       }
10702       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10703                                 DAG.getConstant(SSECC, MVT::i8));
10704       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10705       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10706       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10707     }
10708   }
10709
10710   if (Cond.getOpcode() == ISD::SETCC) {
10711     SDValue NewCond = LowerSETCC(Cond, DAG);
10712     if (NewCond.getNode())
10713       Cond = NewCond;
10714   }
10715
10716   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10717   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10718   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10719   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10720   if (Cond.getOpcode() == X86ISD::SETCC &&
10721       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10722       isZero(Cond.getOperand(1).getOperand(1))) {
10723     SDValue Cmp = Cond.getOperand(1);
10724
10725     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10726
10727     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10728         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10729       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10730
10731       SDValue CmpOp0 = Cmp.getOperand(0);
10732       // Apply further optimizations for special cases
10733       // (select (x != 0), -1, 0) -> neg & sbb
10734       // (select (x == 0), 0, -1) -> neg & sbb
10735       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10736         if (YC->isNullValue() &&
10737             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10738           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10739           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10740                                     DAG.getConstant(0, CmpOp0.getValueType()),
10741                                     CmpOp0);
10742           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10743                                     DAG.getConstant(X86::COND_B, MVT::i8),
10744                                     SDValue(Neg.getNode(), 1));
10745           return Res;
10746         }
10747
10748       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10749                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10750       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10751
10752       SDValue Res =   // Res = 0 or -1.
10753         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10754                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10755
10756       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10757         Res = DAG.getNOT(DL, Res, Res.getValueType());
10758
10759       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10760       if (!N2C || !N2C->isNullValue())
10761         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10762       return Res;
10763     }
10764   }
10765
10766   // Look past (and (setcc_carry (cmp ...)), 1).
10767   if (Cond.getOpcode() == ISD::AND &&
10768       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10769     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10770     if (C && C->getAPIntValue() == 1)
10771       Cond = Cond.getOperand(0);
10772   }
10773
10774   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10775   // setting operand in place of the X86ISD::SETCC.
10776   unsigned CondOpcode = Cond.getOpcode();
10777   if (CondOpcode == X86ISD::SETCC ||
10778       CondOpcode == X86ISD::SETCC_CARRY) {
10779     CC = Cond.getOperand(0);
10780
10781     SDValue Cmp = Cond.getOperand(1);
10782     unsigned Opc = Cmp.getOpcode();
10783     MVT VT = Op.getSimpleValueType();
10784
10785     bool IllegalFPCMov = false;
10786     if (VT.isFloatingPoint() && !VT.isVector() &&
10787         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10788       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10789
10790     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10791         Opc == X86ISD::BT) { // FIXME
10792       Cond = Cmp;
10793       addTest = false;
10794     }
10795   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10796              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10797              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10798               Cond.getOperand(0).getValueType() != MVT::i8)) {
10799     SDValue LHS = Cond.getOperand(0);
10800     SDValue RHS = Cond.getOperand(1);
10801     unsigned X86Opcode;
10802     unsigned X86Cond;
10803     SDVTList VTs;
10804     switch (CondOpcode) {
10805     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10806     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10807     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10808     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10809     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10810     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10811     default: llvm_unreachable("unexpected overflowing operator");
10812     }
10813     if (CondOpcode == ISD::UMULO)
10814       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10815                           MVT::i32);
10816     else
10817       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10818
10819     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10820
10821     if (CondOpcode == ISD::UMULO)
10822       Cond = X86Op.getValue(2);
10823     else
10824       Cond = X86Op.getValue(1);
10825
10826     CC = DAG.getConstant(X86Cond, MVT::i8);
10827     addTest = false;
10828   }
10829
10830   if (addTest) {
10831     // Look pass the truncate if the high bits are known zero.
10832     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10833         Cond = Cond.getOperand(0);
10834
10835     // We know the result of AND is compared against zero. Try to match
10836     // it to BT.
10837     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10838       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10839       if (NewSetCC.getNode()) {
10840         CC = NewSetCC.getOperand(0);
10841         Cond = NewSetCC.getOperand(1);
10842         addTest = false;
10843       }
10844     }
10845   }
10846
10847   if (addTest) {
10848     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10849     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10850   }
10851
10852   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10853   // a <  b ?  0 : -1 -> RES = setcc_carry
10854   // a >= b ? -1 :  0 -> RES = setcc_carry
10855   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10856   if (Cond.getOpcode() == X86ISD::SUB) {
10857     Cond = ConvertCmpIfNecessary(Cond, DAG);
10858     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10859
10860     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10861         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10862       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10863                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10864       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10865         return DAG.getNOT(DL, Res, Res.getValueType());
10866       return Res;
10867     }
10868   }
10869
10870   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10871   // widen the cmov and push the truncate through. This avoids introducing a new
10872   // branch during isel and doesn't add any extensions.
10873   if (Op.getValueType() == MVT::i8 &&
10874       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10875     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10876     if (T1.getValueType() == T2.getValueType() &&
10877         // Blacklist CopyFromReg to avoid partial register stalls.
10878         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10879       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10880       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10881       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10882     }
10883   }
10884
10885   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10886   // condition is true.
10887   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10888   SDValue Ops[] = { Op2, Op1, CC, Cond };
10889   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10890 }
10891
10892 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10893   MVT VT = Op->getSimpleValueType(0);
10894   SDValue In = Op->getOperand(0);
10895   MVT InVT = In.getSimpleValueType();
10896   SDLoc dl(Op);
10897
10898   unsigned int NumElts = VT.getVectorNumElements();
10899   if (NumElts != 8 && NumElts != 16)
10900     return SDValue();
10901
10902   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10903     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10904
10905   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10906   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10907
10908   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10909   Constant *C = ConstantInt::get(*DAG.getContext(),
10910     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10911
10912   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10913   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10914   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10915                           MachinePointerInfo::getConstantPool(),
10916                           false, false, false, Alignment);
10917   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10918   if (VT.is512BitVector())
10919     return Brcst;
10920   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10921 }
10922
10923 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10924                                 SelectionDAG &DAG) {
10925   MVT VT = Op->getSimpleValueType(0);
10926   SDValue In = Op->getOperand(0);
10927   MVT InVT = In.getSimpleValueType();
10928   SDLoc dl(Op);
10929
10930   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10931     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10932
10933   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10934       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10935       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10936     return SDValue();
10937
10938   if (Subtarget->hasInt256())
10939     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10940
10941   // Optimize vectors in AVX mode
10942   // Sign extend  v8i16 to v8i32 and
10943   //              v4i32 to v4i64
10944   //
10945   // Divide input vector into two parts
10946   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10947   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10948   // concat the vectors to original VT
10949
10950   unsigned NumElems = InVT.getVectorNumElements();
10951   SDValue Undef = DAG.getUNDEF(InVT);
10952
10953   SmallVector<int,8> ShufMask1(NumElems, -1);
10954   for (unsigned i = 0; i != NumElems/2; ++i)
10955     ShufMask1[i] = i;
10956
10957   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10958
10959   SmallVector<int,8> ShufMask2(NumElems, -1);
10960   for (unsigned i = 0; i != NumElems/2; ++i)
10961     ShufMask2[i] = i + NumElems/2;
10962
10963   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10964
10965   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10966                                 VT.getVectorNumElements()/2);
10967
10968   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10969   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10970
10971   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10972 }
10973
10974 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10975 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10976 // from the AND / OR.
10977 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10978   Opc = Op.getOpcode();
10979   if (Opc != ISD::OR && Opc != ISD::AND)
10980     return false;
10981   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10982           Op.getOperand(0).hasOneUse() &&
10983           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10984           Op.getOperand(1).hasOneUse());
10985 }
10986
10987 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10988 // 1 and that the SETCC node has a single use.
10989 static bool isXor1OfSetCC(SDValue Op) {
10990   if (Op.getOpcode() != ISD::XOR)
10991     return false;
10992   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10993   if (N1C && N1C->getAPIntValue() == 1) {
10994     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10995       Op.getOperand(0).hasOneUse();
10996   }
10997   return false;
10998 }
10999
11000 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11001   bool addTest = true;
11002   SDValue Chain = Op.getOperand(0);
11003   SDValue Cond  = Op.getOperand(1);
11004   SDValue Dest  = Op.getOperand(2);
11005   SDLoc dl(Op);
11006   SDValue CC;
11007   bool Inverted = false;
11008
11009   if (Cond.getOpcode() == ISD::SETCC) {
11010     // Check for setcc([su]{add,sub,mul}o == 0).
11011     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11012         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11013         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11014         Cond.getOperand(0).getResNo() == 1 &&
11015         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11016          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11017          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11018          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11019          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11020          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11021       Inverted = true;
11022       Cond = Cond.getOperand(0);
11023     } else {
11024       SDValue NewCond = LowerSETCC(Cond, DAG);
11025       if (NewCond.getNode())
11026         Cond = NewCond;
11027     }
11028   }
11029 #if 0
11030   // FIXME: LowerXALUO doesn't handle these!!
11031   else if (Cond.getOpcode() == X86ISD::ADD  ||
11032            Cond.getOpcode() == X86ISD::SUB  ||
11033            Cond.getOpcode() == X86ISD::SMUL ||
11034            Cond.getOpcode() == X86ISD::UMUL)
11035     Cond = LowerXALUO(Cond, DAG);
11036 #endif
11037
11038   // Look pass (and (setcc_carry (cmp ...)), 1).
11039   if (Cond.getOpcode() == ISD::AND &&
11040       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11041     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11042     if (C && C->getAPIntValue() == 1)
11043       Cond = Cond.getOperand(0);
11044   }
11045
11046   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11047   // setting operand in place of the X86ISD::SETCC.
11048   unsigned CondOpcode = Cond.getOpcode();
11049   if (CondOpcode == X86ISD::SETCC ||
11050       CondOpcode == X86ISD::SETCC_CARRY) {
11051     CC = Cond.getOperand(0);
11052
11053     SDValue Cmp = Cond.getOperand(1);
11054     unsigned Opc = Cmp.getOpcode();
11055     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11056     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11057       Cond = Cmp;
11058       addTest = false;
11059     } else {
11060       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11061       default: break;
11062       case X86::COND_O:
11063       case X86::COND_B:
11064         // These can only come from an arithmetic instruction with overflow,
11065         // e.g. SADDO, UADDO.
11066         Cond = Cond.getNode()->getOperand(1);
11067         addTest = false;
11068         break;
11069       }
11070     }
11071   }
11072   CondOpcode = Cond.getOpcode();
11073   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11074       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11075       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11076        Cond.getOperand(0).getValueType() != MVT::i8)) {
11077     SDValue LHS = Cond.getOperand(0);
11078     SDValue RHS = Cond.getOperand(1);
11079     unsigned X86Opcode;
11080     unsigned X86Cond;
11081     SDVTList VTs;
11082     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11083     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11084     // X86ISD::INC).
11085     switch (CondOpcode) {
11086     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11087     case ISD::SADDO:
11088       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11089         if (C->isOne()) {
11090           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11091           break;
11092         }
11093       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11094     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11095     case ISD::SSUBO:
11096       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11097         if (C->isOne()) {
11098           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11099           break;
11100         }
11101       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11102     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11103     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11104     default: llvm_unreachable("unexpected overflowing operator");
11105     }
11106     if (Inverted)
11107       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11108     if (CondOpcode == ISD::UMULO)
11109       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11110                           MVT::i32);
11111     else
11112       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11113
11114     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11115
11116     if (CondOpcode == ISD::UMULO)
11117       Cond = X86Op.getValue(2);
11118     else
11119       Cond = X86Op.getValue(1);
11120
11121     CC = DAG.getConstant(X86Cond, MVT::i8);
11122     addTest = false;
11123   } else {
11124     unsigned CondOpc;
11125     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11126       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11127       if (CondOpc == ISD::OR) {
11128         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11129         // two branches instead of an explicit OR instruction with a
11130         // separate test.
11131         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11132             isX86LogicalCmp(Cmp)) {
11133           CC = Cond.getOperand(0).getOperand(0);
11134           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11135                               Chain, Dest, CC, Cmp);
11136           CC = Cond.getOperand(1).getOperand(0);
11137           Cond = Cmp;
11138           addTest = false;
11139         }
11140       } else { // ISD::AND
11141         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11142         // two branches instead of an explicit AND instruction with a
11143         // separate test. However, we only do this if this block doesn't
11144         // have a fall-through edge, because this requires an explicit
11145         // jmp when the condition is false.
11146         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11147             isX86LogicalCmp(Cmp) &&
11148             Op.getNode()->hasOneUse()) {
11149           X86::CondCode CCode =
11150             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11151           CCode = X86::GetOppositeBranchCondition(CCode);
11152           CC = DAG.getConstant(CCode, MVT::i8);
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             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11166                                 Chain, Dest, CC, Cmp);
11167             X86::CondCode CCode =
11168               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11169             CCode = X86::GetOppositeBranchCondition(CCode);
11170             CC = DAG.getConstant(CCode, MVT::i8);
11171             Cond = Cmp;
11172             addTest = false;
11173           }
11174         }
11175       }
11176     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11177       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11178       // It should be transformed during dag combiner except when the condition
11179       // is set by a arithmetics with overflow node.
11180       X86::CondCode CCode =
11181         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11182       CCode = X86::GetOppositeBranchCondition(CCode);
11183       CC = DAG.getConstant(CCode, MVT::i8);
11184       Cond = Cond.getOperand(0).getOperand(1);
11185       addTest = false;
11186     } else if (Cond.getOpcode() == ISD::SETCC &&
11187                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11188       // For FCMP_OEQ, we can emit
11189       // two branches instead of an explicit AND instruction with a
11190       // separate test. However, we only do this if this block doesn't
11191       // have a fall-through edge, because this requires an explicit
11192       // jmp when the condition is false.
11193       if (Op.getNode()->hasOneUse()) {
11194         SDNode *User = *Op.getNode()->use_begin();
11195         // Look for an unconditional branch following this conditional branch.
11196         // We need this because we need to reverse the successors in order
11197         // to implement FCMP_OEQ.
11198         if (User->getOpcode() == ISD::BR) {
11199           SDValue FalseBB = User->getOperand(1);
11200           SDNode *NewBR =
11201             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11202           assert(NewBR == User);
11203           (void)NewBR;
11204           Dest = FalseBB;
11205
11206           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11207                                     Cond.getOperand(0), Cond.getOperand(1));
11208           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11209           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11210           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11211                               Chain, Dest, CC, Cmp);
11212           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11213           Cond = Cmp;
11214           addTest = false;
11215         }
11216       }
11217     } else if (Cond.getOpcode() == ISD::SETCC &&
11218                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11219       // For FCMP_UNE, we can emit
11220       // two branches instead of an explicit AND instruction with a
11221       // separate test. However, we only do this if this block doesn't
11222       // have a fall-through edge, because this requires an explicit
11223       // jmp when the condition is false.
11224       if (Op.getNode()->hasOneUse()) {
11225         SDNode *User = *Op.getNode()->use_begin();
11226         // Look for an unconditional branch following this conditional branch.
11227         // We need this because we need to reverse the successors in order
11228         // to implement FCMP_UNE.
11229         if (User->getOpcode() == ISD::BR) {
11230           SDValue FalseBB = User->getOperand(1);
11231           SDNode *NewBR =
11232             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11233           assert(NewBR == User);
11234           (void)NewBR;
11235
11236           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11237                                     Cond.getOperand(0), Cond.getOperand(1));
11238           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11239           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11240           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11241                               Chain, Dest, CC, Cmp);
11242           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11243           Cond = Cmp;
11244           addTest = false;
11245           Dest = FalseBB;
11246         }
11247       }
11248     }
11249   }
11250
11251   if (addTest) {
11252     // Look pass the truncate if the high bits are known zero.
11253     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11254         Cond = Cond.getOperand(0);
11255
11256     // We know the result of AND is compared against zero. Try to match
11257     // it to BT.
11258     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11259       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11260       if (NewSetCC.getNode()) {
11261         CC = NewSetCC.getOperand(0);
11262         Cond = NewSetCC.getOperand(1);
11263         addTest = false;
11264       }
11265     }
11266   }
11267
11268   if (addTest) {
11269     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11270     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11271   }
11272   Cond = ConvertCmpIfNecessary(Cond, DAG);
11273   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11274                      Chain, Dest, CC, Cond);
11275 }
11276
11277 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11278 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11279 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11280 // that the guard pages used by the OS virtual memory manager are allocated in
11281 // correct sequence.
11282 SDValue
11283 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11284                                            SelectionDAG &DAG) const {
11285   MachineFunction &MF = DAG.getMachineFunction();
11286   bool SplitStack = MF.shouldSplitStack();
11287   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11288                SplitStack;
11289   SDLoc dl(Op);
11290
11291   if (!Lower) {
11292     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11293     SDNode* Node = Op.getNode();
11294
11295     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11296     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11297         " not tell us which reg is the stack pointer!");
11298     EVT VT = Node->getValueType(0);
11299     SDValue Tmp1 = SDValue(Node, 0);
11300     SDValue Tmp2 = SDValue(Node, 1);
11301     SDValue Tmp3 = Node->getOperand(2);
11302     SDValue Chain = Tmp1.getOperand(0);
11303
11304     // Chain the dynamic stack allocation so that it doesn't modify the stack
11305     // pointer when other instructions are using the stack.
11306     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11307         SDLoc(Node));
11308
11309     SDValue Size = Tmp2.getOperand(1);
11310     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11311     Chain = SP.getValue(1);
11312     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11313     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11314     unsigned StackAlign = TFI.getStackAlignment();
11315     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11316     if (Align > StackAlign)
11317       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11318           DAG.getConstant(-(uint64_t)Align, VT));
11319     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11320
11321     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11322         DAG.getIntPtrConstant(0, true), SDValue(),
11323         SDLoc(Node));
11324
11325     SDValue Ops[2] = { Tmp1, Tmp2 };
11326     return DAG.getMergeValues(Ops, dl);
11327   }
11328
11329   // Get the inputs.
11330   SDValue Chain = Op.getOperand(0);
11331   SDValue Size  = Op.getOperand(1);
11332   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11333   EVT VT = Op.getNode()->getValueType(0);
11334
11335   bool Is64Bit = Subtarget->is64Bit();
11336   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11337
11338   if (SplitStack) {
11339     MachineRegisterInfo &MRI = MF.getRegInfo();
11340
11341     if (Is64Bit) {
11342       // The 64 bit implementation of segmented stacks needs to clobber both r10
11343       // r11. This makes it impossible to use it along with nested parameters.
11344       const Function *F = MF.getFunction();
11345
11346       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11347            I != E; ++I)
11348         if (I->hasNestAttr())
11349           report_fatal_error("Cannot use segmented stacks with functions that "
11350                              "have nested arguments.");
11351     }
11352
11353     const TargetRegisterClass *AddrRegClass =
11354       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11355     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11356     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11357     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11358                                 DAG.getRegister(Vreg, SPTy));
11359     SDValue Ops1[2] = { Value, Chain };
11360     return DAG.getMergeValues(Ops1, dl);
11361   } else {
11362     SDValue Flag;
11363     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11364
11365     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11366     Flag = Chain.getValue(1);
11367     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11368
11369     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11370
11371     const X86RegisterInfo *RegInfo =
11372       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11373     unsigned SPReg = RegInfo->getStackRegister();
11374     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11375     Chain = SP.getValue(1);
11376
11377     if (Align) {
11378       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11379                        DAG.getConstant(-(uint64_t)Align, VT));
11380       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11381     }
11382
11383     SDValue Ops1[2] = { SP, Chain };
11384     return DAG.getMergeValues(Ops1, dl);
11385   }
11386 }
11387
11388 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11389   MachineFunction &MF = DAG.getMachineFunction();
11390   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11391
11392   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11393   SDLoc DL(Op);
11394
11395   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11396     // vastart just stores the address of the VarArgsFrameIndex slot into the
11397     // memory location argument.
11398     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11399                                    getPointerTy());
11400     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11401                         MachinePointerInfo(SV), false, false, 0);
11402   }
11403
11404   // __va_list_tag:
11405   //   gp_offset         (0 - 6 * 8)
11406   //   fp_offset         (48 - 48 + 8 * 16)
11407   //   overflow_arg_area (point to parameters coming in memory).
11408   //   reg_save_area
11409   SmallVector<SDValue, 8> MemOps;
11410   SDValue FIN = Op.getOperand(1);
11411   // Store gp_offset
11412   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11413                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11414                                                MVT::i32),
11415                                FIN, MachinePointerInfo(SV), false, false, 0);
11416   MemOps.push_back(Store);
11417
11418   // Store fp_offset
11419   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11420                     FIN, DAG.getIntPtrConstant(4));
11421   Store = DAG.getStore(Op.getOperand(0), DL,
11422                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11423                                        MVT::i32),
11424                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11425   MemOps.push_back(Store);
11426
11427   // Store ptr to overflow_arg_area
11428   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11429                     FIN, DAG.getIntPtrConstant(4));
11430   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11431                                     getPointerTy());
11432   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11433                        MachinePointerInfo(SV, 8),
11434                        false, false, 0);
11435   MemOps.push_back(Store);
11436
11437   // Store ptr to reg_save_area.
11438   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11439                     FIN, DAG.getIntPtrConstant(8));
11440   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11441                                     getPointerTy());
11442   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11443                        MachinePointerInfo(SV, 16), false, false, 0);
11444   MemOps.push_back(Store);
11445   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11446 }
11447
11448 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11449   assert(Subtarget->is64Bit() &&
11450          "LowerVAARG only handles 64-bit va_arg!");
11451   assert((Subtarget->isTargetLinux() ||
11452           Subtarget->isTargetDarwin()) &&
11453           "Unhandled target in LowerVAARG");
11454   assert(Op.getNode()->getNumOperands() == 4);
11455   SDValue Chain = Op.getOperand(0);
11456   SDValue SrcPtr = Op.getOperand(1);
11457   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11458   unsigned Align = Op.getConstantOperandVal(3);
11459   SDLoc dl(Op);
11460
11461   EVT ArgVT = Op.getNode()->getValueType(0);
11462   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11463   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11464   uint8_t ArgMode;
11465
11466   // Decide which area this value should be read from.
11467   // TODO: Implement the AMD64 ABI in its entirety. This simple
11468   // selection mechanism works only for the basic types.
11469   if (ArgVT == MVT::f80) {
11470     llvm_unreachable("va_arg for f80 not yet implemented");
11471   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11472     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11473   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11474     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11475   } else {
11476     llvm_unreachable("Unhandled argument type in LowerVAARG");
11477   }
11478
11479   if (ArgMode == 2) {
11480     // Sanity Check: Make sure using fp_offset makes sense.
11481     assert(!getTargetMachine().Options.UseSoftFloat &&
11482            !(DAG.getMachineFunction()
11483                 .getFunction()->getAttributes()
11484                 .hasAttribute(AttributeSet::FunctionIndex,
11485                               Attribute::NoImplicitFloat)) &&
11486            Subtarget->hasSSE1());
11487   }
11488
11489   // Insert VAARG_64 node into the DAG
11490   // VAARG_64 returns two values: Variable Argument Address, Chain
11491   SmallVector<SDValue, 11> InstOps;
11492   InstOps.push_back(Chain);
11493   InstOps.push_back(SrcPtr);
11494   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11495   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11496   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11497   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11498   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11499                                           VTs, InstOps, MVT::i64,
11500                                           MachinePointerInfo(SV),
11501                                           /*Align=*/0,
11502                                           /*Volatile=*/false,
11503                                           /*ReadMem=*/true,
11504                                           /*WriteMem=*/true);
11505   Chain = VAARG.getValue(1);
11506
11507   // Load the next argument and return it
11508   return DAG.getLoad(ArgVT, dl,
11509                      Chain,
11510                      VAARG,
11511                      MachinePointerInfo(),
11512                      false, false, false, 0);
11513 }
11514
11515 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11516                            SelectionDAG &DAG) {
11517   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11518   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11519   SDValue Chain = Op.getOperand(0);
11520   SDValue DstPtr = Op.getOperand(1);
11521   SDValue SrcPtr = Op.getOperand(2);
11522   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11523   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11524   SDLoc DL(Op);
11525
11526   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11527                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11528                        false,
11529                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11530 }
11531
11532 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11533 // amount is a constant. Takes immediate version of shift as input.
11534 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11535                                           SDValue SrcOp, uint64_t ShiftAmt,
11536                                           SelectionDAG &DAG) {
11537   MVT ElementType = VT.getVectorElementType();
11538
11539   // Check for ShiftAmt >= element width
11540   if (ShiftAmt >= ElementType.getSizeInBits()) {
11541     if (Opc == X86ISD::VSRAI)
11542       ShiftAmt = ElementType.getSizeInBits() - 1;
11543     else
11544       return DAG.getConstant(0, VT);
11545   }
11546
11547   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11548          && "Unknown target vector shift-by-constant node");
11549
11550   // Fold this packed vector shift into a build vector if SrcOp is a
11551   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11552   if (VT == SrcOp.getSimpleValueType() &&
11553       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11554     SmallVector<SDValue, 8> Elts;
11555     unsigned NumElts = SrcOp->getNumOperands();
11556     ConstantSDNode *ND;
11557
11558     switch(Opc) {
11559     default: llvm_unreachable(nullptr);
11560     case X86ISD::VSHLI:
11561       for (unsigned i=0; i!=NumElts; ++i) {
11562         SDValue CurrentOp = SrcOp->getOperand(i);
11563         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11564           Elts.push_back(CurrentOp);
11565           continue;
11566         }
11567         ND = cast<ConstantSDNode>(CurrentOp);
11568         const APInt &C = ND->getAPIntValue();
11569         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11570       }
11571       break;
11572     case X86ISD::VSRLI:
11573       for (unsigned i=0; i!=NumElts; ++i) {
11574         SDValue CurrentOp = SrcOp->getOperand(i);
11575         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11576           Elts.push_back(CurrentOp);
11577           continue;
11578         }
11579         ND = cast<ConstantSDNode>(CurrentOp);
11580         const APInt &C = ND->getAPIntValue();
11581         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11582       }
11583       break;
11584     case X86ISD::VSRAI:
11585       for (unsigned i=0; i!=NumElts; ++i) {
11586         SDValue CurrentOp = SrcOp->getOperand(i);
11587         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11588           Elts.push_back(CurrentOp);
11589           continue;
11590         }
11591         ND = cast<ConstantSDNode>(CurrentOp);
11592         const APInt &C = ND->getAPIntValue();
11593         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11594       }
11595       break;
11596     }
11597
11598     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11599   }
11600
11601   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11602 }
11603
11604 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11605 // may or may not be a constant. Takes immediate version of shift as input.
11606 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11607                                    SDValue SrcOp, SDValue ShAmt,
11608                                    SelectionDAG &DAG) {
11609   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11610
11611   // Catch shift-by-constant.
11612   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11613     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11614                                       CShAmt->getZExtValue(), DAG);
11615
11616   // Change opcode to non-immediate version
11617   switch (Opc) {
11618     default: llvm_unreachable("Unknown target vector shift node");
11619     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11620     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11621     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11622   }
11623
11624   // Need to build a vector containing shift amount
11625   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11626   SDValue ShOps[4];
11627   ShOps[0] = ShAmt;
11628   ShOps[1] = DAG.getConstant(0, MVT::i32);
11629   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11630   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11631
11632   // The return type has to be a 128-bit type with the same element
11633   // type as the input type.
11634   MVT EltVT = VT.getVectorElementType();
11635   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11636
11637   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11638   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11639 }
11640
11641 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11642   SDLoc dl(Op);
11643   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11644   switch (IntNo) {
11645   default: return SDValue();    // Don't custom lower most intrinsics.
11646   // Comparison intrinsics.
11647   case Intrinsic::x86_sse_comieq_ss:
11648   case Intrinsic::x86_sse_comilt_ss:
11649   case Intrinsic::x86_sse_comile_ss:
11650   case Intrinsic::x86_sse_comigt_ss:
11651   case Intrinsic::x86_sse_comige_ss:
11652   case Intrinsic::x86_sse_comineq_ss:
11653   case Intrinsic::x86_sse_ucomieq_ss:
11654   case Intrinsic::x86_sse_ucomilt_ss:
11655   case Intrinsic::x86_sse_ucomile_ss:
11656   case Intrinsic::x86_sse_ucomigt_ss:
11657   case Intrinsic::x86_sse_ucomige_ss:
11658   case Intrinsic::x86_sse_ucomineq_ss:
11659   case Intrinsic::x86_sse2_comieq_sd:
11660   case Intrinsic::x86_sse2_comilt_sd:
11661   case Intrinsic::x86_sse2_comile_sd:
11662   case Intrinsic::x86_sse2_comigt_sd:
11663   case Intrinsic::x86_sse2_comige_sd:
11664   case Intrinsic::x86_sse2_comineq_sd:
11665   case Intrinsic::x86_sse2_ucomieq_sd:
11666   case Intrinsic::x86_sse2_ucomilt_sd:
11667   case Intrinsic::x86_sse2_ucomile_sd:
11668   case Intrinsic::x86_sse2_ucomigt_sd:
11669   case Intrinsic::x86_sse2_ucomige_sd:
11670   case Intrinsic::x86_sse2_ucomineq_sd: {
11671     unsigned Opc;
11672     ISD::CondCode CC;
11673     switch (IntNo) {
11674     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11675     case Intrinsic::x86_sse_comieq_ss:
11676     case Intrinsic::x86_sse2_comieq_sd:
11677       Opc = X86ISD::COMI;
11678       CC = ISD::SETEQ;
11679       break;
11680     case Intrinsic::x86_sse_comilt_ss:
11681     case Intrinsic::x86_sse2_comilt_sd:
11682       Opc = X86ISD::COMI;
11683       CC = ISD::SETLT;
11684       break;
11685     case Intrinsic::x86_sse_comile_ss:
11686     case Intrinsic::x86_sse2_comile_sd:
11687       Opc = X86ISD::COMI;
11688       CC = ISD::SETLE;
11689       break;
11690     case Intrinsic::x86_sse_comigt_ss:
11691     case Intrinsic::x86_sse2_comigt_sd:
11692       Opc = X86ISD::COMI;
11693       CC = ISD::SETGT;
11694       break;
11695     case Intrinsic::x86_sse_comige_ss:
11696     case Intrinsic::x86_sse2_comige_sd:
11697       Opc = X86ISD::COMI;
11698       CC = ISD::SETGE;
11699       break;
11700     case Intrinsic::x86_sse_comineq_ss:
11701     case Intrinsic::x86_sse2_comineq_sd:
11702       Opc = X86ISD::COMI;
11703       CC = ISD::SETNE;
11704       break;
11705     case Intrinsic::x86_sse_ucomieq_ss:
11706     case Intrinsic::x86_sse2_ucomieq_sd:
11707       Opc = X86ISD::UCOMI;
11708       CC = ISD::SETEQ;
11709       break;
11710     case Intrinsic::x86_sse_ucomilt_ss:
11711     case Intrinsic::x86_sse2_ucomilt_sd:
11712       Opc = X86ISD::UCOMI;
11713       CC = ISD::SETLT;
11714       break;
11715     case Intrinsic::x86_sse_ucomile_ss:
11716     case Intrinsic::x86_sse2_ucomile_sd:
11717       Opc = X86ISD::UCOMI;
11718       CC = ISD::SETLE;
11719       break;
11720     case Intrinsic::x86_sse_ucomigt_ss:
11721     case Intrinsic::x86_sse2_ucomigt_sd:
11722       Opc = X86ISD::UCOMI;
11723       CC = ISD::SETGT;
11724       break;
11725     case Intrinsic::x86_sse_ucomige_ss:
11726     case Intrinsic::x86_sse2_ucomige_sd:
11727       Opc = X86ISD::UCOMI;
11728       CC = ISD::SETGE;
11729       break;
11730     case Intrinsic::x86_sse_ucomineq_ss:
11731     case Intrinsic::x86_sse2_ucomineq_sd:
11732       Opc = X86ISD::UCOMI;
11733       CC = ISD::SETNE;
11734       break;
11735     }
11736
11737     SDValue LHS = Op.getOperand(1);
11738     SDValue RHS = Op.getOperand(2);
11739     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11740     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11741     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11742     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11743                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11744     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11745   }
11746
11747   // Arithmetic intrinsics.
11748   case Intrinsic::x86_sse2_pmulu_dq:
11749   case Intrinsic::x86_avx2_pmulu_dq:
11750     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11751                        Op.getOperand(1), Op.getOperand(2));
11752
11753   case Intrinsic::x86_sse41_pmuldq:
11754   case Intrinsic::x86_avx2_pmul_dq:
11755     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11756                        Op.getOperand(1), Op.getOperand(2));
11757
11758   case Intrinsic::x86_sse2_pmulhu_w:
11759   case Intrinsic::x86_avx2_pmulhu_w:
11760     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11761                        Op.getOperand(1), Op.getOperand(2));
11762
11763   case Intrinsic::x86_sse2_pmulh_w:
11764   case Intrinsic::x86_avx2_pmulh_w:
11765     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11766                        Op.getOperand(1), Op.getOperand(2));
11767
11768   // SSE2/AVX2 sub with unsigned saturation intrinsics
11769   case Intrinsic::x86_sse2_psubus_b:
11770   case Intrinsic::x86_sse2_psubus_w:
11771   case Intrinsic::x86_avx2_psubus_b:
11772   case Intrinsic::x86_avx2_psubus_w:
11773     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11774                        Op.getOperand(1), Op.getOperand(2));
11775
11776   // SSE3/AVX horizontal add/sub intrinsics
11777   case Intrinsic::x86_sse3_hadd_ps:
11778   case Intrinsic::x86_sse3_hadd_pd:
11779   case Intrinsic::x86_avx_hadd_ps_256:
11780   case Intrinsic::x86_avx_hadd_pd_256:
11781   case Intrinsic::x86_sse3_hsub_ps:
11782   case Intrinsic::x86_sse3_hsub_pd:
11783   case Intrinsic::x86_avx_hsub_ps_256:
11784   case Intrinsic::x86_avx_hsub_pd_256:
11785   case Intrinsic::x86_ssse3_phadd_w_128:
11786   case Intrinsic::x86_ssse3_phadd_d_128:
11787   case Intrinsic::x86_avx2_phadd_w:
11788   case Intrinsic::x86_avx2_phadd_d:
11789   case Intrinsic::x86_ssse3_phsub_w_128:
11790   case Intrinsic::x86_ssse3_phsub_d_128:
11791   case Intrinsic::x86_avx2_phsub_w:
11792   case Intrinsic::x86_avx2_phsub_d: {
11793     unsigned Opcode;
11794     switch (IntNo) {
11795     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11796     case Intrinsic::x86_sse3_hadd_ps:
11797     case Intrinsic::x86_sse3_hadd_pd:
11798     case Intrinsic::x86_avx_hadd_ps_256:
11799     case Intrinsic::x86_avx_hadd_pd_256:
11800       Opcode = X86ISD::FHADD;
11801       break;
11802     case Intrinsic::x86_sse3_hsub_ps:
11803     case Intrinsic::x86_sse3_hsub_pd:
11804     case Intrinsic::x86_avx_hsub_ps_256:
11805     case Intrinsic::x86_avx_hsub_pd_256:
11806       Opcode = X86ISD::FHSUB;
11807       break;
11808     case Intrinsic::x86_ssse3_phadd_w_128:
11809     case Intrinsic::x86_ssse3_phadd_d_128:
11810     case Intrinsic::x86_avx2_phadd_w:
11811     case Intrinsic::x86_avx2_phadd_d:
11812       Opcode = X86ISD::HADD;
11813       break;
11814     case Intrinsic::x86_ssse3_phsub_w_128:
11815     case Intrinsic::x86_ssse3_phsub_d_128:
11816     case Intrinsic::x86_avx2_phsub_w:
11817     case Intrinsic::x86_avx2_phsub_d:
11818       Opcode = X86ISD::HSUB;
11819       break;
11820     }
11821     return DAG.getNode(Opcode, dl, Op.getValueType(),
11822                        Op.getOperand(1), Op.getOperand(2));
11823   }
11824
11825   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11826   case Intrinsic::x86_sse2_pmaxu_b:
11827   case Intrinsic::x86_sse41_pmaxuw:
11828   case Intrinsic::x86_sse41_pmaxud:
11829   case Intrinsic::x86_avx2_pmaxu_b:
11830   case Intrinsic::x86_avx2_pmaxu_w:
11831   case Intrinsic::x86_avx2_pmaxu_d:
11832   case Intrinsic::x86_sse2_pminu_b:
11833   case Intrinsic::x86_sse41_pminuw:
11834   case Intrinsic::x86_sse41_pminud:
11835   case Intrinsic::x86_avx2_pminu_b:
11836   case Intrinsic::x86_avx2_pminu_w:
11837   case Intrinsic::x86_avx2_pminu_d:
11838   case Intrinsic::x86_sse41_pmaxsb:
11839   case Intrinsic::x86_sse2_pmaxs_w:
11840   case Intrinsic::x86_sse41_pmaxsd:
11841   case Intrinsic::x86_avx2_pmaxs_b:
11842   case Intrinsic::x86_avx2_pmaxs_w:
11843   case Intrinsic::x86_avx2_pmaxs_d:
11844   case Intrinsic::x86_sse41_pminsb:
11845   case Intrinsic::x86_sse2_pmins_w:
11846   case Intrinsic::x86_sse41_pminsd:
11847   case Intrinsic::x86_avx2_pmins_b:
11848   case Intrinsic::x86_avx2_pmins_w:
11849   case Intrinsic::x86_avx2_pmins_d: {
11850     unsigned Opcode;
11851     switch (IntNo) {
11852     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11853     case Intrinsic::x86_sse2_pmaxu_b:
11854     case Intrinsic::x86_sse41_pmaxuw:
11855     case Intrinsic::x86_sse41_pmaxud:
11856     case Intrinsic::x86_avx2_pmaxu_b:
11857     case Intrinsic::x86_avx2_pmaxu_w:
11858     case Intrinsic::x86_avx2_pmaxu_d:
11859       Opcode = X86ISD::UMAX;
11860       break;
11861     case Intrinsic::x86_sse2_pminu_b:
11862     case Intrinsic::x86_sse41_pminuw:
11863     case Intrinsic::x86_sse41_pminud:
11864     case Intrinsic::x86_avx2_pminu_b:
11865     case Intrinsic::x86_avx2_pminu_w:
11866     case Intrinsic::x86_avx2_pminu_d:
11867       Opcode = X86ISD::UMIN;
11868       break;
11869     case Intrinsic::x86_sse41_pmaxsb:
11870     case Intrinsic::x86_sse2_pmaxs_w:
11871     case Intrinsic::x86_sse41_pmaxsd:
11872     case Intrinsic::x86_avx2_pmaxs_b:
11873     case Intrinsic::x86_avx2_pmaxs_w:
11874     case Intrinsic::x86_avx2_pmaxs_d:
11875       Opcode = X86ISD::SMAX;
11876       break;
11877     case Intrinsic::x86_sse41_pminsb:
11878     case Intrinsic::x86_sse2_pmins_w:
11879     case Intrinsic::x86_sse41_pminsd:
11880     case Intrinsic::x86_avx2_pmins_b:
11881     case Intrinsic::x86_avx2_pmins_w:
11882     case Intrinsic::x86_avx2_pmins_d:
11883       Opcode = X86ISD::SMIN;
11884       break;
11885     }
11886     return DAG.getNode(Opcode, dl, Op.getValueType(),
11887                        Op.getOperand(1), Op.getOperand(2));
11888   }
11889
11890   // SSE/SSE2/AVX floating point max/min intrinsics.
11891   case Intrinsic::x86_sse_max_ps:
11892   case Intrinsic::x86_sse2_max_pd:
11893   case Intrinsic::x86_avx_max_ps_256:
11894   case Intrinsic::x86_avx_max_pd_256:
11895   case Intrinsic::x86_sse_min_ps:
11896   case Intrinsic::x86_sse2_min_pd:
11897   case Intrinsic::x86_avx_min_ps_256:
11898   case Intrinsic::x86_avx_min_pd_256: {
11899     unsigned Opcode;
11900     switch (IntNo) {
11901     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11902     case Intrinsic::x86_sse_max_ps:
11903     case Intrinsic::x86_sse2_max_pd:
11904     case Intrinsic::x86_avx_max_ps_256:
11905     case Intrinsic::x86_avx_max_pd_256:
11906       Opcode = X86ISD::FMAX;
11907       break;
11908     case Intrinsic::x86_sse_min_ps:
11909     case Intrinsic::x86_sse2_min_pd:
11910     case Intrinsic::x86_avx_min_ps_256:
11911     case Intrinsic::x86_avx_min_pd_256:
11912       Opcode = X86ISD::FMIN;
11913       break;
11914     }
11915     return DAG.getNode(Opcode, dl, Op.getValueType(),
11916                        Op.getOperand(1), Op.getOperand(2));
11917   }
11918
11919   // AVX2 variable shift intrinsics
11920   case Intrinsic::x86_avx2_psllv_d:
11921   case Intrinsic::x86_avx2_psllv_q:
11922   case Intrinsic::x86_avx2_psllv_d_256:
11923   case Intrinsic::x86_avx2_psllv_q_256:
11924   case Intrinsic::x86_avx2_psrlv_d:
11925   case Intrinsic::x86_avx2_psrlv_q:
11926   case Intrinsic::x86_avx2_psrlv_d_256:
11927   case Intrinsic::x86_avx2_psrlv_q_256:
11928   case Intrinsic::x86_avx2_psrav_d:
11929   case Intrinsic::x86_avx2_psrav_d_256: {
11930     unsigned Opcode;
11931     switch (IntNo) {
11932     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11933     case Intrinsic::x86_avx2_psllv_d:
11934     case Intrinsic::x86_avx2_psllv_q:
11935     case Intrinsic::x86_avx2_psllv_d_256:
11936     case Intrinsic::x86_avx2_psllv_q_256:
11937       Opcode = ISD::SHL;
11938       break;
11939     case Intrinsic::x86_avx2_psrlv_d:
11940     case Intrinsic::x86_avx2_psrlv_q:
11941     case Intrinsic::x86_avx2_psrlv_d_256:
11942     case Intrinsic::x86_avx2_psrlv_q_256:
11943       Opcode = ISD::SRL;
11944       break;
11945     case Intrinsic::x86_avx2_psrav_d:
11946     case Intrinsic::x86_avx2_psrav_d_256:
11947       Opcode = ISD::SRA;
11948       break;
11949     }
11950     return DAG.getNode(Opcode, dl, Op.getValueType(),
11951                        Op.getOperand(1), Op.getOperand(2));
11952   }
11953
11954   case Intrinsic::x86_ssse3_pshuf_b_128:
11955   case Intrinsic::x86_avx2_pshuf_b:
11956     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11957                        Op.getOperand(1), Op.getOperand(2));
11958
11959   case Intrinsic::x86_ssse3_psign_b_128:
11960   case Intrinsic::x86_ssse3_psign_w_128:
11961   case Intrinsic::x86_ssse3_psign_d_128:
11962   case Intrinsic::x86_avx2_psign_b:
11963   case Intrinsic::x86_avx2_psign_w:
11964   case Intrinsic::x86_avx2_psign_d:
11965     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11966                        Op.getOperand(1), Op.getOperand(2));
11967
11968   case Intrinsic::x86_sse41_insertps:
11969     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11970                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11971
11972   case Intrinsic::x86_avx_vperm2f128_ps_256:
11973   case Intrinsic::x86_avx_vperm2f128_pd_256:
11974   case Intrinsic::x86_avx_vperm2f128_si_256:
11975   case Intrinsic::x86_avx2_vperm2i128:
11976     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11977                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11978
11979   case Intrinsic::x86_avx2_permd:
11980   case Intrinsic::x86_avx2_permps:
11981     // Operands intentionally swapped. Mask is last operand to intrinsic,
11982     // but second operand for node/instruction.
11983     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11984                        Op.getOperand(2), Op.getOperand(1));
11985
11986   case Intrinsic::x86_sse_sqrt_ps:
11987   case Intrinsic::x86_sse2_sqrt_pd:
11988   case Intrinsic::x86_avx_sqrt_ps_256:
11989   case Intrinsic::x86_avx_sqrt_pd_256:
11990     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11991
11992   // ptest and testp intrinsics. The intrinsic these come from are designed to
11993   // return an integer value, not just an instruction so lower it to the ptest
11994   // or testp pattern and a setcc for the result.
11995   case Intrinsic::x86_sse41_ptestz:
11996   case Intrinsic::x86_sse41_ptestc:
11997   case Intrinsic::x86_sse41_ptestnzc:
11998   case Intrinsic::x86_avx_ptestz_256:
11999   case Intrinsic::x86_avx_ptestc_256:
12000   case Intrinsic::x86_avx_ptestnzc_256:
12001   case Intrinsic::x86_avx_vtestz_ps:
12002   case Intrinsic::x86_avx_vtestc_ps:
12003   case Intrinsic::x86_avx_vtestnzc_ps:
12004   case Intrinsic::x86_avx_vtestz_pd:
12005   case Intrinsic::x86_avx_vtestc_pd:
12006   case Intrinsic::x86_avx_vtestnzc_pd:
12007   case Intrinsic::x86_avx_vtestz_ps_256:
12008   case Intrinsic::x86_avx_vtestc_ps_256:
12009   case Intrinsic::x86_avx_vtestnzc_ps_256:
12010   case Intrinsic::x86_avx_vtestz_pd_256:
12011   case Intrinsic::x86_avx_vtestc_pd_256:
12012   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12013     bool IsTestPacked = false;
12014     unsigned X86CC;
12015     switch (IntNo) {
12016     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12017     case Intrinsic::x86_avx_vtestz_ps:
12018     case Intrinsic::x86_avx_vtestz_pd:
12019     case Intrinsic::x86_avx_vtestz_ps_256:
12020     case Intrinsic::x86_avx_vtestz_pd_256:
12021       IsTestPacked = true; // Fallthrough
12022     case Intrinsic::x86_sse41_ptestz:
12023     case Intrinsic::x86_avx_ptestz_256:
12024       // ZF = 1
12025       X86CC = X86::COND_E;
12026       break;
12027     case Intrinsic::x86_avx_vtestc_ps:
12028     case Intrinsic::x86_avx_vtestc_pd:
12029     case Intrinsic::x86_avx_vtestc_ps_256:
12030     case Intrinsic::x86_avx_vtestc_pd_256:
12031       IsTestPacked = true; // Fallthrough
12032     case Intrinsic::x86_sse41_ptestc:
12033     case Intrinsic::x86_avx_ptestc_256:
12034       // CF = 1
12035       X86CC = X86::COND_B;
12036       break;
12037     case Intrinsic::x86_avx_vtestnzc_ps:
12038     case Intrinsic::x86_avx_vtestnzc_pd:
12039     case Intrinsic::x86_avx_vtestnzc_ps_256:
12040     case Intrinsic::x86_avx_vtestnzc_pd_256:
12041       IsTestPacked = true; // Fallthrough
12042     case Intrinsic::x86_sse41_ptestnzc:
12043     case Intrinsic::x86_avx_ptestnzc_256:
12044       // ZF and CF = 0
12045       X86CC = X86::COND_A;
12046       break;
12047     }
12048
12049     SDValue LHS = Op.getOperand(1);
12050     SDValue RHS = Op.getOperand(2);
12051     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12052     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12053     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12054     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12055     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12056   }
12057   case Intrinsic::x86_avx512_kortestz_w:
12058   case Intrinsic::x86_avx512_kortestc_w: {
12059     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12060     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12061     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12062     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12063     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12064     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12065     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12066   }
12067
12068   // SSE/AVX shift intrinsics
12069   case Intrinsic::x86_sse2_psll_w:
12070   case Intrinsic::x86_sse2_psll_d:
12071   case Intrinsic::x86_sse2_psll_q:
12072   case Intrinsic::x86_avx2_psll_w:
12073   case Intrinsic::x86_avx2_psll_d:
12074   case Intrinsic::x86_avx2_psll_q:
12075   case Intrinsic::x86_sse2_psrl_w:
12076   case Intrinsic::x86_sse2_psrl_d:
12077   case Intrinsic::x86_sse2_psrl_q:
12078   case Intrinsic::x86_avx2_psrl_w:
12079   case Intrinsic::x86_avx2_psrl_d:
12080   case Intrinsic::x86_avx2_psrl_q:
12081   case Intrinsic::x86_sse2_psra_w:
12082   case Intrinsic::x86_sse2_psra_d:
12083   case Intrinsic::x86_avx2_psra_w:
12084   case Intrinsic::x86_avx2_psra_d: {
12085     unsigned Opcode;
12086     switch (IntNo) {
12087     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12088     case Intrinsic::x86_sse2_psll_w:
12089     case Intrinsic::x86_sse2_psll_d:
12090     case Intrinsic::x86_sse2_psll_q:
12091     case Intrinsic::x86_avx2_psll_w:
12092     case Intrinsic::x86_avx2_psll_d:
12093     case Intrinsic::x86_avx2_psll_q:
12094       Opcode = X86ISD::VSHL;
12095       break;
12096     case Intrinsic::x86_sse2_psrl_w:
12097     case Intrinsic::x86_sse2_psrl_d:
12098     case Intrinsic::x86_sse2_psrl_q:
12099     case Intrinsic::x86_avx2_psrl_w:
12100     case Intrinsic::x86_avx2_psrl_d:
12101     case Intrinsic::x86_avx2_psrl_q:
12102       Opcode = X86ISD::VSRL;
12103       break;
12104     case Intrinsic::x86_sse2_psra_w:
12105     case Intrinsic::x86_sse2_psra_d:
12106     case Intrinsic::x86_avx2_psra_w:
12107     case Intrinsic::x86_avx2_psra_d:
12108       Opcode = X86ISD::VSRA;
12109       break;
12110     }
12111     return DAG.getNode(Opcode, dl, Op.getValueType(),
12112                        Op.getOperand(1), Op.getOperand(2));
12113   }
12114
12115   // SSE/AVX immediate shift intrinsics
12116   case Intrinsic::x86_sse2_pslli_w:
12117   case Intrinsic::x86_sse2_pslli_d:
12118   case Intrinsic::x86_sse2_pslli_q:
12119   case Intrinsic::x86_avx2_pslli_w:
12120   case Intrinsic::x86_avx2_pslli_d:
12121   case Intrinsic::x86_avx2_pslli_q:
12122   case Intrinsic::x86_sse2_psrli_w:
12123   case Intrinsic::x86_sse2_psrli_d:
12124   case Intrinsic::x86_sse2_psrli_q:
12125   case Intrinsic::x86_avx2_psrli_w:
12126   case Intrinsic::x86_avx2_psrli_d:
12127   case Intrinsic::x86_avx2_psrli_q:
12128   case Intrinsic::x86_sse2_psrai_w:
12129   case Intrinsic::x86_sse2_psrai_d:
12130   case Intrinsic::x86_avx2_psrai_w:
12131   case Intrinsic::x86_avx2_psrai_d: {
12132     unsigned Opcode;
12133     switch (IntNo) {
12134     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12135     case Intrinsic::x86_sse2_pslli_w:
12136     case Intrinsic::x86_sse2_pslli_d:
12137     case Intrinsic::x86_sse2_pslli_q:
12138     case Intrinsic::x86_avx2_pslli_w:
12139     case Intrinsic::x86_avx2_pslli_d:
12140     case Intrinsic::x86_avx2_pslli_q:
12141       Opcode = X86ISD::VSHLI;
12142       break;
12143     case Intrinsic::x86_sse2_psrli_w:
12144     case Intrinsic::x86_sse2_psrli_d:
12145     case Intrinsic::x86_sse2_psrli_q:
12146     case Intrinsic::x86_avx2_psrli_w:
12147     case Intrinsic::x86_avx2_psrli_d:
12148     case Intrinsic::x86_avx2_psrli_q:
12149       Opcode = X86ISD::VSRLI;
12150       break;
12151     case Intrinsic::x86_sse2_psrai_w:
12152     case Intrinsic::x86_sse2_psrai_d:
12153     case Intrinsic::x86_avx2_psrai_w:
12154     case Intrinsic::x86_avx2_psrai_d:
12155       Opcode = X86ISD::VSRAI;
12156       break;
12157     }
12158     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12159                                Op.getOperand(1), Op.getOperand(2), DAG);
12160   }
12161
12162   case Intrinsic::x86_sse42_pcmpistria128:
12163   case Intrinsic::x86_sse42_pcmpestria128:
12164   case Intrinsic::x86_sse42_pcmpistric128:
12165   case Intrinsic::x86_sse42_pcmpestric128:
12166   case Intrinsic::x86_sse42_pcmpistrio128:
12167   case Intrinsic::x86_sse42_pcmpestrio128:
12168   case Intrinsic::x86_sse42_pcmpistris128:
12169   case Intrinsic::x86_sse42_pcmpestris128:
12170   case Intrinsic::x86_sse42_pcmpistriz128:
12171   case Intrinsic::x86_sse42_pcmpestriz128: {
12172     unsigned Opcode;
12173     unsigned X86CC;
12174     switch (IntNo) {
12175     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12176     case Intrinsic::x86_sse42_pcmpistria128:
12177       Opcode = X86ISD::PCMPISTRI;
12178       X86CC = X86::COND_A;
12179       break;
12180     case Intrinsic::x86_sse42_pcmpestria128:
12181       Opcode = X86ISD::PCMPESTRI;
12182       X86CC = X86::COND_A;
12183       break;
12184     case Intrinsic::x86_sse42_pcmpistric128:
12185       Opcode = X86ISD::PCMPISTRI;
12186       X86CC = X86::COND_B;
12187       break;
12188     case Intrinsic::x86_sse42_pcmpestric128:
12189       Opcode = X86ISD::PCMPESTRI;
12190       X86CC = X86::COND_B;
12191       break;
12192     case Intrinsic::x86_sse42_pcmpistrio128:
12193       Opcode = X86ISD::PCMPISTRI;
12194       X86CC = X86::COND_O;
12195       break;
12196     case Intrinsic::x86_sse42_pcmpestrio128:
12197       Opcode = X86ISD::PCMPESTRI;
12198       X86CC = X86::COND_O;
12199       break;
12200     case Intrinsic::x86_sse42_pcmpistris128:
12201       Opcode = X86ISD::PCMPISTRI;
12202       X86CC = X86::COND_S;
12203       break;
12204     case Intrinsic::x86_sse42_pcmpestris128:
12205       Opcode = X86ISD::PCMPESTRI;
12206       X86CC = X86::COND_S;
12207       break;
12208     case Intrinsic::x86_sse42_pcmpistriz128:
12209       Opcode = X86ISD::PCMPISTRI;
12210       X86CC = X86::COND_E;
12211       break;
12212     case Intrinsic::x86_sse42_pcmpestriz128:
12213       Opcode = X86ISD::PCMPESTRI;
12214       X86CC = X86::COND_E;
12215       break;
12216     }
12217     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12218     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12219     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12220     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12221                                 DAG.getConstant(X86CC, MVT::i8),
12222                                 SDValue(PCMP.getNode(), 1));
12223     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12224   }
12225
12226   case Intrinsic::x86_sse42_pcmpistri128:
12227   case Intrinsic::x86_sse42_pcmpestri128: {
12228     unsigned Opcode;
12229     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12230       Opcode = X86ISD::PCMPISTRI;
12231     else
12232       Opcode = X86ISD::PCMPESTRI;
12233
12234     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12235     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12236     return DAG.getNode(Opcode, dl, VTs, NewOps);
12237   }
12238   case Intrinsic::x86_fma_vfmadd_ps:
12239   case Intrinsic::x86_fma_vfmadd_pd:
12240   case Intrinsic::x86_fma_vfmsub_ps:
12241   case Intrinsic::x86_fma_vfmsub_pd:
12242   case Intrinsic::x86_fma_vfnmadd_ps:
12243   case Intrinsic::x86_fma_vfnmadd_pd:
12244   case Intrinsic::x86_fma_vfnmsub_ps:
12245   case Intrinsic::x86_fma_vfnmsub_pd:
12246   case Intrinsic::x86_fma_vfmaddsub_ps:
12247   case Intrinsic::x86_fma_vfmaddsub_pd:
12248   case Intrinsic::x86_fma_vfmsubadd_ps:
12249   case Intrinsic::x86_fma_vfmsubadd_pd:
12250   case Intrinsic::x86_fma_vfmadd_ps_256:
12251   case Intrinsic::x86_fma_vfmadd_pd_256:
12252   case Intrinsic::x86_fma_vfmsub_ps_256:
12253   case Intrinsic::x86_fma_vfmsub_pd_256:
12254   case Intrinsic::x86_fma_vfnmadd_ps_256:
12255   case Intrinsic::x86_fma_vfnmadd_pd_256:
12256   case Intrinsic::x86_fma_vfnmsub_ps_256:
12257   case Intrinsic::x86_fma_vfnmsub_pd_256:
12258   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12259   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12260   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12261   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12262   case Intrinsic::x86_fma_vfmadd_ps_512:
12263   case Intrinsic::x86_fma_vfmadd_pd_512:
12264   case Intrinsic::x86_fma_vfmsub_ps_512:
12265   case Intrinsic::x86_fma_vfmsub_pd_512:
12266   case Intrinsic::x86_fma_vfnmadd_ps_512:
12267   case Intrinsic::x86_fma_vfnmadd_pd_512:
12268   case Intrinsic::x86_fma_vfnmsub_ps_512:
12269   case Intrinsic::x86_fma_vfnmsub_pd_512:
12270   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12271   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12272   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12273   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12274     unsigned Opc;
12275     switch (IntNo) {
12276     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12277     case Intrinsic::x86_fma_vfmadd_ps:
12278     case Intrinsic::x86_fma_vfmadd_pd:
12279     case Intrinsic::x86_fma_vfmadd_ps_256:
12280     case Intrinsic::x86_fma_vfmadd_pd_256:
12281     case Intrinsic::x86_fma_vfmadd_ps_512:
12282     case Intrinsic::x86_fma_vfmadd_pd_512:
12283       Opc = X86ISD::FMADD;
12284       break;
12285     case Intrinsic::x86_fma_vfmsub_ps:
12286     case Intrinsic::x86_fma_vfmsub_pd:
12287     case Intrinsic::x86_fma_vfmsub_ps_256:
12288     case Intrinsic::x86_fma_vfmsub_pd_256:
12289     case Intrinsic::x86_fma_vfmsub_ps_512:
12290     case Intrinsic::x86_fma_vfmsub_pd_512:
12291       Opc = X86ISD::FMSUB;
12292       break;
12293     case Intrinsic::x86_fma_vfnmadd_ps:
12294     case Intrinsic::x86_fma_vfnmadd_pd:
12295     case Intrinsic::x86_fma_vfnmadd_ps_256:
12296     case Intrinsic::x86_fma_vfnmadd_pd_256:
12297     case Intrinsic::x86_fma_vfnmadd_ps_512:
12298     case Intrinsic::x86_fma_vfnmadd_pd_512:
12299       Opc = X86ISD::FNMADD;
12300       break;
12301     case Intrinsic::x86_fma_vfnmsub_ps:
12302     case Intrinsic::x86_fma_vfnmsub_pd:
12303     case Intrinsic::x86_fma_vfnmsub_ps_256:
12304     case Intrinsic::x86_fma_vfnmsub_pd_256:
12305     case Intrinsic::x86_fma_vfnmsub_ps_512:
12306     case Intrinsic::x86_fma_vfnmsub_pd_512:
12307       Opc = X86ISD::FNMSUB;
12308       break;
12309     case Intrinsic::x86_fma_vfmaddsub_ps:
12310     case Intrinsic::x86_fma_vfmaddsub_pd:
12311     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12312     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12313     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12314     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12315       Opc = X86ISD::FMADDSUB;
12316       break;
12317     case Intrinsic::x86_fma_vfmsubadd_ps:
12318     case Intrinsic::x86_fma_vfmsubadd_pd:
12319     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12320     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12321     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12322     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12323       Opc = X86ISD::FMSUBADD;
12324       break;
12325     }
12326
12327     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12328                        Op.getOperand(2), Op.getOperand(3));
12329   }
12330   }
12331 }
12332
12333 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12334                              SDValue Base, SDValue Index,
12335                              SDValue ScaleOp, SDValue Chain,
12336                              const X86Subtarget * Subtarget) {
12337   SDLoc dl(Op);
12338   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12339   assert(C && "Invalid scale type");
12340   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12341   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12342   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12343                              Index.getSimpleValueType().getVectorNumElements());
12344   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12345   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12346   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12347   SDValue Segment = DAG.getRegister(0, MVT::i32);
12348   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12349   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12350   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12351   return DAG.getMergeValues(RetOps, dl);
12352 }
12353
12354 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12355                               SDValue Src, SDValue Mask, SDValue Base,
12356                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12357                               const X86Subtarget * Subtarget) {
12358   SDLoc dl(Op);
12359   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12360   assert(C && "Invalid scale type");
12361   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
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(Op.getValueType(), MaskVT, MVT::Other);
12366   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12367   SDValue Segment = DAG.getRegister(0, MVT::i32);
12368   if (Src.getOpcode() == ISD::UNDEF)
12369     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12370   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12371   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12372   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12373   return DAG.getMergeValues(RetOps, dl);
12374 }
12375
12376 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12377                               SDValue Src, SDValue Base, SDValue Index,
12378                               SDValue ScaleOp, SDValue Chain) {
12379   SDLoc dl(Op);
12380   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12381   assert(C && "Invalid scale type");
12382   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12383   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12384   SDValue Segment = DAG.getRegister(0, MVT::i32);
12385   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12386                              Index.getSimpleValueType().getVectorNumElements());
12387   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12388   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12389   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12390   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12391   return SDValue(Res, 1);
12392 }
12393
12394 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12395                                SDValue Src, SDValue Mask, SDValue Base,
12396                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12397   SDLoc dl(Op);
12398   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12399   assert(C && "Invalid scale type");
12400   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12401   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12402   SDValue Segment = DAG.getRegister(0, MVT::i32);
12403   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12404                              Index.getSimpleValueType().getVectorNumElements());
12405   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12406   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12407   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12408   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12409   return SDValue(Res, 1);
12410 }
12411
12412 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12413 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12414 // also used to custom lower READCYCLECOUNTER nodes.
12415 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12416                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12417                               SmallVectorImpl<SDValue> &Results) {
12418   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12419   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12420   SDValue LO, HI;
12421
12422   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12423   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12424   // and the EAX register is loaded with the low-order 32 bits.
12425   if (Subtarget->is64Bit()) {
12426     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12427     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12428                             LO.getValue(2));
12429   } else {
12430     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12431     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12432                             LO.getValue(2));
12433   }
12434   SDValue Chain = HI.getValue(1);
12435
12436   if (Opcode == X86ISD::RDTSCP_DAG) {
12437     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12438
12439     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12440     // the ECX register. Add 'ecx' explicitly to the chain.
12441     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12442                                      HI.getValue(2));
12443     // Explicitly store the content of ECX at the location passed in input
12444     // to the 'rdtscp' intrinsic.
12445     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12446                          MachinePointerInfo(), false, false, 0);
12447   }
12448
12449   if (Subtarget->is64Bit()) {
12450     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12451     // the EAX register is loaded with the low-order 32 bits.
12452     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12453                               DAG.getConstant(32, MVT::i8));
12454     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12455     Results.push_back(Chain);
12456     return;
12457   }
12458
12459   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12460   SDValue Ops[] = { LO, HI };
12461   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12462   Results.push_back(Pair);
12463   Results.push_back(Chain);
12464 }
12465
12466 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12467                                      SelectionDAG &DAG) {
12468   SmallVector<SDValue, 2> Results;
12469   SDLoc DL(Op);
12470   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12471                           Results);
12472   return DAG.getMergeValues(Results, DL);
12473 }
12474
12475 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12476                                       SelectionDAG &DAG) {
12477   SDLoc dl(Op);
12478   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12479   switch (IntNo) {
12480   default: return SDValue();    // Don't custom lower most intrinsics.
12481
12482   // RDRAND/RDSEED intrinsics.
12483   case Intrinsic::x86_rdrand_16:
12484   case Intrinsic::x86_rdrand_32:
12485   case Intrinsic::x86_rdrand_64:
12486   case Intrinsic::x86_rdseed_16:
12487   case Intrinsic::x86_rdseed_32:
12488   case Intrinsic::x86_rdseed_64: {
12489     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12490                        IntNo == Intrinsic::x86_rdseed_32 ||
12491                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12492                                                             X86ISD::RDRAND;
12493     // Emit the node with the right value type.
12494     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12495     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12496
12497     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12498     // Otherwise return the value from Rand, which is always 0, casted to i32.
12499     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12500                       DAG.getConstant(1, Op->getValueType(1)),
12501                       DAG.getConstant(X86::COND_B, MVT::i32),
12502                       SDValue(Result.getNode(), 1) };
12503     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12504                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12505                                   Ops);
12506
12507     // Return { result, isValid, chain }.
12508     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12509                        SDValue(Result.getNode(), 2));
12510   }
12511   //int_gather(index, base, scale);
12512   case Intrinsic::x86_avx512_gather_qpd_512:
12513   case Intrinsic::x86_avx512_gather_qps_512:
12514   case Intrinsic::x86_avx512_gather_dpd_512:
12515   case Intrinsic::x86_avx512_gather_qpi_512:
12516   case Intrinsic::x86_avx512_gather_qpq_512:
12517   case Intrinsic::x86_avx512_gather_dpq_512:
12518   case Intrinsic::x86_avx512_gather_dps_512:
12519   case Intrinsic::x86_avx512_gather_dpi_512: {
12520     unsigned Opc;
12521     switch (IntNo) {
12522     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12523     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12524     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12525     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12526     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12527     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12528     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12529     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12530     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12531     }
12532     SDValue Chain = Op.getOperand(0);
12533     SDValue Index = Op.getOperand(2);
12534     SDValue Base  = Op.getOperand(3);
12535     SDValue Scale = Op.getOperand(4);
12536     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12537   }
12538   //int_gather_mask(v1, mask, index, base, scale);
12539   case Intrinsic::x86_avx512_gather_qps_mask_512:
12540   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12541   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12542   case Intrinsic::x86_avx512_gather_dps_mask_512:
12543   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12544   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12545   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12546   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12547     unsigned Opc;
12548     switch (IntNo) {
12549     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12550     case Intrinsic::x86_avx512_gather_qps_mask_512:
12551       Opc = X86::VGATHERQPSZrm; break;
12552     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12553       Opc = X86::VGATHERQPDZrm; break;
12554     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12555       Opc = X86::VGATHERDPDZrm; break;
12556     case Intrinsic::x86_avx512_gather_dps_mask_512:
12557       Opc = X86::VGATHERDPSZrm; break;
12558     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12559       Opc = X86::VPGATHERQDZrm; break;
12560     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12561       Opc = X86::VPGATHERQQZrm; break;
12562     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12563       Opc = X86::VPGATHERDDZrm; break;
12564     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12565       Opc = X86::VPGATHERDQZrm; break;
12566     }
12567     SDValue Chain = Op.getOperand(0);
12568     SDValue Src   = Op.getOperand(2);
12569     SDValue Mask  = Op.getOperand(3);
12570     SDValue Index = Op.getOperand(4);
12571     SDValue Base  = Op.getOperand(5);
12572     SDValue Scale = Op.getOperand(6);
12573     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12574                           Subtarget);
12575   }
12576   //int_scatter(base, index, v1, scale);
12577   case Intrinsic::x86_avx512_scatter_qpd_512:
12578   case Intrinsic::x86_avx512_scatter_qps_512:
12579   case Intrinsic::x86_avx512_scatter_dpd_512:
12580   case Intrinsic::x86_avx512_scatter_qpi_512:
12581   case Intrinsic::x86_avx512_scatter_qpq_512:
12582   case Intrinsic::x86_avx512_scatter_dpq_512:
12583   case Intrinsic::x86_avx512_scatter_dps_512:
12584   case Intrinsic::x86_avx512_scatter_dpi_512: {
12585     unsigned Opc;
12586     switch (IntNo) {
12587     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12588     case Intrinsic::x86_avx512_scatter_qpd_512:
12589       Opc = X86::VSCATTERQPDZmr; break;
12590     case Intrinsic::x86_avx512_scatter_qps_512:
12591       Opc = X86::VSCATTERQPSZmr; break;
12592     case Intrinsic::x86_avx512_scatter_dpd_512:
12593       Opc = X86::VSCATTERDPDZmr; break;
12594     case Intrinsic::x86_avx512_scatter_dps_512:
12595       Opc = X86::VSCATTERDPSZmr; break;
12596     case Intrinsic::x86_avx512_scatter_qpi_512:
12597       Opc = X86::VPSCATTERQDZmr; break;
12598     case Intrinsic::x86_avx512_scatter_qpq_512:
12599       Opc = X86::VPSCATTERQQZmr; break;
12600     case Intrinsic::x86_avx512_scatter_dpq_512:
12601       Opc = X86::VPSCATTERDQZmr; break;
12602     case Intrinsic::x86_avx512_scatter_dpi_512:
12603       Opc = X86::VPSCATTERDDZmr; break;
12604     }
12605     SDValue Chain = Op.getOperand(0);
12606     SDValue Base  = Op.getOperand(2);
12607     SDValue Index = Op.getOperand(3);
12608     SDValue Src   = Op.getOperand(4);
12609     SDValue Scale = Op.getOperand(5);
12610     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12611   }
12612   //int_scatter_mask(base, mask, index, v1, scale);
12613   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12614   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12615   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12616   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12617   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12618   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12619   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12620   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12621     unsigned Opc;
12622     switch (IntNo) {
12623     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12624     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12625       Opc = X86::VSCATTERQPDZmr; break;
12626     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12627       Opc = X86::VSCATTERQPSZmr; break;
12628     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12629       Opc = X86::VSCATTERDPDZmr; break;
12630     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12631       Opc = X86::VSCATTERDPSZmr; break;
12632     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12633       Opc = X86::VPSCATTERQDZmr; break;
12634     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12635       Opc = X86::VPSCATTERQQZmr; break;
12636     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12637       Opc = X86::VPSCATTERDQZmr; break;
12638     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12639       Opc = X86::VPSCATTERDDZmr; break;
12640     }
12641     SDValue Chain = Op.getOperand(0);
12642     SDValue Base  = Op.getOperand(2);
12643     SDValue Mask  = Op.getOperand(3);
12644     SDValue Index = Op.getOperand(4);
12645     SDValue Src   = Op.getOperand(5);
12646     SDValue Scale = Op.getOperand(6);
12647     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12648   }
12649   // Read Time Stamp Counter (RDTSC).
12650   case Intrinsic::x86_rdtsc:
12651   // Read Time Stamp Counter and Processor ID (RDTSCP).
12652   case Intrinsic::x86_rdtscp: {
12653     unsigned Opc;
12654     switch (IntNo) {
12655     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12656     case Intrinsic::x86_rdtsc:
12657       Opc = X86ISD::RDTSC_DAG; break;
12658     case Intrinsic::x86_rdtscp:
12659       Opc = X86ISD::RDTSCP_DAG; break;
12660     }
12661     SmallVector<SDValue, 2> Results;
12662     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12663     return DAG.getMergeValues(Results, dl);
12664   }
12665   // XTEST intrinsics.
12666   case Intrinsic::x86_xtest: {
12667     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12668     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12669     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12670                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12671                                 InTrans);
12672     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12673     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12674                        Ret, SDValue(InTrans.getNode(), 1));
12675   }
12676   }
12677 }
12678
12679 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12680                                            SelectionDAG &DAG) const {
12681   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12682   MFI->setReturnAddressIsTaken(true);
12683
12684   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12685     return SDValue();
12686
12687   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12688   SDLoc dl(Op);
12689   EVT PtrVT = getPointerTy();
12690
12691   if (Depth > 0) {
12692     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12693     const X86RegisterInfo *RegInfo =
12694       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12695     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12696     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12697                        DAG.getNode(ISD::ADD, dl, PtrVT,
12698                                    FrameAddr, Offset),
12699                        MachinePointerInfo(), false, false, false, 0);
12700   }
12701
12702   // Just load the return address.
12703   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12704   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12705                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12706 }
12707
12708 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12709   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12710   MFI->setFrameAddressIsTaken(true);
12711
12712   EVT VT = Op.getValueType();
12713   SDLoc dl(Op);  // FIXME probably not meaningful
12714   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12715   const X86RegisterInfo *RegInfo =
12716     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12717   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12718   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12719           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12720          "Invalid Frame Register!");
12721   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12722   while (Depth--)
12723     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12724                             MachinePointerInfo(),
12725                             false, false, false, 0);
12726   return FrameAddr;
12727 }
12728
12729 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12730                                                      SelectionDAG &DAG) const {
12731   const X86RegisterInfo *RegInfo =
12732     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12733   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12734 }
12735
12736 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12737   SDValue Chain     = Op.getOperand(0);
12738   SDValue Offset    = Op.getOperand(1);
12739   SDValue Handler   = Op.getOperand(2);
12740   SDLoc dl      (Op);
12741
12742   EVT PtrVT = getPointerTy();
12743   const X86RegisterInfo *RegInfo =
12744     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12745   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12746   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12747           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12748          "Invalid Frame Register!");
12749   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12750   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12751
12752   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12753                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12754   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12755   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12756                        false, false, 0);
12757   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12758
12759   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12760                      DAG.getRegister(StoreAddrReg, PtrVT));
12761 }
12762
12763 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12764                                                SelectionDAG &DAG) const {
12765   SDLoc DL(Op);
12766   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12767                      DAG.getVTList(MVT::i32, MVT::Other),
12768                      Op.getOperand(0), Op.getOperand(1));
12769 }
12770
12771 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12772                                                 SelectionDAG &DAG) const {
12773   SDLoc DL(Op);
12774   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12775                      Op.getOperand(0), Op.getOperand(1));
12776 }
12777
12778 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12779   return Op.getOperand(0);
12780 }
12781
12782 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12783                                                 SelectionDAG &DAG) const {
12784   SDValue Root = Op.getOperand(0);
12785   SDValue Trmp = Op.getOperand(1); // trampoline
12786   SDValue FPtr = Op.getOperand(2); // nested function
12787   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12788   SDLoc dl (Op);
12789
12790   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12791   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12792
12793   if (Subtarget->is64Bit()) {
12794     SDValue OutChains[6];
12795
12796     // Large code-model.
12797     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12798     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12799
12800     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12801     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12802
12803     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12804
12805     // Load the pointer to the nested function into R11.
12806     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12807     SDValue Addr = Trmp;
12808     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12809                                 Addr, MachinePointerInfo(TrmpAddr),
12810                                 false, false, 0);
12811
12812     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12813                        DAG.getConstant(2, MVT::i64));
12814     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12815                                 MachinePointerInfo(TrmpAddr, 2),
12816                                 false, false, 2);
12817
12818     // Load the 'nest' parameter value into R10.
12819     // R10 is specified in X86CallingConv.td
12820     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12821     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12822                        DAG.getConstant(10, MVT::i64));
12823     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12824                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12825                                 false, false, 0);
12826
12827     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12828                        DAG.getConstant(12, MVT::i64));
12829     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12830                                 MachinePointerInfo(TrmpAddr, 12),
12831                                 false, false, 2);
12832
12833     // Jump to the nested function.
12834     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12835     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12836                        DAG.getConstant(20, MVT::i64));
12837     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12838                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12839                                 false, false, 0);
12840
12841     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12842     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12843                        DAG.getConstant(22, MVT::i64));
12844     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12845                                 MachinePointerInfo(TrmpAddr, 22),
12846                                 false, false, 0);
12847
12848     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12849   } else {
12850     const Function *Func =
12851       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12852     CallingConv::ID CC = Func->getCallingConv();
12853     unsigned NestReg;
12854
12855     switch (CC) {
12856     default:
12857       llvm_unreachable("Unsupported calling convention");
12858     case CallingConv::C:
12859     case CallingConv::X86_StdCall: {
12860       // Pass 'nest' parameter in ECX.
12861       // Must be kept in sync with X86CallingConv.td
12862       NestReg = X86::ECX;
12863
12864       // Check that ECX wasn't needed by an 'inreg' parameter.
12865       FunctionType *FTy = Func->getFunctionType();
12866       const AttributeSet &Attrs = Func->getAttributes();
12867
12868       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12869         unsigned InRegCount = 0;
12870         unsigned Idx = 1;
12871
12872         for (FunctionType::param_iterator I = FTy->param_begin(),
12873              E = FTy->param_end(); I != E; ++I, ++Idx)
12874           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12875             // FIXME: should only count parameters that are lowered to integers.
12876             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12877
12878         if (InRegCount > 2) {
12879           report_fatal_error("Nest register in use - reduce number of inreg"
12880                              " parameters!");
12881         }
12882       }
12883       break;
12884     }
12885     case CallingConv::X86_FastCall:
12886     case CallingConv::X86_ThisCall:
12887     case CallingConv::Fast:
12888       // Pass 'nest' parameter in EAX.
12889       // Must be kept in sync with X86CallingConv.td
12890       NestReg = X86::EAX;
12891       break;
12892     }
12893
12894     SDValue OutChains[4];
12895     SDValue Addr, Disp;
12896
12897     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12898                        DAG.getConstant(10, MVT::i32));
12899     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12900
12901     // This is storing the opcode for MOV32ri.
12902     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12903     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12904     OutChains[0] = DAG.getStore(Root, dl,
12905                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12906                                 Trmp, MachinePointerInfo(TrmpAddr),
12907                                 false, false, 0);
12908
12909     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12910                        DAG.getConstant(1, MVT::i32));
12911     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12912                                 MachinePointerInfo(TrmpAddr, 1),
12913                                 false, false, 1);
12914
12915     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12916     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12917                        DAG.getConstant(5, MVT::i32));
12918     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12919                                 MachinePointerInfo(TrmpAddr, 5),
12920                                 false, false, 1);
12921
12922     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12923                        DAG.getConstant(6, MVT::i32));
12924     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12925                                 MachinePointerInfo(TrmpAddr, 6),
12926                                 false, false, 1);
12927
12928     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12929   }
12930 }
12931
12932 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12933                                             SelectionDAG &DAG) const {
12934   /*
12935    The rounding mode is in bits 11:10 of FPSR, and has the following
12936    settings:
12937      00 Round to nearest
12938      01 Round to -inf
12939      10 Round to +inf
12940      11 Round to 0
12941
12942   FLT_ROUNDS, on the other hand, expects the following:
12943     -1 Undefined
12944      0 Round to 0
12945      1 Round to nearest
12946      2 Round to +inf
12947      3 Round to -inf
12948
12949   To perform the conversion, we do:
12950     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12951   */
12952
12953   MachineFunction &MF = DAG.getMachineFunction();
12954   const TargetMachine &TM = MF.getTarget();
12955   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12956   unsigned StackAlignment = TFI.getStackAlignment();
12957   MVT VT = Op.getSimpleValueType();
12958   SDLoc DL(Op);
12959
12960   // Save FP Control Word to stack slot
12961   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12962   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12963
12964   MachineMemOperand *MMO =
12965    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12966                            MachineMemOperand::MOStore, 2, 2);
12967
12968   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12969   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12970                                           DAG.getVTList(MVT::Other),
12971                                           Ops, MVT::i16, MMO);
12972
12973   // Load FP Control Word from stack slot
12974   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12975                             MachinePointerInfo(), false, false, false, 0);
12976
12977   // Transform as necessary
12978   SDValue CWD1 =
12979     DAG.getNode(ISD::SRL, DL, MVT::i16,
12980                 DAG.getNode(ISD::AND, DL, MVT::i16,
12981                             CWD, DAG.getConstant(0x800, MVT::i16)),
12982                 DAG.getConstant(11, MVT::i8));
12983   SDValue CWD2 =
12984     DAG.getNode(ISD::SRL, DL, MVT::i16,
12985                 DAG.getNode(ISD::AND, DL, MVT::i16,
12986                             CWD, DAG.getConstant(0x400, MVT::i16)),
12987                 DAG.getConstant(9, MVT::i8));
12988
12989   SDValue RetVal =
12990     DAG.getNode(ISD::AND, DL, MVT::i16,
12991                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12992                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12993                             DAG.getConstant(1, MVT::i16)),
12994                 DAG.getConstant(3, MVT::i16));
12995
12996   return DAG.getNode((VT.getSizeInBits() < 16 ?
12997                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12998 }
12999
13000 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13001   MVT VT = Op.getSimpleValueType();
13002   EVT OpVT = VT;
13003   unsigned NumBits = VT.getSizeInBits();
13004   SDLoc dl(Op);
13005
13006   Op = Op.getOperand(0);
13007   if (VT == MVT::i8) {
13008     // Zero extend to i32 since there is not an i8 bsr.
13009     OpVT = MVT::i32;
13010     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13011   }
13012
13013   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13014   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13015   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13016
13017   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13018   SDValue Ops[] = {
13019     Op,
13020     DAG.getConstant(NumBits+NumBits-1, OpVT),
13021     DAG.getConstant(X86::COND_E, MVT::i8),
13022     Op.getValue(1)
13023   };
13024   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13025
13026   // Finally xor with NumBits-1.
13027   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13028
13029   if (VT == MVT::i8)
13030     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13031   return Op;
13032 }
13033
13034 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13035   MVT VT = Op.getSimpleValueType();
13036   EVT OpVT = VT;
13037   unsigned NumBits = VT.getSizeInBits();
13038   SDLoc dl(Op);
13039
13040   Op = Op.getOperand(0);
13041   if (VT == MVT::i8) {
13042     // Zero extend to i32 since there is not an i8 bsr.
13043     OpVT = MVT::i32;
13044     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13045   }
13046
13047   // Issue a bsr (scan bits in reverse).
13048   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13049   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13050
13051   // And xor with NumBits-1.
13052   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13053
13054   if (VT == MVT::i8)
13055     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13056   return Op;
13057 }
13058
13059 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13060   MVT VT = Op.getSimpleValueType();
13061   unsigned NumBits = VT.getSizeInBits();
13062   SDLoc dl(Op);
13063   Op = Op.getOperand(0);
13064
13065   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13066   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13067   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13068
13069   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13070   SDValue Ops[] = {
13071     Op,
13072     DAG.getConstant(NumBits, VT),
13073     DAG.getConstant(X86::COND_E, MVT::i8),
13074     Op.getValue(1)
13075   };
13076   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13077 }
13078
13079 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13080 // ones, and then concatenate the result back.
13081 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13082   MVT VT = Op.getSimpleValueType();
13083
13084   assert(VT.is256BitVector() && VT.isInteger() &&
13085          "Unsupported value type for operation");
13086
13087   unsigned NumElems = VT.getVectorNumElements();
13088   SDLoc dl(Op);
13089
13090   // Extract the LHS vectors
13091   SDValue LHS = Op.getOperand(0);
13092   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13093   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13094
13095   // Extract the RHS vectors
13096   SDValue RHS = Op.getOperand(1);
13097   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13098   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13099
13100   MVT EltVT = VT.getVectorElementType();
13101   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13102
13103   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13104                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13105                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13106 }
13107
13108 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13109   assert(Op.getSimpleValueType().is256BitVector() &&
13110          Op.getSimpleValueType().isInteger() &&
13111          "Only handle AVX 256-bit vector integer operation");
13112   return Lower256IntArith(Op, DAG);
13113 }
13114
13115 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13116   assert(Op.getSimpleValueType().is256BitVector() &&
13117          Op.getSimpleValueType().isInteger() &&
13118          "Only handle AVX 256-bit vector integer operation");
13119   return Lower256IntArith(Op, DAG);
13120 }
13121
13122 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13123                         SelectionDAG &DAG) {
13124   SDLoc dl(Op);
13125   MVT VT = Op.getSimpleValueType();
13126
13127   // Decompose 256-bit ops into smaller 128-bit ops.
13128   if (VT.is256BitVector() && !Subtarget->hasInt256())
13129     return Lower256IntArith(Op, DAG);
13130
13131   SDValue A = Op.getOperand(0);
13132   SDValue B = Op.getOperand(1);
13133
13134   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13135   if (VT == MVT::v4i32) {
13136     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13137            "Should not custom lower when pmuldq is available!");
13138
13139     // Extract the odd parts.
13140     static const int UnpackMask[] = { 1, -1, 3, -1 };
13141     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13142     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13143
13144     // Multiply the even parts.
13145     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13146     // Now multiply odd parts.
13147     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13148
13149     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13150     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13151
13152     // Merge the two vectors back together with a shuffle. This expands into 2
13153     // shuffles.
13154     static const int ShufMask[] = { 0, 4, 2, 6 };
13155     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13156   }
13157
13158   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13159          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13160
13161   //  Ahi = psrlqi(a, 32);
13162   //  Bhi = psrlqi(b, 32);
13163   //
13164   //  AloBlo = pmuludq(a, b);
13165   //  AloBhi = pmuludq(a, Bhi);
13166   //  AhiBlo = pmuludq(Ahi, b);
13167
13168   //  AloBhi = psllqi(AloBhi, 32);
13169   //  AhiBlo = psllqi(AhiBlo, 32);
13170   //  return AloBlo + AloBhi + AhiBlo;
13171
13172   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13173   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13174
13175   // Bit cast to 32-bit vectors for MULUDQ
13176   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13177                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13178   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13179   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13180   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13181   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13182
13183   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13184   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13185   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13186
13187   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13188   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13189
13190   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13191   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13192 }
13193
13194 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13195   assert(Subtarget->isTargetWin64() && "Unexpected target");
13196   EVT VT = Op.getValueType();
13197   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13198          "Unexpected return type for lowering");
13199
13200   RTLIB::Libcall LC;
13201   bool isSigned;
13202   switch (Op->getOpcode()) {
13203   default: llvm_unreachable("Unexpected request for libcall!");
13204   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13205   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13206   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13207   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13208   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13209   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13210   }
13211
13212   SDLoc dl(Op);
13213   SDValue InChain = DAG.getEntryNode();
13214
13215   TargetLowering::ArgListTy Args;
13216   TargetLowering::ArgListEntry Entry;
13217   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13218     EVT ArgVT = Op->getOperand(i).getValueType();
13219     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13220            "Unexpected argument type for lowering");
13221     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13222     Entry.Node = StackPtr;
13223     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13224                            false, false, 16);
13225     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13226     Entry.Ty = PointerType::get(ArgTy,0);
13227     Entry.isSExt = false;
13228     Entry.isZExt = false;
13229     Args.push_back(Entry);
13230   }
13231
13232   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13233                                          getPointerTy());
13234
13235   TargetLowering::CallLoweringInfo CLI(
13236       InChain, static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13237       isSigned, !isSigned, false, true, 0, getLibcallCallingConv(LC),
13238       /*isTailCall=*/false,
13239       /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, Callee, Args, DAG,
13240       dl);
13241   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13242
13243   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13244 }
13245
13246 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13247                              SelectionDAG &DAG) {
13248   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13249   EVT VT = Op0.getValueType();
13250   SDLoc dl(Op);
13251
13252   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13253          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13254
13255   // Get the high parts.
13256   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13257   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13258   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13259
13260   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13261   // ints.
13262   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13263   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13264   unsigned Opcode =
13265       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13266   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13267                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13268   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13269                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13270
13271   // Shuffle it back into the right order.
13272   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13273   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13274   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13275   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13276
13277   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13278   // unsigned multiply.
13279   if (IsSigned && !Subtarget->hasSSE41()) {
13280     SDValue ShAmt =
13281         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13282     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13283                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13284     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13285                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13286
13287     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13288     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13289   }
13290
13291   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13292 }
13293
13294 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13295                                          const X86Subtarget *Subtarget) {
13296   MVT VT = Op.getSimpleValueType();
13297   SDLoc dl(Op);
13298   SDValue R = Op.getOperand(0);
13299   SDValue Amt = Op.getOperand(1);
13300
13301   // Optimize shl/srl/sra with constant shift amount.
13302   if (isSplatVector(Amt.getNode())) {
13303     SDValue SclrAmt = Amt->getOperand(0);
13304     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13305       uint64_t ShiftAmt = C->getZExtValue();
13306
13307       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13308           (Subtarget->hasInt256() &&
13309            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13310           (Subtarget->hasAVX512() &&
13311            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13312         if (Op.getOpcode() == ISD::SHL)
13313           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13314                                             DAG);
13315         if (Op.getOpcode() == ISD::SRL)
13316           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13317                                             DAG);
13318         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13319           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13320                                             DAG);
13321       }
13322
13323       if (VT == MVT::v16i8) {
13324         if (Op.getOpcode() == ISD::SHL) {
13325           // Make a large shift.
13326           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13327                                                    MVT::v8i16, R, ShiftAmt,
13328                                                    DAG);
13329           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13330           // Zero out the rightmost bits.
13331           SmallVector<SDValue, 16> V(16,
13332                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13333                                                      MVT::i8));
13334           return DAG.getNode(ISD::AND, dl, VT, SHL,
13335                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13336         }
13337         if (Op.getOpcode() == ISD::SRL) {
13338           // Make a large shift.
13339           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13340                                                    MVT::v8i16, R, ShiftAmt,
13341                                                    DAG);
13342           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13343           // Zero out the leftmost bits.
13344           SmallVector<SDValue, 16> V(16,
13345                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13346                                                      MVT::i8));
13347           return DAG.getNode(ISD::AND, dl, VT, SRL,
13348                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13349         }
13350         if (Op.getOpcode() == ISD::SRA) {
13351           if (ShiftAmt == 7) {
13352             // R s>> 7  ===  R s< 0
13353             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13354             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13355           }
13356
13357           // R s>> a === ((R u>> a) ^ m) - m
13358           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13359           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13360                                                          MVT::i8));
13361           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13362           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13363           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13364           return Res;
13365         }
13366         llvm_unreachable("Unknown shift opcode.");
13367       }
13368
13369       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13370         if (Op.getOpcode() == ISD::SHL) {
13371           // Make a large shift.
13372           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13373                                                    MVT::v16i16, R, ShiftAmt,
13374                                                    DAG);
13375           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13376           // Zero out the rightmost bits.
13377           SmallVector<SDValue, 32> V(32,
13378                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13379                                                      MVT::i8));
13380           return DAG.getNode(ISD::AND, dl, VT, SHL,
13381                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13382         }
13383         if (Op.getOpcode() == ISD::SRL) {
13384           // Make a large shift.
13385           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13386                                                    MVT::v16i16, R, ShiftAmt,
13387                                                    DAG);
13388           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13389           // Zero out the leftmost bits.
13390           SmallVector<SDValue, 32> V(32,
13391                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13392                                                      MVT::i8));
13393           return DAG.getNode(ISD::AND, dl, VT, SRL,
13394                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13395         }
13396         if (Op.getOpcode() == ISD::SRA) {
13397           if (ShiftAmt == 7) {
13398             // R s>> 7  ===  R s< 0
13399             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13400             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13401           }
13402
13403           // R s>> a === ((R u>> a) ^ m) - m
13404           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13405           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13406                                                          MVT::i8));
13407           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13408           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13409           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13410           return Res;
13411         }
13412         llvm_unreachable("Unknown shift opcode.");
13413       }
13414     }
13415   }
13416
13417   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13418   if (!Subtarget->is64Bit() &&
13419       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13420       Amt.getOpcode() == ISD::BITCAST &&
13421       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13422     Amt = Amt.getOperand(0);
13423     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13424                      VT.getVectorNumElements();
13425     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13426     uint64_t ShiftAmt = 0;
13427     for (unsigned i = 0; i != Ratio; ++i) {
13428       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13429       if (!C)
13430         return SDValue();
13431       // 6 == Log2(64)
13432       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13433     }
13434     // Check remaining shift amounts.
13435     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13436       uint64_t ShAmt = 0;
13437       for (unsigned j = 0; j != Ratio; ++j) {
13438         ConstantSDNode *C =
13439           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13440         if (!C)
13441           return SDValue();
13442         // 6 == Log2(64)
13443         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13444       }
13445       if (ShAmt != ShiftAmt)
13446         return SDValue();
13447     }
13448     switch (Op.getOpcode()) {
13449     default:
13450       llvm_unreachable("Unknown shift opcode!");
13451     case ISD::SHL:
13452       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13453                                         DAG);
13454     case ISD::SRL:
13455       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13456                                         DAG);
13457     case ISD::SRA:
13458       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13459                                         DAG);
13460     }
13461   }
13462
13463   return SDValue();
13464 }
13465
13466 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13467                                         const X86Subtarget* Subtarget) {
13468   MVT VT = Op.getSimpleValueType();
13469   SDLoc dl(Op);
13470   SDValue R = Op.getOperand(0);
13471   SDValue Amt = Op.getOperand(1);
13472
13473   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13474       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13475       (Subtarget->hasInt256() &&
13476        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13477         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13478        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13479     SDValue BaseShAmt;
13480     EVT EltVT = VT.getVectorElementType();
13481
13482     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13483       unsigned NumElts = VT.getVectorNumElements();
13484       unsigned i, j;
13485       for (i = 0; i != NumElts; ++i) {
13486         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13487           continue;
13488         break;
13489       }
13490       for (j = i; j != NumElts; ++j) {
13491         SDValue Arg = Amt.getOperand(j);
13492         if (Arg.getOpcode() == ISD::UNDEF) continue;
13493         if (Arg != Amt.getOperand(i))
13494           break;
13495       }
13496       if (i != NumElts && j == NumElts)
13497         BaseShAmt = Amt.getOperand(i);
13498     } else {
13499       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13500         Amt = Amt.getOperand(0);
13501       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13502                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13503         SDValue InVec = Amt.getOperand(0);
13504         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13505           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13506           unsigned i = 0;
13507           for (; i != NumElts; ++i) {
13508             SDValue Arg = InVec.getOperand(i);
13509             if (Arg.getOpcode() == ISD::UNDEF) continue;
13510             BaseShAmt = Arg;
13511             break;
13512           }
13513         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13514            if (ConstantSDNode *C =
13515                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13516              unsigned SplatIdx =
13517                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13518              if (C->getZExtValue() == SplatIdx)
13519                BaseShAmt = InVec.getOperand(1);
13520            }
13521         }
13522         if (!BaseShAmt.getNode())
13523           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13524                                   DAG.getIntPtrConstant(0));
13525       }
13526     }
13527
13528     if (BaseShAmt.getNode()) {
13529       if (EltVT.bitsGT(MVT::i32))
13530         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13531       else if (EltVT.bitsLT(MVT::i32))
13532         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13533
13534       switch (Op.getOpcode()) {
13535       default:
13536         llvm_unreachable("Unknown shift opcode!");
13537       case ISD::SHL:
13538         switch (VT.SimpleTy) {
13539         default: return SDValue();
13540         case MVT::v2i64:
13541         case MVT::v4i32:
13542         case MVT::v8i16:
13543         case MVT::v4i64:
13544         case MVT::v8i32:
13545         case MVT::v16i16:
13546         case MVT::v16i32:
13547         case MVT::v8i64:
13548           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13549         }
13550       case ISD::SRA:
13551         switch (VT.SimpleTy) {
13552         default: return SDValue();
13553         case MVT::v4i32:
13554         case MVT::v8i16:
13555         case MVT::v8i32:
13556         case MVT::v16i16:
13557         case MVT::v16i32:
13558         case MVT::v8i64:
13559           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13560         }
13561       case ISD::SRL:
13562         switch (VT.SimpleTy) {
13563         default: return SDValue();
13564         case MVT::v2i64:
13565         case MVT::v4i32:
13566         case MVT::v8i16:
13567         case MVT::v4i64:
13568         case MVT::v8i32:
13569         case MVT::v16i16:
13570         case MVT::v16i32:
13571         case MVT::v8i64:
13572           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13573         }
13574       }
13575     }
13576   }
13577
13578   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13579   if (!Subtarget->is64Bit() &&
13580       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13581       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13582       Amt.getOpcode() == ISD::BITCAST &&
13583       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13584     Amt = Amt.getOperand(0);
13585     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13586                      VT.getVectorNumElements();
13587     std::vector<SDValue> Vals(Ratio);
13588     for (unsigned i = 0; i != Ratio; ++i)
13589       Vals[i] = Amt.getOperand(i);
13590     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13591       for (unsigned j = 0; j != Ratio; ++j)
13592         if (Vals[j] != Amt.getOperand(i + j))
13593           return SDValue();
13594     }
13595     switch (Op.getOpcode()) {
13596     default:
13597       llvm_unreachable("Unknown shift opcode!");
13598     case ISD::SHL:
13599       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13600     case ISD::SRL:
13601       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13602     case ISD::SRA:
13603       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13604     }
13605   }
13606
13607   return SDValue();
13608 }
13609
13610 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13611                           SelectionDAG &DAG) {
13612
13613   MVT VT = Op.getSimpleValueType();
13614   SDLoc dl(Op);
13615   SDValue R = Op.getOperand(0);
13616   SDValue Amt = Op.getOperand(1);
13617   SDValue V;
13618
13619   if (!Subtarget->hasSSE2())
13620     return SDValue();
13621
13622   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13623   if (V.getNode())
13624     return V;
13625
13626   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13627   if (V.getNode())
13628       return V;
13629
13630   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13631     return Op;
13632   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13633   if (Subtarget->hasInt256()) {
13634     if (Op.getOpcode() == ISD::SRL &&
13635         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13636          VT == MVT::v4i64 || VT == MVT::v8i32))
13637       return Op;
13638     if (Op.getOpcode() == ISD::SHL &&
13639         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13640          VT == MVT::v4i64 || VT == MVT::v8i32))
13641       return Op;
13642     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13643       return Op;
13644   }
13645
13646   // If possible, lower this packed shift into a vector multiply instead of
13647   // expanding it into a sequence of scalar shifts.
13648   // Do this only if the vector shift count is a constant build_vector.
13649   if (Op.getOpcode() == ISD::SHL && 
13650       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13651        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13652       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13653     SmallVector<SDValue, 8> Elts;
13654     EVT SVT = VT.getScalarType();
13655     unsigned SVTBits = SVT.getSizeInBits();
13656     const APInt &One = APInt(SVTBits, 1);
13657     unsigned NumElems = VT.getVectorNumElements();
13658
13659     for (unsigned i=0; i !=NumElems; ++i) {
13660       SDValue Op = Amt->getOperand(i);
13661       if (Op->getOpcode() == ISD::UNDEF) {
13662         Elts.push_back(Op);
13663         continue;
13664       }
13665
13666       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13667       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13668       uint64_t ShAmt = C.getZExtValue();
13669       if (ShAmt >= SVTBits) {
13670         Elts.push_back(DAG.getUNDEF(SVT));
13671         continue;
13672       }
13673       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13674     }
13675     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13676     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13677   }
13678
13679   // Lower SHL with variable shift amount.
13680   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13681     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13682
13683     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13684     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13685     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13686     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13687   }
13688
13689   // If possible, lower this shift as a sequence of two shifts by
13690   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13691   // Example:
13692   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13693   //
13694   // Could be rewritten as:
13695   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13696   //
13697   // The advantage is that the two shifts from the example would be
13698   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13699   // the vector shift into four scalar shifts plus four pairs of vector
13700   // insert/extract.
13701   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13702       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13703     unsigned TargetOpcode = X86ISD::MOVSS;
13704     bool CanBeSimplified;
13705     // The splat value for the first packed shift (the 'X' from the example).
13706     SDValue Amt1 = Amt->getOperand(0);
13707     // The splat value for the second packed shift (the 'Y' from the example).
13708     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13709                                         Amt->getOperand(2);
13710
13711     // See if it is possible to replace this node with a sequence of
13712     // two shifts followed by a MOVSS/MOVSD
13713     if (VT == MVT::v4i32) {
13714       // Check if it is legal to use a MOVSS.
13715       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13716                         Amt2 == Amt->getOperand(3);
13717       if (!CanBeSimplified) {
13718         // Otherwise, check if we can still simplify this node using a MOVSD.
13719         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13720                           Amt->getOperand(2) == Amt->getOperand(3);
13721         TargetOpcode = X86ISD::MOVSD;
13722         Amt2 = Amt->getOperand(2);
13723       }
13724     } else {
13725       // Do similar checks for the case where the machine value type
13726       // is MVT::v8i16.
13727       CanBeSimplified = Amt1 == Amt->getOperand(1);
13728       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13729         CanBeSimplified = Amt2 == Amt->getOperand(i);
13730
13731       if (!CanBeSimplified) {
13732         TargetOpcode = X86ISD::MOVSD;
13733         CanBeSimplified = true;
13734         Amt2 = Amt->getOperand(4);
13735         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13736           CanBeSimplified = Amt1 == Amt->getOperand(i);
13737         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13738           CanBeSimplified = Amt2 == Amt->getOperand(j);
13739       }
13740     }
13741     
13742     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13743         isa<ConstantSDNode>(Amt2)) {
13744       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13745       EVT CastVT = MVT::v4i32;
13746       SDValue Splat1 = 
13747         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13748       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13749       SDValue Splat2 = 
13750         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13751       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13752       if (TargetOpcode == X86ISD::MOVSD)
13753         CastVT = MVT::v2i64;
13754       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13755       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13756       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13757                                             BitCast1, DAG);
13758       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13759     }
13760   }
13761
13762   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13763     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13764
13765     // a = a << 5;
13766     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13767     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13768
13769     // Turn 'a' into a mask suitable for VSELECT
13770     SDValue VSelM = DAG.getConstant(0x80, VT);
13771     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13772     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13773
13774     SDValue CM1 = DAG.getConstant(0x0f, VT);
13775     SDValue CM2 = DAG.getConstant(0x3f, VT);
13776
13777     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13778     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13779     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13780     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13781     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13782
13783     // a += a
13784     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13785     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13786     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13787
13788     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13789     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13790     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13791     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13792     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13793
13794     // a += a
13795     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13796     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13797     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13798
13799     // return VSELECT(r, r+r, a);
13800     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13801                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13802     return R;
13803   }
13804
13805   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13806   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13807   // solution better.
13808   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13809     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13810     unsigned ExtOpc =
13811         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13812     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13813     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13814     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13815                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13816     }
13817
13818   // Decompose 256-bit shifts into smaller 128-bit shifts.
13819   if (VT.is256BitVector()) {
13820     unsigned NumElems = VT.getVectorNumElements();
13821     MVT EltVT = VT.getVectorElementType();
13822     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13823
13824     // Extract the two vectors
13825     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13826     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13827
13828     // Recreate the shift amount vectors
13829     SDValue Amt1, Amt2;
13830     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13831       // Constant shift amount
13832       SmallVector<SDValue, 4> Amt1Csts;
13833       SmallVector<SDValue, 4> Amt2Csts;
13834       for (unsigned i = 0; i != NumElems/2; ++i)
13835         Amt1Csts.push_back(Amt->getOperand(i));
13836       for (unsigned i = NumElems/2; i != NumElems; ++i)
13837         Amt2Csts.push_back(Amt->getOperand(i));
13838
13839       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13840       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13841     } else {
13842       // Variable shift amount
13843       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13844       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13845     }
13846
13847     // Issue new vector shifts for the smaller types
13848     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13849     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13850
13851     // Concatenate the result back
13852     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13853   }
13854
13855   return SDValue();
13856 }
13857
13858 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13859   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13860   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13861   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13862   // has only one use.
13863   SDNode *N = Op.getNode();
13864   SDValue LHS = N->getOperand(0);
13865   SDValue RHS = N->getOperand(1);
13866   unsigned BaseOp = 0;
13867   unsigned Cond = 0;
13868   SDLoc DL(Op);
13869   switch (Op.getOpcode()) {
13870   default: llvm_unreachable("Unknown ovf instruction!");
13871   case ISD::SADDO:
13872     // A subtract of one will be selected as a INC. Note that INC doesn't
13873     // set CF, so we can't do this for UADDO.
13874     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13875       if (C->isOne()) {
13876         BaseOp = X86ISD::INC;
13877         Cond = X86::COND_O;
13878         break;
13879       }
13880     BaseOp = X86ISD::ADD;
13881     Cond = X86::COND_O;
13882     break;
13883   case ISD::UADDO:
13884     BaseOp = X86ISD::ADD;
13885     Cond = X86::COND_B;
13886     break;
13887   case ISD::SSUBO:
13888     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13889     // set CF, so we can't do this for USUBO.
13890     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13891       if (C->isOne()) {
13892         BaseOp = X86ISD::DEC;
13893         Cond = X86::COND_O;
13894         break;
13895       }
13896     BaseOp = X86ISD::SUB;
13897     Cond = X86::COND_O;
13898     break;
13899   case ISD::USUBO:
13900     BaseOp = X86ISD::SUB;
13901     Cond = X86::COND_B;
13902     break;
13903   case ISD::SMULO:
13904     BaseOp = X86ISD::SMUL;
13905     Cond = X86::COND_O;
13906     break;
13907   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13908     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13909                                  MVT::i32);
13910     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13911
13912     SDValue SetCC =
13913       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13914                   DAG.getConstant(X86::COND_O, MVT::i32),
13915                   SDValue(Sum.getNode(), 2));
13916
13917     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13918   }
13919   }
13920
13921   // Also sets EFLAGS.
13922   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13923   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13924
13925   SDValue SetCC =
13926     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13927                 DAG.getConstant(Cond, MVT::i32),
13928                 SDValue(Sum.getNode(), 1));
13929
13930   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13931 }
13932
13933 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13934                                                   SelectionDAG &DAG) const {
13935   SDLoc dl(Op);
13936   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13937   MVT VT = Op.getSimpleValueType();
13938
13939   if (!Subtarget->hasSSE2() || !VT.isVector())
13940     return SDValue();
13941
13942   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13943                       ExtraVT.getScalarType().getSizeInBits();
13944
13945   switch (VT.SimpleTy) {
13946     default: return SDValue();
13947     case MVT::v8i32:
13948     case MVT::v16i16:
13949       if (!Subtarget->hasFp256())
13950         return SDValue();
13951       if (!Subtarget->hasInt256()) {
13952         // needs to be split
13953         unsigned NumElems = VT.getVectorNumElements();
13954
13955         // Extract the LHS vectors
13956         SDValue LHS = Op.getOperand(0);
13957         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13958         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13959
13960         MVT EltVT = VT.getVectorElementType();
13961         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13962
13963         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13964         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13965         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13966                                    ExtraNumElems/2);
13967         SDValue Extra = DAG.getValueType(ExtraVT);
13968
13969         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13970         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13971
13972         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13973       }
13974       // fall through
13975     case MVT::v4i32:
13976     case MVT::v8i16: {
13977       SDValue Op0 = Op.getOperand(0);
13978       SDValue Op00 = Op0.getOperand(0);
13979       SDValue Tmp1;
13980       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13981       if (Op0.getOpcode() == ISD::BITCAST &&
13982           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13983         // (sext (vzext x)) -> (vsext x)
13984         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13985         if (Tmp1.getNode()) {
13986           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13987           // This folding is only valid when the in-reg type is a vector of i8,
13988           // i16, or i32.
13989           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13990               ExtraEltVT == MVT::i32) {
13991             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13992             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13993                    "This optimization is invalid without a VZEXT.");
13994             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13995           }
13996           Op0 = Tmp1;
13997         }
13998       }
13999
14000       // If the above didn't work, then just use Shift-Left + Shift-Right.
14001       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14002                                         DAG);
14003       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14004                                         DAG);
14005     }
14006   }
14007 }
14008
14009 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14010                                  SelectionDAG &DAG) {
14011   SDLoc dl(Op);
14012   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14013     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14014   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14015     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14016
14017   // The only fence that needs an instruction is a sequentially-consistent
14018   // cross-thread fence.
14019   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14020     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14021     // no-sse2). There isn't any reason to disable it if the target processor
14022     // supports it.
14023     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14024       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14025
14026     SDValue Chain = Op.getOperand(0);
14027     SDValue Zero = DAG.getConstant(0, MVT::i32);
14028     SDValue Ops[] = {
14029       DAG.getRegister(X86::ESP, MVT::i32), // Base
14030       DAG.getTargetConstant(1, MVT::i8),   // Scale
14031       DAG.getRegister(0, MVT::i32),        // Index
14032       DAG.getTargetConstant(0, MVT::i32),  // Disp
14033       DAG.getRegister(0, MVT::i32),        // Segment.
14034       Zero,
14035       Chain
14036     };
14037     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14038     return SDValue(Res, 0);
14039   }
14040
14041   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14042   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14043 }
14044
14045 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14046                              SelectionDAG &DAG) {
14047   MVT T = Op.getSimpleValueType();
14048   SDLoc DL(Op);
14049   unsigned Reg = 0;
14050   unsigned size = 0;
14051   switch(T.SimpleTy) {
14052   default: llvm_unreachable("Invalid value type!");
14053   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14054   case MVT::i16: Reg = X86::AX;  size = 2; break;
14055   case MVT::i32: Reg = X86::EAX; size = 4; break;
14056   case MVT::i64:
14057     assert(Subtarget->is64Bit() && "Node not type legal!");
14058     Reg = X86::RAX; size = 8;
14059     break;
14060   }
14061   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14062                                     Op.getOperand(2), SDValue());
14063   SDValue Ops[] = { cpIn.getValue(0),
14064                     Op.getOperand(1),
14065                     Op.getOperand(3),
14066                     DAG.getTargetConstant(size, MVT::i8),
14067                     cpIn.getValue(1) };
14068   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14069   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14070   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14071                                            Ops, T, MMO);
14072   SDValue cpOut =
14073     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14074   return cpOut;
14075 }
14076
14077 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14078                             SelectionDAG &DAG) {
14079   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14080   MVT DstVT = Op.getSimpleValueType();
14081   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14082          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14083   assert((DstVT == MVT::i64 ||
14084           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14085          "Unexpected custom BITCAST");
14086   // i64 <=> MMX conversions are Legal.
14087   if (SrcVT==MVT::i64 && DstVT.isVector())
14088     return Op;
14089   if (DstVT==MVT::i64 && SrcVT.isVector())
14090     return Op;
14091   // MMX <=> MMX conversions are Legal.
14092   if (SrcVT.isVector() && DstVT.isVector())
14093     return Op;
14094   // All other conversions need to be expanded.
14095   return SDValue();
14096 }
14097
14098 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14099   SDNode *Node = Op.getNode();
14100   SDLoc dl(Node);
14101   EVT T = Node->getValueType(0);
14102   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14103                               DAG.getConstant(0, T), Node->getOperand(2));
14104   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14105                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14106                        Node->getOperand(0),
14107                        Node->getOperand(1), negOp,
14108                        cast<AtomicSDNode>(Node)->getMemOperand(),
14109                        cast<AtomicSDNode>(Node)->getOrdering(),
14110                        cast<AtomicSDNode>(Node)->getSynchScope());
14111 }
14112
14113 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14114   SDNode *Node = Op.getNode();
14115   SDLoc dl(Node);
14116   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14117
14118   // Convert seq_cst store -> xchg
14119   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14120   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14121   //        (The only way to get a 16-byte store is cmpxchg16b)
14122   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14123   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14124       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14125     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14126                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14127                                  Node->getOperand(0),
14128                                  Node->getOperand(1), Node->getOperand(2),
14129                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14130                                  cast<AtomicSDNode>(Node)->getOrdering(),
14131                                  cast<AtomicSDNode>(Node)->getSynchScope());
14132     return Swap.getValue(1);
14133   }
14134   // Other atomic stores have a simple pattern.
14135   return Op;
14136 }
14137
14138 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14139   EVT VT = Op.getNode()->getSimpleValueType(0);
14140
14141   // Let legalize expand this if it isn't a legal type yet.
14142   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14143     return SDValue();
14144
14145   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14146
14147   unsigned Opc;
14148   bool ExtraOp = false;
14149   switch (Op.getOpcode()) {
14150   default: llvm_unreachable("Invalid code");
14151   case ISD::ADDC: Opc = X86ISD::ADD; break;
14152   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14153   case ISD::SUBC: Opc = X86ISD::SUB; break;
14154   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14155   }
14156
14157   if (!ExtraOp)
14158     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14159                        Op.getOperand(1));
14160   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14161                      Op.getOperand(1), Op.getOperand(2));
14162 }
14163
14164 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14165                             SelectionDAG &DAG) {
14166   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14167
14168   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14169   // which returns the values as { float, float } (in XMM0) or
14170   // { double, double } (which is returned in XMM0, XMM1).
14171   SDLoc dl(Op);
14172   SDValue Arg = Op.getOperand(0);
14173   EVT ArgVT = Arg.getValueType();
14174   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14175
14176   TargetLowering::ArgListTy Args;
14177   TargetLowering::ArgListEntry Entry;
14178
14179   Entry.Node = Arg;
14180   Entry.Ty = ArgTy;
14181   Entry.isSExt = false;
14182   Entry.isZExt = false;
14183   Args.push_back(Entry);
14184
14185   bool isF64 = ArgVT == MVT::f64;
14186   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14187   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14188   // the results are returned via SRet in memory.
14189   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14190   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14191   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14192
14193   Type *RetTy = isF64
14194     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14195     : (Type*)VectorType::get(ArgTy, 4);
14196   TargetLowering::
14197     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14198                          false, false, false, false, 0,
14199                          CallingConv::C, /*isTaillCall=*/false,
14200                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14201                          Callee, Args, DAG, dl);
14202   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14203
14204   if (isF64)
14205     // Returned in xmm0 and xmm1.
14206     return CallResult.first;
14207
14208   // Returned in bits 0:31 and 32:64 xmm0.
14209   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14210                                CallResult.first, DAG.getIntPtrConstant(0));
14211   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14212                                CallResult.first, DAG.getIntPtrConstant(1));
14213   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14214   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14215 }
14216
14217 /// LowerOperation - Provide custom lowering hooks for some operations.
14218 ///
14219 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14220   switch (Op.getOpcode()) {
14221   default: llvm_unreachable("Should not custom lower this!");
14222   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14223   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14224   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14225   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14226   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14227   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14228   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14229   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14230   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14231   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14232   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14233   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14234   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14235   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14236   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14237   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14238   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14239   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14240   case ISD::SHL_PARTS:
14241   case ISD::SRA_PARTS:
14242   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14243   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14244   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14245   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14246   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14247   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14248   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14249   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14250   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14251   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14252   case ISD::FABS:               return LowerFABS(Op, DAG);
14253   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14254   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14255   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14256   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14257   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14258   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14259   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14260   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14261   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14262   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14263   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14264   case ISD::INTRINSIC_VOID:
14265   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14266   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14267   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14268   case ISD::FRAME_TO_ARGS_OFFSET:
14269                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14270   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14271   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14272   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14273   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14274   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14275   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14276   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14277   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14278   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14279   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14280   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14281   case ISD::UMUL_LOHI:
14282   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14283   case ISD::SRA:
14284   case ISD::SRL:
14285   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14286   case ISD::SADDO:
14287   case ISD::UADDO:
14288   case ISD::SSUBO:
14289   case ISD::USUBO:
14290   case ISD::SMULO:
14291   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14292   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14293   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14294   case ISD::ADDC:
14295   case ISD::ADDE:
14296   case ISD::SUBC:
14297   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14298   case ISD::ADD:                return LowerADD(Op, DAG);
14299   case ISD::SUB:                return LowerSUB(Op, DAG);
14300   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14301   }
14302 }
14303
14304 static void ReplaceATOMIC_LOAD(SDNode *Node,
14305                                   SmallVectorImpl<SDValue> &Results,
14306                                   SelectionDAG &DAG) {
14307   SDLoc dl(Node);
14308   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14309
14310   // Convert wide load -> cmpxchg8b/cmpxchg16b
14311   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14312   //        (The only way to get a 16-byte load is cmpxchg16b)
14313   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14314   SDValue Zero = DAG.getConstant(0, VT);
14315   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14316                                Node->getOperand(0),
14317                                Node->getOperand(1), Zero, Zero,
14318                                cast<AtomicSDNode>(Node)->getMemOperand(),
14319                                cast<AtomicSDNode>(Node)->getOrdering(),
14320                                cast<AtomicSDNode>(Node)->getOrdering(),
14321                                cast<AtomicSDNode>(Node)->getSynchScope());
14322   Results.push_back(Swap.getValue(0));
14323   Results.push_back(Swap.getValue(1));
14324 }
14325
14326 static void
14327 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14328                         SelectionDAG &DAG, unsigned NewOp) {
14329   SDLoc dl(Node);
14330   assert (Node->getValueType(0) == MVT::i64 &&
14331           "Only know how to expand i64 atomics");
14332
14333   SDValue Chain = Node->getOperand(0);
14334   SDValue In1 = Node->getOperand(1);
14335   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14336                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14337   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14338                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14339   SDValue Ops[] = { Chain, In1, In2L, In2H };
14340   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14341   SDValue Result =
14342     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14343                             cast<MemSDNode>(Node)->getMemOperand());
14344   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14345   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14346   Results.push_back(Result.getValue(2));
14347 }
14348
14349 /// ReplaceNodeResults - Replace a node with an illegal result type
14350 /// with a new node built out of custom code.
14351 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14352                                            SmallVectorImpl<SDValue>&Results,
14353                                            SelectionDAG &DAG) const {
14354   SDLoc dl(N);
14355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14356   switch (N->getOpcode()) {
14357   default:
14358     llvm_unreachable("Do not know how to custom type legalize this operation!");
14359   case ISD::SIGN_EXTEND_INREG:
14360   case ISD::ADDC:
14361   case ISD::ADDE:
14362   case ISD::SUBC:
14363   case ISD::SUBE:
14364     // We don't want to expand or promote these.
14365     return;
14366   case ISD::SDIV:
14367   case ISD::UDIV:
14368   case ISD::SREM:
14369   case ISD::UREM:
14370   case ISD::SDIVREM:
14371   case ISD::UDIVREM: {
14372     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14373     Results.push_back(V);
14374     return;
14375   }
14376   case ISD::FP_TO_SINT:
14377   case ISD::FP_TO_UINT: {
14378     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14379
14380     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14381       return;
14382
14383     std::pair<SDValue,SDValue> Vals =
14384         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14385     SDValue FIST = Vals.first, StackSlot = Vals.second;
14386     if (FIST.getNode()) {
14387       EVT VT = N->getValueType(0);
14388       // Return a load from the stack slot.
14389       if (StackSlot.getNode())
14390         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14391                                       MachinePointerInfo(),
14392                                       false, false, false, 0));
14393       else
14394         Results.push_back(FIST);
14395     }
14396     return;
14397   }
14398   case ISD::UINT_TO_FP: {
14399     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14400     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14401         N->getValueType(0) != MVT::v2f32)
14402       return;
14403     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14404                                  N->getOperand(0));
14405     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14406                                      MVT::f64);
14407     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14408     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14409                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14410     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14411     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14412     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14413     return;
14414   }
14415   case ISD::FP_ROUND: {
14416     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14417         return;
14418     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14419     Results.push_back(V);
14420     return;
14421   }
14422   case ISD::INTRINSIC_W_CHAIN: {
14423     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14424     switch (IntNo) {
14425     default : llvm_unreachable("Do not know how to custom type "
14426                                "legalize this intrinsic operation!");
14427     case Intrinsic::x86_rdtsc:
14428       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14429                                      Results);
14430     case Intrinsic::x86_rdtscp:
14431       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14432                                      Results);
14433     }
14434   }
14435   case ISD::READCYCLECOUNTER: {
14436     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14437                                    Results);
14438   }
14439   case ISD::ATOMIC_CMP_SWAP: {
14440     EVT T = N->getValueType(0);
14441     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14442     bool Regs64bit = T == MVT::i128;
14443     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14444     SDValue cpInL, cpInH;
14445     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14446                         DAG.getConstant(0, HalfT));
14447     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14448                         DAG.getConstant(1, HalfT));
14449     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14450                              Regs64bit ? X86::RAX : X86::EAX,
14451                              cpInL, SDValue());
14452     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14453                              Regs64bit ? X86::RDX : X86::EDX,
14454                              cpInH, cpInL.getValue(1));
14455     SDValue swapInL, swapInH;
14456     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14457                           DAG.getConstant(0, HalfT));
14458     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14459                           DAG.getConstant(1, HalfT));
14460     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14461                                Regs64bit ? X86::RBX : X86::EBX,
14462                                swapInL, cpInH.getValue(1));
14463     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14464                                Regs64bit ? X86::RCX : X86::ECX,
14465                                swapInH, swapInL.getValue(1));
14466     SDValue Ops[] = { swapInH.getValue(0),
14467                       N->getOperand(1),
14468                       swapInH.getValue(1) };
14469     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14470     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14471     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14472                                   X86ISD::LCMPXCHG8_DAG;
14473     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14474     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14475                                         Regs64bit ? X86::RAX : X86::EAX,
14476                                         HalfT, Result.getValue(1));
14477     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14478                                         Regs64bit ? X86::RDX : X86::EDX,
14479                                         HalfT, cpOutL.getValue(2));
14480     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14481     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14482     Results.push_back(cpOutH.getValue(1));
14483     return;
14484   }
14485   case ISD::ATOMIC_LOAD_ADD:
14486   case ISD::ATOMIC_LOAD_AND:
14487   case ISD::ATOMIC_LOAD_NAND:
14488   case ISD::ATOMIC_LOAD_OR:
14489   case ISD::ATOMIC_LOAD_SUB:
14490   case ISD::ATOMIC_LOAD_XOR:
14491   case ISD::ATOMIC_LOAD_MAX:
14492   case ISD::ATOMIC_LOAD_MIN:
14493   case ISD::ATOMIC_LOAD_UMAX:
14494   case ISD::ATOMIC_LOAD_UMIN:
14495   case ISD::ATOMIC_SWAP: {
14496     unsigned Opc;
14497     switch (N->getOpcode()) {
14498     default: llvm_unreachable("Unexpected opcode");
14499     case ISD::ATOMIC_LOAD_ADD:
14500       Opc = X86ISD::ATOMADD64_DAG;
14501       break;
14502     case ISD::ATOMIC_LOAD_AND:
14503       Opc = X86ISD::ATOMAND64_DAG;
14504       break;
14505     case ISD::ATOMIC_LOAD_NAND:
14506       Opc = X86ISD::ATOMNAND64_DAG;
14507       break;
14508     case ISD::ATOMIC_LOAD_OR:
14509       Opc = X86ISD::ATOMOR64_DAG;
14510       break;
14511     case ISD::ATOMIC_LOAD_SUB:
14512       Opc = X86ISD::ATOMSUB64_DAG;
14513       break;
14514     case ISD::ATOMIC_LOAD_XOR:
14515       Opc = X86ISD::ATOMXOR64_DAG;
14516       break;
14517     case ISD::ATOMIC_LOAD_MAX:
14518       Opc = X86ISD::ATOMMAX64_DAG;
14519       break;
14520     case ISD::ATOMIC_LOAD_MIN:
14521       Opc = X86ISD::ATOMMIN64_DAG;
14522       break;
14523     case ISD::ATOMIC_LOAD_UMAX:
14524       Opc = X86ISD::ATOMUMAX64_DAG;
14525       break;
14526     case ISD::ATOMIC_LOAD_UMIN:
14527       Opc = X86ISD::ATOMUMIN64_DAG;
14528       break;
14529     case ISD::ATOMIC_SWAP:
14530       Opc = X86ISD::ATOMSWAP64_DAG;
14531       break;
14532     }
14533     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14534     return;
14535   }
14536   case ISD::ATOMIC_LOAD:
14537     ReplaceATOMIC_LOAD(N, Results, DAG);
14538   }
14539 }
14540
14541 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14542   switch (Opcode) {
14543   default: return nullptr;
14544   case X86ISD::BSF:                return "X86ISD::BSF";
14545   case X86ISD::BSR:                return "X86ISD::BSR";
14546   case X86ISD::SHLD:               return "X86ISD::SHLD";
14547   case X86ISD::SHRD:               return "X86ISD::SHRD";
14548   case X86ISD::FAND:               return "X86ISD::FAND";
14549   case X86ISD::FANDN:              return "X86ISD::FANDN";
14550   case X86ISD::FOR:                return "X86ISD::FOR";
14551   case X86ISD::FXOR:               return "X86ISD::FXOR";
14552   case X86ISD::FSRL:               return "X86ISD::FSRL";
14553   case X86ISD::FILD:               return "X86ISD::FILD";
14554   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14555   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14556   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14557   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14558   case X86ISD::FLD:                return "X86ISD::FLD";
14559   case X86ISD::FST:                return "X86ISD::FST";
14560   case X86ISD::CALL:               return "X86ISD::CALL";
14561   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14562   case X86ISD::BT:                 return "X86ISD::BT";
14563   case X86ISD::CMP:                return "X86ISD::CMP";
14564   case X86ISD::COMI:               return "X86ISD::COMI";
14565   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14566   case X86ISD::CMPM:               return "X86ISD::CMPM";
14567   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14568   case X86ISD::SETCC:              return "X86ISD::SETCC";
14569   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14570   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14571   case X86ISD::CMOV:               return "X86ISD::CMOV";
14572   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14573   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14574   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14575   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14576   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14577   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14578   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14579   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14580   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14581   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14582   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14583   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14584   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14585   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14586   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14587   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14588   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14589   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14590   case X86ISD::HADD:               return "X86ISD::HADD";
14591   case X86ISD::HSUB:               return "X86ISD::HSUB";
14592   case X86ISD::FHADD:              return "X86ISD::FHADD";
14593   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14594   case X86ISD::UMAX:               return "X86ISD::UMAX";
14595   case X86ISD::UMIN:               return "X86ISD::UMIN";
14596   case X86ISD::SMAX:               return "X86ISD::SMAX";
14597   case X86ISD::SMIN:               return "X86ISD::SMIN";
14598   case X86ISD::FMAX:               return "X86ISD::FMAX";
14599   case X86ISD::FMIN:               return "X86ISD::FMIN";
14600   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14601   case X86ISD::FMINC:              return "X86ISD::FMINC";
14602   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14603   case X86ISD::FRCP:               return "X86ISD::FRCP";
14604   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14605   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14606   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14607   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14608   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14609   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14610   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14611   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14612   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14613   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14614   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14615   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14616   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14617   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14618   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14619   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14620   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14621   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14622   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14623   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14624   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14625   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14626   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14627   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14628   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14629   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14630   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14631   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14632   case X86ISD::VSHL:               return "X86ISD::VSHL";
14633   case X86ISD::VSRL:               return "X86ISD::VSRL";
14634   case X86ISD::VSRA:               return "X86ISD::VSRA";
14635   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14636   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14637   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14638   case X86ISD::CMPP:               return "X86ISD::CMPP";
14639   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14640   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14641   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14642   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14643   case X86ISD::ADD:                return "X86ISD::ADD";
14644   case X86ISD::SUB:                return "X86ISD::SUB";
14645   case X86ISD::ADC:                return "X86ISD::ADC";
14646   case X86ISD::SBB:                return "X86ISD::SBB";
14647   case X86ISD::SMUL:               return "X86ISD::SMUL";
14648   case X86ISD::UMUL:               return "X86ISD::UMUL";
14649   case X86ISD::INC:                return "X86ISD::INC";
14650   case X86ISD::DEC:                return "X86ISD::DEC";
14651   case X86ISD::OR:                 return "X86ISD::OR";
14652   case X86ISD::XOR:                return "X86ISD::XOR";
14653   case X86ISD::AND:                return "X86ISD::AND";
14654   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14655   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14656   case X86ISD::PTEST:              return "X86ISD::PTEST";
14657   case X86ISD::TESTP:              return "X86ISD::TESTP";
14658   case X86ISD::TESTM:              return "X86ISD::TESTM";
14659   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14660   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14661   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14662   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14663   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14664   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14665   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14666   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14667   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14668   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14669   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14670   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14671   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14672   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14673   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14674   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14675   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14676   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14677   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14678   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14679   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14680   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14681   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14682   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14683   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14684   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14685   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14686   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14687   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14688   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14689   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14690   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14691   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14692   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14693   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14694   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14695   case X86ISD::SAHF:               return "X86ISD::SAHF";
14696   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14697   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14698   case X86ISD::FMADD:              return "X86ISD::FMADD";
14699   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14700   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14701   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14702   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14703   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14704   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14705   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14706   case X86ISD::XTEST:              return "X86ISD::XTEST";
14707   }
14708 }
14709
14710 // isLegalAddressingMode - Return true if the addressing mode represented
14711 // by AM is legal for this target, for a load/store of the specified type.
14712 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14713                                               Type *Ty) const {
14714   // X86 supports extremely general addressing modes.
14715   CodeModel::Model M = getTargetMachine().getCodeModel();
14716   Reloc::Model R = getTargetMachine().getRelocationModel();
14717
14718   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14719   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14720     return false;
14721
14722   if (AM.BaseGV) {
14723     unsigned GVFlags =
14724       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14725
14726     // If a reference to this global requires an extra load, we can't fold it.
14727     if (isGlobalStubReference(GVFlags))
14728       return false;
14729
14730     // If BaseGV requires a register for the PIC base, we cannot also have a
14731     // BaseReg specified.
14732     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14733       return false;
14734
14735     // If lower 4G is not available, then we must use rip-relative addressing.
14736     if ((M != CodeModel::Small || R != Reloc::Static) &&
14737         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14738       return false;
14739   }
14740
14741   switch (AM.Scale) {
14742   case 0:
14743   case 1:
14744   case 2:
14745   case 4:
14746   case 8:
14747     // These scales always work.
14748     break;
14749   case 3:
14750   case 5:
14751   case 9:
14752     // These scales are formed with basereg+scalereg.  Only accept if there is
14753     // no basereg yet.
14754     if (AM.HasBaseReg)
14755       return false;
14756     break;
14757   default:  // Other stuff never works.
14758     return false;
14759   }
14760
14761   return true;
14762 }
14763
14764 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14765   unsigned Bits = Ty->getScalarSizeInBits();
14766
14767   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14768   // particularly cheaper than those without.
14769   if (Bits == 8)
14770     return false;
14771
14772   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14773   // variable shifts just as cheap as scalar ones.
14774   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14775     return false;
14776
14777   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14778   // fully general vector.
14779   return true;
14780 }
14781
14782 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14783   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14784     return false;
14785   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14786   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14787   return NumBits1 > NumBits2;
14788 }
14789
14790 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14791   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14792     return false;
14793
14794   if (!isTypeLegal(EVT::getEVT(Ty1)))
14795     return false;
14796
14797   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14798
14799   // Assuming the caller doesn't have a zeroext or signext return parameter,
14800   // truncation all the way down to i1 is valid.
14801   return true;
14802 }
14803
14804 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14805   return isInt<32>(Imm);
14806 }
14807
14808 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14809   // Can also use sub to handle negated immediates.
14810   return isInt<32>(Imm);
14811 }
14812
14813 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14814   if (!VT1.isInteger() || !VT2.isInteger())
14815     return false;
14816   unsigned NumBits1 = VT1.getSizeInBits();
14817   unsigned NumBits2 = VT2.getSizeInBits();
14818   return NumBits1 > NumBits2;
14819 }
14820
14821 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14822   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14823   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14824 }
14825
14826 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14827   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14828   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14829 }
14830
14831 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14832   EVT VT1 = Val.getValueType();
14833   if (isZExtFree(VT1, VT2))
14834     return true;
14835
14836   if (Val.getOpcode() != ISD::LOAD)
14837     return false;
14838
14839   if (!VT1.isSimple() || !VT1.isInteger() ||
14840       !VT2.isSimple() || !VT2.isInteger())
14841     return false;
14842
14843   switch (VT1.getSimpleVT().SimpleTy) {
14844   default: break;
14845   case MVT::i8:
14846   case MVT::i16:
14847   case MVT::i32:
14848     // X86 has 8, 16, and 32-bit zero-extending loads.
14849     return true;
14850   }
14851
14852   return false;
14853 }
14854
14855 bool
14856 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14857   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14858     return false;
14859
14860   VT = VT.getScalarType();
14861
14862   if (!VT.isSimple())
14863     return false;
14864
14865   switch (VT.getSimpleVT().SimpleTy) {
14866   case MVT::f32:
14867   case MVT::f64:
14868     return true;
14869   default:
14870     break;
14871   }
14872
14873   return false;
14874 }
14875
14876 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14877   // i16 instructions are longer (0x66 prefix) and potentially slower.
14878   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14879 }
14880
14881 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14882 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14883 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14884 /// are assumed to be legal.
14885 bool
14886 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14887                                       EVT VT) const {
14888   if (!VT.isSimple())
14889     return false;
14890
14891   MVT SVT = VT.getSimpleVT();
14892
14893   // Very little shuffling can be done for 64-bit vectors right now.
14894   if (VT.getSizeInBits() == 64)
14895     return false;
14896
14897   // FIXME: pshufb, blends, shifts.
14898   return (SVT.getVectorNumElements() == 2 ||
14899           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14900           isMOVLMask(M, SVT) ||
14901           isSHUFPMask(M, SVT) ||
14902           isPSHUFDMask(M, SVT) ||
14903           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14904           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14905           isPALIGNRMask(M, SVT, Subtarget) ||
14906           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14907           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14908           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14909           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14910 }
14911
14912 bool
14913 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14914                                           EVT VT) const {
14915   if (!VT.isSimple())
14916     return false;
14917
14918   MVT SVT = VT.getSimpleVT();
14919   unsigned NumElts = SVT.getVectorNumElements();
14920   // FIXME: This collection of masks seems suspect.
14921   if (NumElts == 2)
14922     return true;
14923   if (NumElts == 4 && SVT.is128BitVector()) {
14924     return (isMOVLMask(Mask, SVT)  ||
14925             isCommutedMOVLMask(Mask, SVT, true) ||
14926             isSHUFPMask(Mask, SVT) ||
14927             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14928   }
14929   return false;
14930 }
14931
14932 //===----------------------------------------------------------------------===//
14933 //                           X86 Scheduler Hooks
14934 //===----------------------------------------------------------------------===//
14935
14936 /// Utility function to emit xbegin specifying the start of an RTM region.
14937 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14938                                      const TargetInstrInfo *TII) {
14939   DebugLoc DL = MI->getDebugLoc();
14940
14941   const BasicBlock *BB = MBB->getBasicBlock();
14942   MachineFunction::iterator I = MBB;
14943   ++I;
14944
14945   // For the v = xbegin(), we generate
14946   //
14947   // thisMBB:
14948   //  xbegin sinkMBB
14949   //
14950   // mainMBB:
14951   //  eax = -1
14952   //
14953   // sinkMBB:
14954   //  v = eax
14955
14956   MachineBasicBlock *thisMBB = MBB;
14957   MachineFunction *MF = MBB->getParent();
14958   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14959   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14960   MF->insert(I, mainMBB);
14961   MF->insert(I, sinkMBB);
14962
14963   // Transfer the remainder of BB and its successor edges to sinkMBB.
14964   sinkMBB->splice(sinkMBB->begin(), MBB,
14965                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14966   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14967
14968   // thisMBB:
14969   //  xbegin sinkMBB
14970   //  # fallthrough to mainMBB
14971   //  # abortion to sinkMBB
14972   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14973   thisMBB->addSuccessor(mainMBB);
14974   thisMBB->addSuccessor(sinkMBB);
14975
14976   // mainMBB:
14977   //  EAX = -1
14978   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14979   mainMBB->addSuccessor(sinkMBB);
14980
14981   // sinkMBB:
14982   // EAX is live into the sinkMBB
14983   sinkMBB->addLiveIn(X86::EAX);
14984   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14985           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14986     .addReg(X86::EAX);
14987
14988   MI->eraseFromParent();
14989   return sinkMBB;
14990 }
14991
14992 // Get CMPXCHG opcode for the specified data type.
14993 static unsigned getCmpXChgOpcode(EVT VT) {
14994   switch (VT.getSimpleVT().SimpleTy) {
14995   case MVT::i8:  return X86::LCMPXCHG8;
14996   case MVT::i16: return X86::LCMPXCHG16;
14997   case MVT::i32: return X86::LCMPXCHG32;
14998   case MVT::i64: return X86::LCMPXCHG64;
14999   default:
15000     break;
15001   }
15002   llvm_unreachable("Invalid operand size!");
15003 }
15004
15005 // Get LOAD opcode for the specified data type.
15006 static unsigned getLoadOpcode(EVT VT) {
15007   switch (VT.getSimpleVT().SimpleTy) {
15008   case MVT::i8:  return X86::MOV8rm;
15009   case MVT::i16: return X86::MOV16rm;
15010   case MVT::i32: return X86::MOV32rm;
15011   case MVT::i64: return X86::MOV64rm;
15012   default:
15013     break;
15014   }
15015   llvm_unreachable("Invalid operand size!");
15016 }
15017
15018 // Get opcode of the non-atomic one from the specified atomic instruction.
15019 static unsigned getNonAtomicOpcode(unsigned Opc) {
15020   switch (Opc) {
15021   case X86::ATOMAND8:  return X86::AND8rr;
15022   case X86::ATOMAND16: return X86::AND16rr;
15023   case X86::ATOMAND32: return X86::AND32rr;
15024   case X86::ATOMAND64: return X86::AND64rr;
15025   case X86::ATOMOR8:   return X86::OR8rr;
15026   case X86::ATOMOR16:  return X86::OR16rr;
15027   case X86::ATOMOR32:  return X86::OR32rr;
15028   case X86::ATOMOR64:  return X86::OR64rr;
15029   case X86::ATOMXOR8:  return X86::XOR8rr;
15030   case X86::ATOMXOR16: return X86::XOR16rr;
15031   case X86::ATOMXOR32: return X86::XOR32rr;
15032   case X86::ATOMXOR64: return X86::XOR64rr;
15033   }
15034   llvm_unreachable("Unhandled atomic-load-op opcode!");
15035 }
15036
15037 // Get opcode of the non-atomic one from the specified atomic instruction with
15038 // extra opcode.
15039 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15040                                                unsigned &ExtraOpc) {
15041   switch (Opc) {
15042   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15043   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15044   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15045   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15046   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15047   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15048   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15049   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15050   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15051   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15052   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15053   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15054   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15055   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15056   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15057   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15058   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15059   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15060   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15061   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15062   }
15063   llvm_unreachable("Unhandled atomic-load-op opcode!");
15064 }
15065
15066 // Get opcode of the non-atomic one from the specified atomic instruction for
15067 // 64-bit data type on 32-bit target.
15068 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15069   switch (Opc) {
15070   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15071   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15072   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15073   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15074   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15075   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15076   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15077   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15078   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15079   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15080   }
15081   llvm_unreachable("Unhandled atomic-load-op opcode!");
15082 }
15083
15084 // Get opcode of the non-atomic one from the specified atomic instruction for
15085 // 64-bit data type on 32-bit target with extra opcode.
15086 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15087                                                    unsigned &HiOpc,
15088                                                    unsigned &ExtraOpc) {
15089   switch (Opc) {
15090   case X86::ATOMNAND6432:
15091     ExtraOpc = X86::NOT32r;
15092     HiOpc = X86::AND32rr;
15093     return X86::AND32rr;
15094   }
15095   llvm_unreachable("Unhandled atomic-load-op opcode!");
15096 }
15097
15098 // Get pseudo CMOV opcode from the specified data type.
15099 static unsigned getPseudoCMOVOpc(EVT VT) {
15100   switch (VT.getSimpleVT().SimpleTy) {
15101   case MVT::i8:  return X86::CMOV_GR8;
15102   case MVT::i16: return X86::CMOV_GR16;
15103   case MVT::i32: return X86::CMOV_GR32;
15104   default:
15105     break;
15106   }
15107   llvm_unreachable("Unknown CMOV opcode!");
15108 }
15109
15110 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15111 // They will be translated into a spin-loop or compare-exchange loop from
15112 //
15113 //    ...
15114 //    dst = atomic-fetch-op MI.addr, MI.val
15115 //    ...
15116 //
15117 // to
15118 //
15119 //    ...
15120 //    t1 = LOAD MI.addr
15121 // loop:
15122 //    t4 = phi(t1, t3 / loop)
15123 //    t2 = OP MI.val, t4
15124 //    EAX = t4
15125 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15126 //    t3 = EAX
15127 //    JNE loop
15128 // sink:
15129 //    dst = t3
15130 //    ...
15131 MachineBasicBlock *
15132 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15133                                        MachineBasicBlock *MBB) const {
15134   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15135   DebugLoc DL = MI->getDebugLoc();
15136
15137   MachineFunction *MF = MBB->getParent();
15138   MachineRegisterInfo &MRI = MF->getRegInfo();
15139
15140   const BasicBlock *BB = MBB->getBasicBlock();
15141   MachineFunction::iterator I = MBB;
15142   ++I;
15143
15144   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15145          "Unexpected number of operands");
15146
15147   assert(MI->hasOneMemOperand() &&
15148          "Expected atomic-load-op to have one memoperand");
15149
15150   // Memory Reference
15151   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15152   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15153
15154   unsigned DstReg, SrcReg;
15155   unsigned MemOpndSlot;
15156
15157   unsigned CurOp = 0;
15158
15159   DstReg = MI->getOperand(CurOp++).getReg();
15160   MemOpndSlot = CurOp;
15161   CurOp += X86::AddrNumOperands;
15162   SrcReg = MI->getOperand(CurOp++).getReg();
15163
15164   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15165   MVT::SimpleValueType VT = *RC->vt_begin();
15166   unsigned t1 = MRI.createVirtualRegister(RC);
15167   unsigned t2 = MRI.createVirtualRegister(RC);
15168   unsigned t3 = MRI.createVirtualRegister(RC);
15169   unsigned t4 = MRI.createVirtualRegister(RC);
15170   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15171
15172   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15173   unsigned LOADOpc = getLoadOpcode(VT);
15174
15175   // For the atomic load-arith operator, we generate
15176   //
15177   //  thisMBB:
15178   //    t1 = LOAD [MI.addr]
15179   //  mainMBB:
15180   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15181   //    t1 = OP MI.val, EAX
15182   //    EAX = t4
15183   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15184   //    t3 = EAX
15185   //    JNE mainMBB
15186   //  sinkMBB:
15187   //    dst = t3
15188
15189   MachineBasicBlock *thisMBB = MBB;
15190   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15191   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15192   MF->insert(I, mainMBB);
15193   MF->insert(I, sinkMBB);
15194
15195   MachineInstrBuilder MIB;
15196
15197   // Transfer the remainder of BB and its successor edges to sinkMBB.
15198   sinkMBB->splice(sinkMBB->begin(), MBB,
15199                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15200   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15201
15202   // thisMBB:
15203   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15204   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15205     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15206     if (NewMO.isReg())
15207       NewMO.setIsKill(false);
15208     MIB.addOperand(NewMO);
15209   }
15210   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15211     unsigned flags = (*MMOI)->getFlags();
15212     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15213     MachineMemOperand *MMO =
15214       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15215                                (*MMOI)->getSize(),
15216                                (*MMOI)->getBaseAlignment(),
15217                                (*MMOI)->getTBAAInfo(),
15218                                (*MMOI)->getRanges());
15219     MIB.addMemOperand(MMO);
15220   }
15221
15222   thisMBB->addSuccessor(mainMBB);
15223
15224   // mainMBB:
15225   MachineBasicBlock *origMainMBB = mainMBB;
15226
15227   // Add a PHI.
15228   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15229                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15230
15231   unsigned Opc = MI->getOpcode();
15232   switch (Opc) {
15233   default:
15234     llvm_unreachable("Unhandled atomic-load-op opcode!");
15235   case X86::ATOMAND8:
15236   case X86::ATOMAND16:
15237   case X86::ATOMAND32:
15238   case X86::ATOMAND64:
15239   case X86::ATOMOR8:
15240   case X86::ATOMOR16:
15241   case X86::ATOMOR32:
15242   case X86::ATOMOR64:
15243   case X86::ATOMXOR8:
15244   case X86::ATOMXOR16:
15245   case X86::ATOMXOR32:
15246   case X86::ATOMXOR64: {
15247     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15248     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15249       .addReg(t4);
15250     break;
15251   }
15252   case X86::ATOMNAND8:
15253   case X86::ATOMNAND16:
15254   case X86::ATOMNAND32:
15255   case X86::ATOMNAND64: {
15256     unsigned Tmp = MRI.createVirtualRegister(RC);
15257     unsigned NOTOpc;
15258     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15259     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15260       .addReg(t4);
15261     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15262     break;
15263   }
15264   case X86::ATOMMAX8:
15265   case X86::ATOMMAX16:
15266   case X86::ATOMMAX32:
15267   case X86::ATOMMAX64:
15268   case X86::ATOMMIN8:
15269   case X86::ATOMMIN16:
15270   case X86::ATOMMIN32:
15271   case X86::ATOMMIN64:
15272   case X86::ATOMUMAX8:
15273   case X86::ATOMUMAX16:
15274   case X86::ATOMUMAX32:
15275   case X86::ATOMUMAX64:
15276   case X86::ATOMUMIN8:
15277   case X86::ATOMUMIN16:
15278   case X86::ATOMUMIN32:
15279   case X86::ATOMUMIN64: {
15280     unsigned CMPOpc;
15281     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15282
15283     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15284       .addReg(SrcReg)
15285       .addReg(t4);
15286
15287     if (Subtarget->hasCMov()) {
15288       if (VT != MVT::i8) {
15289         // Native support
15290         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15291           .addReg(SrcReg)
15292           .addReg(t4);
15293       } else {
15294         // Promote i8 to i32 to use CMOV32
15295         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15296         const TargetRegisterClass *RC32 =
15297           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15298         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15299         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15300         unsigned Tmp = MRI.createVirtualRegister(RC32);
15301
15302         unsigned Undef = MRI.createVirtualRegister(RC32);
15303         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15304
15305         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15306           .addReg(Undef)
15307           .addReg(SrcReg)
15308           .addImm(X86::sub_8bit);
15309         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15310           .addReg(Undef)
15311           .addReg(t4)
15312           .addImm(X86::sub_8bit);
15313
15314         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15315           .addReg(SrcReg32)
15316           .addReg(AccReg32);
15317
15318         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15319           .addReg(Tmp, 0, X86::sub_8bit);
15320       }
15321     } else {
15322       // Use pseudo select and lower them.
15323       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15324              "Invalid atomic-load-op transformation!");
15325       unsigned SelOpc = getPseudoCMOVOpc(VT);
15326       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15327       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15328       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15329               .addReg(SrcReg).addReg(t4)
15330               .addImm(CC);
15331       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15332       // Replace the original PHI node as mainMBB is changed after CMOV
15333       // lowering.
15334       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15335         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15336       Phi->eraseFromParent();
15337     }
15338     break;
15339   }
15340   }
15341
15342   // Copy PhyReg back from virtual register.
15343   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15344     .addReg(t4);
15345
15346   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15347   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15348     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15349     if (NewMO.isReg())
15350       NewMO.setIsKill(false);
15351     MIB.addOperand(NewMO);
15352   }
15353   MIB.addReg(t2);
15354   MIB.setMemRefs(MMOBegin, MMOEnd);
15355
15356   // Copy PhyReg back to virtual register.
15357   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15358     .addReg(PhyReg);
15359
15360   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15361
15362   mainMBB->addSuccessor(origMainMBB);
15363   mainMBB->addSuccessor(sinkMBB);
15364
15365   // sinkMBB:
15366   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15367           TII->get(TargetOpcode::COPY), DstReg)
15368     .addReg(t3);
15369
15370   MI->eraseFromParent();
15371   return sinkMBB;
15372 }
15373
15374 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15375 // instructions. They will be translated into a spin-loop or compare-exchange
15376 // loop from
15377 //
15378 //    ...
15379 //    dst = atomic-fetch-op MI.addr, MI.val
15380 //    ...
15381 //
15382 // to
15383 //
15384 //    ...
15385 //    t1L = LOAD [MI.addr + 0]
15386 //    t1H = LOAD [MI.addr + 4]
15387 // loop:
15388 //    t4L = phi(t1L, t3L / loop)
15389 //    t4H = phi(t1H, t3H / loop)
15390 //    t2L = OP MI.val.lo, t4L
15391 //    t2H = OP MI.val.hi, t4H
15392 //    EAX = t4L
15393 //    EDX = t4H
15394 //    EBX = t2L
15395 //    ECX = t2H
15396 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15397 //    t3L = EAX
15398 //    t3H = EDX
15399 //    JNE loop
15400 // sink:
15401 //    dstL = t3L
15402 //    dstH = t3H
15403 //    ...
15404 MachineBasicBlock *
15405 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15406                                            MachineBasicBlock *MBB) const {
15407   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15408   DebugLoc DL = MI->getDebugLoc();
15409
15410   MachineFunction *MF = MBB->getParent();
15411   MachineRegisterInfo &MRI = MF->getRegInfo();
15412
15413   const BasicBlock *BB = MBB->getBasicBlock();
15414   MachineFunction::iterator I = MBB;
15415   ++I;
15416
15417   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15418          "Unexpected number of operands");
15419
15420   assert(MI->hasOneMemOperand() &&
15421          "Expected atomic-load-op32 to have one memoperand");
15422
15423   // Memory Reference
15424   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15425   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15426
15427   unsigned DstLoReg, DstHiReg;
15428   unsigned SrcLoReg, SrcHiReg;
15429   unsigned MemOpndSlot;
15430
15431   unsigned CurOp = 0;
15432
15433   DstLoReg = MI->getOperand(CurOp++).getReg();
15434   DstHiReg = MI->getOperand(CurOp++).getReg();
15435   MemOpndSlot = CurOp;
15436   CurOp += X86::AddrNumOperands;
15437   SrcLoReg = MI->getOperand(CurOp++).getReg();
15438   SrcHiReg = MI->getOperand(CurOp++).getReg();
15439
15440   const TargetRegisterClass *RC = &X86::GR32RegClass;
15441   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15442
15443   unsigned t1L = MRI.createVirtualRegister(RC);
15444   unsigned t1H = MRI.createVirtualRegister(RC);
15445   unsigned t2L = MRI.createVirtualRegister(RC);
15446   unsigned t2H = MRI.createVirtualRegister(RC);
15447   unsigned t3L = MRI.createVirtualRegister(RC);
15448   unsigned t3H = MRI.createVirtualRegister(RC);
15449   unsigned t4L = MRI.createVirtualRegister(RC);
15450   unsigned t4H = MRI.createVirtualRegister(RC);
15451
15452   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15453   unsigned LOADOpc = X86::MOV32rm;
15454
15455   // For the atomic load-arith operator, we generate
15456   //
15457   //  thisMBB:
15458   //    t1L = LOAD [MI.addr + 0]
15459   //    t1H = LOAD [MI.addr + 4]
15460   //  mainMBB:
15461   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15462   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15463   //    t2L = OP MI.val.lo, t4L
15464   //    t2H = OP MI.val.hi, t4H
15465   //    EBX = t2L
15466   //    ECX = t2H
15467   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15468   //    t3L = EAX
15469   //    t3H = EDX
15470   //    JNE loop
15471   //  sinkMBB:
15472   //    dstL = t3L
15473   //    dstH = t3H
15474
15475   MachineBasicBlock *thisMBB = MBB;
15476   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15477   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15478   MF->insert(I, mainMBB);
15479   MF->insert(I, sinkMBB);
15480
15481   MachineInstrBuilder MIB;
15482
15483   // Transfer the remainder of BB and its successor edges to sinkMBB.
15484   sinkMBB->splice(sinkMBB->begin(), MBB,
15485                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15486   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15487
15488   // thisMBB:
15489   // Lo
15490   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15491   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15492     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15493     if (NewMO.isReg())
15494       NewMO.setIsKill(false);
15495     MIB.addOperand(NewMO);
15496   }
15497   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15498     unsigned flags = (*MMOI)->getFlags();
15499     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15500     MachineMemOperand *MMO =
15501       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15502                                (*MMOI)->getSize(),
15503                                (*MMOI)->getBaseAlignment(),
15504                                (*MMOI)->getTBAAInfo(),
15505                                (*MMOI)->getRanges());
15506     MIB.addMemOperand(MMO);
15507   };
15508   MachineInstr *LowMI = MIB;
15509
15510   // Hi
15511   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15512   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15513     if (i == X86::AddrDisp) {
15514       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15515     } else {
15516       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15517       if (NewMO.isReg())
15518         NewMO.setIsKill(false);
15519       MIB.addOperand(NewMO);
15520     }
15521   }
15522   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15523
15524   thisMBB->addSuccessor(mainMBB);
15525
15526   // mainMBB:
15527   MachineBasicBlock *origMainMBB = mainMBB;
15528
15529   // Add PHIs.
15530   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15531                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15532   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15533                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15534
15535   unsigned Opc = MI->getOpcode();
15536   switch (Opc) {
15537   default:
15538     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15539   case X86::ATOMAND6432:
15540   case X86::ATOMOR6432:
15541   case X86::ATOMXOR6432:
15542   case X86::ATOMADD6432:
15543   case X86::ATOMSUB6432: {
15544     unsigned HiOpc;
15545     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15546     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15547       .addReg(SrcLoReg);
15548     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15549       .addReg(SrcHiReg);
15550     break;
15551   }
15552   case X86::ATOMNAND6432: {
15553     unsigned HiOpc, NOTOpc;
15554     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15555     unsigned TmpL = MRI.createVirtualRegister(RC);
15556     unsigned TmpH = MRI.createVirtualRegister(RC);
15557     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15558       .addReg(t4L);
15559     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15560       .addReg(t4H);
15561     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15562     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15563     break;
15564   }
15565   case X86::ATOMMAX6432:
15566   case X86::ATOMMIN6432:
15567   case X86::ATOMUMAX6432:
15568   case X86::ATOMUMIN6432: {
15569     unsigned HiOpc;
15570     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15571     unsigned cL = MRI.createVirtualRegister(RC8);
15572     unsigned cH = MRI.createVirtualRegister(RC8);
15573     unsigned cL32 = MRI.createVirtualRegister(RC);
15574     unsigned cH32 = MRI.createVirtualRegister(RC);
15575     unsigned cc = MRI.createVirtualRegister(RC);
15576     // cl := cmp src_lo, lo
15577     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15578       .addReg(SrcLoReg).addReg(t4L);
15579     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15580     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15581     // ch := cmp src_hi, hi
15582     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15583       .addReg(SrcHiReg).addReg(t4H);
15584     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15585     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15586     // cc := if (src_hi == hi) ? cl : ch;
15587     if (Subtarget->hasCMov()) {
15588       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15589         .addReg(cH32).addReg(cL32);
15590     } else {
15591       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15592               .addReg(cH32).addReg(cL32)
15593               .addImm(X86::COND_E);
15594       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15595     }
15596     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15597     if (Subtarget->hasCMov()) {
15598       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15599         .addReg(SrcLoReg).addReg(t4L);
15600       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15601         .addReg(SrcHiReg).addReg(t4H);
15602     } else {
15603       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15604               .addReg(SrcLoReg).addReg(t4L)
15605               .addImm(X86::COND_NE);
15606       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15607       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15608       // 2nd CMOV lowering.
15609       mainMBB->addLiveIn(X86::EFLAGS);
15610       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15611               .addReg(SrcHiReg).addReg(t4H)
15612               .addImm(X86::COND_NE);
15613       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15614       // Replace the original PHI node as mainMBB is changed after CMOV
15615       // lowering.
15616       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15617         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15618       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15619         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15620       PhiL->eraseFromParent();
15621       PhiH->eraseFromParent();
15622     }
15623     break;
15624   }
15625   case X86::ATOMSWAP6432: {
15626     unsigned HiOpc;
15627     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15628     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15629     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15630     break;
15631   }
15632   }
15633
15634   // Copy EDX:EAX back from HiReg:LoReg
15635   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15636   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15637   // Copy ECX:EBX from t1H:t1L
15638   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15639   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15640
15641   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15642   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15643     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15644     if (NewMO.isReg())
15645       NewMO.setIsKill(false);
15646     MIB.addOperand(NewMO);
15647   }
15648   MIB.setMemRefs(MMOBegin, MMOEnd);
15649
15650   // Copy EDX:EAX back to t3H:t3L
15651   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15652   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15653
15654   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15655
15656   mainMBB->addSuccessor(origMainMBB);
15657   mainMBB->addSuccessor(sinkMBB);
15658
15659   // sinkMBB:
15660   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15661           TII->get(TargetOpcode::COPY), DstLoReg)
15662     .addReg(t3L);
15663   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15664           TII->get(TargetOpcode::COPY), DstHiReg)
15665     .addReg(t3H);
15666
15667   MI->eraseFromParent();
15668   return sinkMBB;
15669 }
15670
15671 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15672 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15673 // in the .td file.
15674 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15675                                        const TargetInstrInfo *TII) {
15676   unsigned Opc;
15677   switch (MI->getOpcode()) {
15678   default: llvm_unreachable("illegal opcode!");
15679   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15680   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15681   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15682   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15683   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15684   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15685   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15686   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15687   }
15688
15689   DebugLoc dl = MI->getDebugLoc();
15690   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15691
15692   unsigned NumArgs = MI->getNumOperands();
15693   for (unsigned i = 1; i < NumArgs; ++i) {
15694     MachineOperand &Op = MI->getOperand(i);
15695     if (!(Op.isReg() && Op.isImplicit()))
15696       MIB.addOperand(Op);
15697   }
15698   if (MI->hasOneMemOperand())
15699     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15700
15701   BuildMI(*BB, MI, dl,
15702     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15703     .addReg(X86::XMM0);
15704
15705   MI->eraseFromParent();
15706   return BB;
15707 }
15708
15709 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15710 // defs in an instruction pattern
15711 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15712                                        const TargetInstrInfo *TII) {
15713   unsigned Opc;
15714   switch (MI->getOpcode()) {
15715   default: llvm_unreachable("illegal opcode!");
15716   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15717   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15718   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15719   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15720   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15721   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15722   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15723   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15724   }
15725
15726   DebugLoc dl = MI->getDebugLoc();
15727   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15728
15729   unsigned NumArgs = MI->getNumOperands(); // remove the results
15730   for (unsigned i = 1; i < NumArgs; ++i) {
15731     MachineOperand &Op = MI->getOperand(i);
15732     if (!(Op.isReg() && Op.isImplicit()))
15733       MIB.addOperand(Op);
15734   }
15735   if (MI->hasOneMemOperand())
15736     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15737
15738   BuildMI(*BB, MI, dl,
15739     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15740     .addReg(X86::ECX);
15741
15742   MI->eraseFromParent();
15743   return BB;
15744 }
15745
15746 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15747                                        const TargetInstrInfo *TII,
15748                                        const X86Subtarget* Subtarget) {
15749   DebugLoc dl = MI->getDebugLoc();
15750
15751   // Address into RAX/EAX, other two args into ECX, EDX.
15752   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15753   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15754   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15755   for (int i = 0; i < X86::AddrNumOperands; ++i)
15756     MIB.addOperand(MI->getOperand(i));
15757
15758   unsigned ValOps = X86::AddrNumOperands;
15759   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15760     .addReg(MI->getOperand(ValOps).getReg());
15761   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15762     .addReg(MI->getOperand(ValOps+1).getReg());
15763
15764   // The instruction doesn't actually take any operands though.
15765   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15766
15767   MI->eraseFromParent(); // The pseudo is gone now.
15768   return BB;
15769 }
15770
15771 MachineBasicBlock *
15772 X86TargetLowering::EmitVAARG64WithCustomInserter(
15773                    MachineInstr *MI,
15774                    MachineBasicBlock *MBB) const {
15775   // Emit va_arg instruction on X86-64.
15776
15777   // Operands to this pseudo-instruction:
15778   // 0  ) Output        : destination address (reg)
15779   // 1-5) Input         : va_list address (addr, i64mem)
15780   // 6  ) ArgSize       : Size (in bytes) of vararg type
15781   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15782   // 8  ) Align         : Alignment of type
15783   // 9  ) EFLAGS (implicit-def)
15784
15785   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15786   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15787
15788   unsigned DestReg = MI->getOperand(0).getReg();
15789   MachineOperand &Base = MI->getOperand(1);
15790   MachineOperand &Scale = MI->getOperand(2);
15791   MachineOperand &Index = MI->getOperand(3);
15792   MachineOperand &Disp = MI->getOperand(4);
15793   MachineOperand &Segment = MI->getOperand(5);
15794   unsigned ArgSize = MI->getOperand(6).getImm();
15795   unsigned ArgMode = MI->getOperand(7).getImm();
15796   unsigned Align = MI->getOperand(8).getImm();
15797
15798   // Memory Reference
15799   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15800   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15801   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15802
15803   // Machine Information
15804   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15805   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15806   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15807   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15808   DebugLoc DL = MI->getDebugLoc();
15809
15810   // struct va_list {
15811   //   i32   gp_offset
15812   //   i32   fp_offset
15813   //   i64   overflow_area (address)
15814   //   i64   reg_save_area (address)
15815   // }
15816   // sizeof(va_list) = 24
15817   // alignment(va_list) = 8
15818
15819   unsigned TotalNumIntRegs = 6;
15820   unsigned TotalNumXMMRegs = 8;
15821   bool UseGPOffset = (ArgMode == 1);
15822   bool UseFPOffset = (ArgMode == 2);
15823   unsigned MaxOffset = TotalNumIntRegs * 8 +
15824                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15825
15826   /* Align ArgSize to a multiple of 8 */
15827   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15828   bool NeedsAlign = (Align > 8);
15829
15830   MachineBasicBlock *thisMBB = MBB;
15831   MachineBasicBlock *overflowMBB;
15832   MachineBasicBlock *offsetMBB;
15833   MachineBasicBlock *endMBB;
15834
15835   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15836   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15837   unsigned OffsetReg = 0;
15838
15839   if (!UseGPOffset && !UseFPOffset) {
15840     // If we only pull from the overflow region, we don't create a branch.
15841     // We don't need to alter control flow.
15842     OffsetDestReg = 0; // unused
15843     OverflowDestReg = DestReg;
15844
15845     offsetMBB = nullptr;
15846     overflowMBB = thisMBB;
15847     endMBB = thisMBB;
15848   } else {
15849     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15850     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15851     // If not, pull from overflow_area. (branch to overflowMBB)
15852     //
15853     //       thisMBB
15854     //         |     .
15855     //         |        .
15856     //     offsetMBB   overflowMBB
15857     //         |        .
15858     //         |     .
15859     //        endMBB
15860
15861     // Registers for the PHI in endMBB
15862     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15863     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15864
15865     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15866     MachineFunction *MF = MBB->getParent();
15867     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15868     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15869     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15870
15871     MachineFunction::iterator MBBIter = MBB;
15872     ++MBBIter;
15873
15874     // Insert the new basic blocks
15875     MF->insert(MBBIter, offsetMBB);
15876     MF->insert(MBBIter, overflowMBB);
15877     MF->insert(MBBIter, endMBB);
15878
15879     // Transfer the remainder of MBB and its successor edges to endMBB.
15880     endMBB->splice(endMBB->begin(), thisMBB,
15881                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15882     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15883
15884     // Make offsetMBB and overflowMBB successors of thisMBB
15885     thisMBB->addSuccessor(offsetMBB);
15886     thisMBB->addSuccessor(overflowMBB);
15887
15888     // endMBB is a successor of both offsetMBB and overflowMBB
15889     offsetMBB->addSuccessor(endMBB);
15890     overflowMBB->addSuccessor(endMBB);
15891
15892     // Load the offset value into a register
15893     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15894     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15895       .addOperand(Base)
15896       .addOperand(Scale)
15897       .addOperand(Index)
15898       .addDisp(Disp, UseFPOffset ? 4 : 0)
15899       .addOperand(Segment)
15900       .setMemRefs(MMOBegin, MMOEnd);
15901
15902     // Check if there is enough room left to pull this argument.
15903     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15904       .addReg(OffsetReg)
15905       .addImm(MaxOffset + 8 - ArgSizeA8);
15906
15907     // Branch to "overflowMBB" if offset >= max
15908     // Fall through to "offsetMBB" otherwise
15909     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15910       .addMBB(overflowMBB);
15911   }
15912
15913   // In offsetMBB, emit code to use the reg_save_area.
15914   if (offsetMBB) {
15915     assert(OffsetReg != 0);
15916
15917     // Read the reg_save_area address.
15918     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15919     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15920       .addOperand(Base)
15921       .addOperand(Scale)
15922       .addOperand(Index)
15923       .addDisp(Disp, 16)
15924       .addOperand(Segment)
15925       .setMemRefs(MMOBegin, MMOEnd);
15926
15927     // Zero-extend the offset
15928     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15929       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15930         .addImm(0)
15931         .addReg(OffsetReg)
15932         .addImm(X86::sub_32bit);
15933
15934     // Add the offset to the reg_save_area to get the final address.
15935     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15936       .addReg(OffsetReg64)
15937       .addReg(RegSaveReg);
15938
15939     // Compute the offset for the next argument
15940     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15941     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15942       .addReg(OffsetReg)
15943       .addImm(UseFPOffset ? 16 : 8);
15944
15945     // Store it back into the va_list.
15946     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15947       .addOperand(Base)
15948       .addOperand(Scale)
15949       .addOperand(Index)
15950       .addDisp(Disp, UseFPOffset ? 4 : 0)
15951       .addOperand(Segment)
15952       .addReg(NextOffsetReg)
15953       .setMemRefs(MMOBegin, MMOEnd);
15954
15955     // Jump to endMBB
15956     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15957       .addMBB(endMBB);
15958   }
15959
15960   //
15961   // Emit code to use overflow area
15962   //
15963
15964   // Load the overflow_area address into a register.
15965   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15966   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15967     .addOperand(Base)
15968     .addOperand(Scale)
15969     .addOperand(Index)
15970     .addDisp(Disp, 8)
15971     .addOperand(Segment)
15972     .setMemRefs(MMOBegin, MMOEnd);
15973
15974   // If we need to align it, do so. Otherwise, just copy the address
15975   // to OverflowDestReg.
15976   if (NeedsAlign) {
15977     // Align the overflow address
15978     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15979     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15980
15981     // aligned_addr = (addr + (align-1)) & ~(align-1)
15982     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15983       .addReg(OverflowAddrReg)
15984       .addImm(Align-1);
15985
15986     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15987       .addReg(TmpReg)
15988       .addImm(~(uint64_t)(Align-1));
15989   } else {
15990     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15991       .addReg(OverflowAddrReg);
15992   }
15993
15994   // Compute the next overflow address after this argument.
15995   // (the overflow address should be kept 8-byte aligned)
15996   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15997   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15998     .addReg(OverflowDestReg)
15999     .addImm(ArgSizeA8);
16000
16001   // Store the new overflow address.
16002   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16003     .addOperand(Base)
16004     .addOperand(Scale)
16005     .addOperand(Index)
16006     .addDisp(Disp, 8)
16007     .addOperand(Segment)
16008     .addReg(NextAddrReg)
16009     .setMemRefs(MMOBegin, MMOEnd);
16010
16011   // If we branched, emit the PHI to the front of endMBB.
16012   if (offsetMBB) {
16013     BuildMI(*endMBB, endMBB->begin(), DL,
16014             TII->get(X86::PHI), DestReg)
16015       .addReg(OffsetDestReg).addMBB(offsetMBB)
16016       .addReg(OverflowDestReg).addMBB(overflowMBB);
16017   }
16018
16019   // Erase the pseudo instruction
16020   MI->eraseFromParent();
16021
16022   return endMBB;
16023 }
16024
16025 MachineBasicBlock *
16026 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16027                                                  MachineInstr *MI,
16028                                                  MachineBasicBlock *MBB) const {
16029   // Emit code to save XMM registers to the stack. The ABI says that the
16030   // number of registers to save is given in %al, so it's theoretically
16031   // possible to do an indirect jump trick to avoid saving all of them,
16032   // however this code takes a simpler approach and just executes all
16033   // of the stores if %al is non-zero. It's less code, and it's probably
16034   // easier on the hardware branch predictor, and stores aren't all that
16035   // expensive anyway.
16036
16037   // Create the new basic blocks. One block contains all the XMM stores,
16038   // and one block is the final destination regardless of whether any
16039   // stores were performed.
16040   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16041   MachineFunction *F = MBB->getParent();
16042   MachineFunction::iterator MBBIter = MBB;
16043   ++MBBIter;
16044   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16045   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16046   F->insert(MBBIter, XMMSaveMBB);
16047   F->insert(MBBIter, EndMBB);
16048
16049   // Transfer the remainder of MBB and its successor edges to EndMBB.
16050   EndMBB->splice(EndMBB->begin(), MBB,
16051                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16052   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16053
16054   // The original block will now fall through to the XMM save block.
16055   MBB->addSuccessor(XMMSaveMBB);
16056   // The XMMSaveMBB will fall through to the end block.
16057   XMMSaveMBB->addSuccessor(EndMBB);
16058
16059   // Now add the instructions.
16060   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16061   DebugLoc DL = MI->getDebugLoc();
16062
16063   unsigned CountReg = MI->getOperand(0).getReg();
16064   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16065   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16066
16067   if (!Subtarget->isTargetWin64()) {
16068     // If %al is 0, branch around the XMM save block.
16069     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16070     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16071     MBB->addSuccessor(EndMBB);
16072   }
16073
16074   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16075   // that was just emitted, but clearly shouldn't be "saved".
16076   assert((MI->getNumOperands() <= 3 ||
16077           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16078           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16079          && "Expected last argument to be EFLAGS");
16080   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16081   // In the XMM save block, save all the XMM argument registers.
16082   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16083     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16084     MachineMemOperand *MMO =
16085       F->getMachineMemOperand(
16086           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16087         MachineMemOperand::MOStore,
16088         /*Size=*/16, /*Align=*/16);
16089     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16090       .addFrameIndex(RegSaveFrameIndex)
16091       .addImm(/*Scale=*/1)
16092       .addReg(/*IndexReg=*/0)
16093       .addImm(/*Disp=*/Offset)
16094       .addReg(/*Segment=*/0)
16095       .addReg(MI->getOperand(i).getReg())
16096       .addMemOperand(MMO);
16097   }
16098
16099   MI->eraseFromParent();   // The pseudo instruction is gone now.
16100
16101   return EndMBB;
16102 }
16103
16104 // The EFLAGS operand of SelectItr might be missing a kill marker
16105 // because there were multiple uses of EFLAGS, and ISel didn't know
16106 // which to mark. Figure out whether SelectItr should have had a
16107 // kill marker, and set it if it should. Returns the correct kill
16108 // marker value.
16109 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16110                                      MachineBasicBlock* BB,
16111                                      const TargetRegisterInfo* TRI) {
16112   // Scan forward through BB for a use/def of EFLAGS.
16113   MachineBasicBlock::iterator miI(std::next(SelectItr));
16114   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16115     const MachineInstr& mi = *miI;
16116     if (mi.readsRegister(X86::EFLAGS))
16117       return false;
16118     if (mi.definesRegister(X86::EFLAGS))
16119       break; // Should have kill-flag - update below.
16120   }
16121
16122   // If we hit the end of the block, check whether EFLAGS is live into a
16123   // successor.
16124   if (miI == BB->end()) {
16125     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16126                                           sEnd = BB->succ_end();
16127          sItr != sEnd; ++sItr) {
16128       MachineBasicBlock* succ = *sItr;
16129       if (succ->isLiveIn(X86::EFLAGS))
16130         return false;
16131     }
16132   }
16133
16134   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16135   // out. SelectMI should have a kill flag on EFLAGS.
16136   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16137   return true;
16138 }
16139
16140 MachineBasicBlock *
16141 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16142                                      MachineBasicBlock *BB) const {
16143   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16144   DebugLoc DL = MI->getDebugLoc();
16145
16146   // To "insert" a SELECT_CC instruction, we actually have to insert the
16147   // diamond control-flow pattern.  The incoming instruction knows the
16148   // destination vreg to set, the condition code register to branch on, the
16149   // true/false values to select between, and a branch opcode to use.
16150   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16151   MachineFunction::iterator It = BB;
16152   ++It;
16153
16154   //  thisMBB:
16155   //  ...
16156   //   TrueVal = ...
16157   //   cmpTY ccX, r1, r2
16158   //   bCC copy1MBB
16159   //   fallthrough --> copy0MBB
16160   MachineBasicBlock *thisMBB = BB;
16161   MachineFunction *F = BB->getParent();
16162   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16163   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16164   F->insert(It, copy0MBB);
16165   F->insert(It, sinkMBB);
16166
16167   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16168   // live into the sink and copy blocks.
16169   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16170   if (!MI->killsRegister(X86::EFLAGS) &&
16171       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16172     copy0MBB->addLiveIn(X86::EFLAGS);
16173     sinkMBB->addLiveIn(X86::EFLAGS);
16174   }
16175
16176   // Transfer the remainder of BB and its successor edges to sinkMBB.
16177   sinkMBB->splice(sinkMBB->begin(), BB,
16178                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16179   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16180
16181   // Add the true and fallthrough blocks as its successors.
16182   BB->addSuccessor(copy0MBB);
16183   BB->addSuccessor(sinkMBB);
16184
16185   // Create the conditional branch instruction.
16186   unsigned Opc =
16187     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16188   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16189
16190   //  copy0MBB:
16191   //   %FalseValue = ...
16192   //   # fallthrough to sinkMBB
16193   copy0MBB->addSuccessor(sinkMBB);
16194
16195   //  sinkMBB:
16196   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16197   //  ...
16198   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16199           TII->get(X86::PHI), MI->getOperand(0).getReg())
16200     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16201     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16202
16203   MI->eraseFromParent();   // The pseudo instruction is gone now.
16204   return sinkMBB;
16205 }
16206
16207 MachineBasicBlock *
16208 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16209                                         bool Is64Bit) const {
16210   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16211   DebugLoc DL = MI->getDebugLoc();
16212   MachineFunction *MF = BB->getParent();
16213   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16214
16215   assert(MF->shouldSplitStack());
16216
16217   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16218   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16219
16220   // BB:
16221   //  ... [Till the alloca]
16222   // If stacklet is not large enough, jump to mallocMBB
16223   //
16224   // bumpMBB:
16225   //  Allocate by subtracting from RSP
16226   //  Jump to continueMBB
16227   //
16228   // mallocMBB:
16229   //  Allocate by call to runtime
16230   //
16231   // continueMBB:
16232   //  ...
16233   //  [rest of original BB]
16234   //
16235
16236   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16237   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16238   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16239
16240   MachineRegisterInfo &MRI = MF->getRegInfo();
16241   const TargetRegisterClass *AddrRegClass =
16242     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16243
16244   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16245     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16246     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16247     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16248     sizeVReg = MI->getOperand(1).getReg(),
16249     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16250
16251   MachineFunction::iterator MBBIter = BB;
16252   ++MBBIter;
16253
16254   MF->insert(MBBIter, bumpMBB);
16255   MF->insert(MBBIter, mallocMBB);
16256   MF->insert(MBBIter, continueMBB);
16257
16258   continueMBB->splice(continueMBB->begin(), BB,
16259                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16260   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16261
16262   // Add code to the main basic block to check if the stack limit has been hit,
16263   // and if so, jump to mallocMBB otherwise to bumpMBB.
16264   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16265   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16266     .addReg(tmpSPVReg).addReg(sizeVReg);
16267   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16268     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16269     .addReg(SPLimitVReg);
16270   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16271
16272   // bumpMBB simply decreases the stack pointer, since we know the current
16273   // stacklet has enough space.
16274   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16275     .addReg(SPLimitVReg);
16276   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16277     .addReg(SPLimitVReg);
16278   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16279
16280   // Calls into a routine in libgcc to allocate more space from the heap.
16281   const uint32_t *RegMask =
16282     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16283   if (Is64Bit) {
16284     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16285       .addReg(sizeVReg);
16286     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16287       .addExternalSymbol("__morestack_allocate_stack_space")
16288       .addRegMask(RegMask)
16289       .addReg(X86::RDI, RegState::Implicit)
16290       .addReg(X86::RAX, RegState::ImplicitDefine);
16291   } else {
16292     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16293       .addImm(12);
16294     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16295     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16296       .addExternalSymbol("__morestack_allocate_stack_space")
16297       .addRegMask(RegMask)
16298       .addReg(X86::EAX, RegState::ImplicitDefine);
16299   }
16300
16301   if (!Is64Bit)
16302     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16303       .addImm(16);
16304
16305   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16306     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16307   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16308
16309   // Set up the CFG correctly.
16310   BB->addSuccessor(bumpMBB);
16311   BB->addSuccessor(mallocMBB);
16312   mallocMBB->addSuccessor(continueMBB);
16313   bumpMBB->addSuccessor(continueMBB);
16314
16315   // Take care of the PHI nodes.
16316   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16317           MI->getOperand(0).getReg())
16318     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16319     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16320
16321   // Delete the original pseudo instruction.
16322   MI->eraseFromParent();
16323
16324   // And we're done.
16325   return continueMBB;
16326 }
16327
16328 MachineBasicBlock *
16329 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16330                                           MachineBasicBlock *BB) const {
16331   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16332   DebugLoc DL = MI->getDebugLoc();
16333
16334   assert(!Subtarget->isTargetMacho());
16335
16336   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16337   // non-trivial part is impdef of ESP.
16338
16339   if (Subtarget->isTargetWin64()) {
16340     if (Subtarget->isTargetCygMing()) {
16341       // ___chkstk(Mingw64):
16342       // Clobbers R10, R11, RAX and EFLAGS.
16343       // Updates RSP.
16344       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16345         .addExternalSymbol("___chkstk")
16346         .addReg(X86::RAX, RegState::Implicit)
16347         .addReg(X86::RSP, RegState::Implicit)
16348         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16349         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16350         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16351     } else {
16352       // __chkstk(MSVCRT): does not update stack pointer.
16353       // Clobbers R10, R11 and EFLAGS.
16354       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16355         .addExternalSymbol("__chkstk")
16356         .addReg(X86::RAX, RegState::Implicit)
16357         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16358       // RAX has the offset to be subtracted from RSP.
16359       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16360         .addReg(X86::RSP)
16361         .addReg(X86::RAX);
16362     }
16363   } else {
16364     const char *StackProbeSymbol =
16365       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16366
16367     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16368       .addExternalSymbol(StackProbeSymbol)
16369       .addReg(X86::EAX, RegState::Implicit)
16370       .addReg(X86::ESP, RegState::Implicit)
16371       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16372       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16373       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16374   }
16375
16376   MI->eraseFromParent();   // The pseudo instruction is gone now.
16377   return BB;
16378 }
16379
16380 MachineBasicBlock *
16381 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16382                                       MachineBasicBlock *BB) const {
16383   // This is pretty easy.  We're taking the value that we received from
16384   // our load from the relocation, sticking it in either RDI (x86-64)
16385   // or EAX and doing an indirect call.  The return value will then
16386   // be in the normal return register.
16387   const X86InstrInfo *TII
16388     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16389   DebugLoc DL = MI->getDebugLoc();
16390   MachineFunction *F = BB->getParent();
16391
16392   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16393   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16394
16395   // Get a register mask for the lowered call.
16396   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16397   // proper register mask.
16398   const uint32_t *RegMask =
16399     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16400   if (Subtarget->is64Bit()) {
16401     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16402                                       TII->get(X86::MOV64rm), X86::RDI)
16403     .addReg(X86::RIP)
16404     .addImm(0).addReg(0)
16405     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16406                       MI->getOperand(3).getTargetFlags())
16407     .addReg(0);
16408     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16409     addDirectMem(MIB, X86::RDI);
16410     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16411   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16412     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16413                                       TII->get(X86::MOV32rm), X86::EAX)
16414     .addReg(0)
16415     .addImm(0).addReg(0)
16416     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16417                       MI->getOperand(3).getTargetFlags())
16418     .addReg(0);
16419     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16420     addDirectMem(MIB, X86::EAX);
16421     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16422   } else {
16423     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16424                                       TII->get(X86::MOV32rm), X86::EAX)
16425     .addReg(TII->getGlobalBaseReg(F))
16426     .addImm(0).addReg(0)
16427     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16428                       MI->getOperand(3).getTargetFlags())
16429     .addReg(0);
16430     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16431     addDirectMem(MIB, X86::EAX);
16432     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16433   }
16434
16435   MI->eraseFromParent(); // The pseudo instruction is gone now.
16436   return BB;
16437 }
16438
16439 MachineBasicBlock *
16440 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16441                                     MachineBasicBlock *MBB) const {
16442   DebugLoc DL = MI->getDebugLoc();
16443   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16444
16445   MachineFunction *MF = MBB->getParent();
16446   MachineRegisterInfo &MRI = MF->getRegInfo();
16447
16448   const BasicBlock *BB = MBB->getBasicBlock();
16449   MachineFunction::iterator I = MBB;
16450   ++I;
16451
16452   // Memory Reference
16453   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16454   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16455
16456   unsigned DstReg;
16457   unsigned MemOpndSlot = 0;
16458
16459   unsigned CurOp = 0;
16460
16461   DstReg = MI->getOperand(CurOp++).getReg();
16462   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16463   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16464   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16465   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16466
16467   MemOpndSlot = CurOp;
16468
16469   MVT PVT = getPointerTy();
16470   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16471          "Invalid Pointer Size!");
16472
16473   // For v = setjmp(buf), we generate
16474   //
16475   // thisMBB:
16476   //  buf[LabelOffset] = restoreMBB
16477   //  SjLjSetup restoreMBB
16478   //
16479   // mainMBB:
16480   //  v_main = 0
16481   //
16482   // sinkMBB:
16483   //  v = phi(main, restore)
16484   //
16485   // restoreMBB:
16486   //  v_restore = 1
16487
16488   MachineBasicBlock *thisMBB = MBB;
16489   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16490   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16491   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16492   MF->insert(I, mainMBB);
16493   MF->insert(I, sinkMBB);
16494   MF->push_back(restoreMBB);
16495
16496   MachineInstrBuilder MIB;
16497
16498   // Transfer the remainder of BB and its successor edges to sinkMBB.
16499   sinkMBB->splice(sinkMBB->begin(), MBB,
16500                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16501   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16502
16503   // thisMBB:
16504   unsigned PtrStoreOpc = 0;
16505   unsigned LabelReg = 0;
16506   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16507   Reloc::Model RM = getTargetMachine().getRelocationModel();
16508   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16509                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16510
16511   // Prepare IP either in reg or imm.
16512   if (!UseImmLabel) {
16513     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16514     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16515     LabelReg = MRI.createVirtualRegister(PtrRC);
16516     if (Subtarget->is64Bit()) {
16517       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16518               .addReg(X86::RIP)
16519               .addImm(0)
16520               .addReg(0)
16521               .addMBB(restoreMBB)
16522               .addReg(0);
16523     } else {
16524       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16525       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16526               .addReg(XII->getGlobalBaseReg(MF))
16527               .addImm(0)
16528               .addReg(0)
16529               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16530               .addReg(0);
16531     }
16532   } else
16533     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16534   // Store IP
16535   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16536   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16537     if (i == X86::AddrDisp)
16538       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16539     else
16540       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16541   }
16542   if (!UseImmLabel)
16543     MIB.addReg(LabelReg);
16544   else
16545     MIB.addMBB(restoreMBB);
16546   MIB.setMemRefs(MMOBegin, MMOEnd);
16547   // Setup
16548   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16549           .addMBB(restoreMBB);
16550
16551   const X86RegisterInfo *RegInfo =
16552     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16553   MIB.addRegMask(RegInfo->getNoPreservedMask());
16554   thisMBB->addSuccessor(mainMBB);
16555   thisMBB->addSuccessor(restoreMBB);
16556
16557   // mainMBB:
16558   //  EAX = 0
16559   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16560   mainMBB->addSuccessor(sinkMBB);
16561
16562   // sinkMBB:
16563   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16564           TII->get(X86::PHI), DstReg)
16565     .addReg(mainDstReg).addMBB(mainMBB)
16566     .addReg(restoreDstReg).addMBB(restoreMBB);
16567
16568   // restoreMBB:
16569   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16570   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16571   restoreMBB->addSuccessor(sinkMBB);
16572
16573   MI->eraseFromParent();
16574   return sinkMBB;
16575 }
16576
16577 MachineBasicBlock *
16578 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16579                                      MachineBasicBlock *MBB) const {
16580   DebugLoc DL = MI->getDebugLoc();
16581   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16582
16583   MachineFunction *MF = MBB->getParent();
16584   MachineRegisterInfo &MRI = MF->getRegInfo();
16585
16586   // Memory Reference
16587   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16588   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16589
16590   MVT PVT = getPointerTy();
16591   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16592          "Invalid Pointer Size!");
16593
16594   const TargetRegisterClass *RC =
16595     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16596   unsigned Tmp = MRI.createVirtualRegister(RC);
16597   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16598   const X86RegisterInfo *RegInfo =
16599     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16600   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16601   unsigned SP = RegInfo->getStackRegister();
16602
16603   MachineInstrBuilder MIB;
16604
16605   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16606   const int64_t SPOffset = 2 * PVT.getStoreSize();
16607
16608   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16609   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16610
16611   // Reload FP
16612   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16613   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16614     MIB.addOperand(MI->getOperand(i));
16615   MIB.setMemRefs(MMOBegin, MMOEnd);
16616   // Reload IP
16617   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16618   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16619     if (i == X86::AddrDisp)
16620       MIB.addDisp(MI->getOperand(i), LabelOffset);
16621     else
16622       MIB.addOperand(MI->getOperand(i));
16623   }
16624   MIB.setMemRefs(MMOBegin, MMOEnd);
16625   // Reload SP
16626   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16627   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16628     if (i == X86::AddrDisp)
16629       MIB.addDisp(MI->getOperand(i), SPOffset);
16630     else
16631       MIB.addOperand(MI->getOperand(i));
16632   }
16633   MIB.setMemRefs(MMOBegin, MMOEnd);
16634   // Jump
16635   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16636
16637   MI->eraseFromParent();
16638   return MBB;
16639 }
16640
16641 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16642 // accumulator loops. Writing back to the accumulator allows the coalescer
16643 // to remove extra copies in the loop.   
16644 MachineBasicBlock *
16645 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16646                                  MachineBasicBlock *MBB) const {
16647   MachineOperand &AddendOp = MI->getOperand(3);
16648
16649   // Bail out early if the addend isn't a register - we can't switch these.
16650   if (!AddendOp.isReg())
16651     return MBB;
16652
16653   MachineFunction &MF = *MBB->getParent();
16654   MachineRegisterInfo &MRI = MF.getRegInfo();
16655
16656   // Check whether the addend is defined by a PHI:
16657   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16658   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16659   if (!AddendDef.isPHI())
16660     return MBB;
16661
16662   // Look for the following pattern:
16663   // loop:
16664   //   %addend = phi [%entry, 0], [%loop, %result]
16665   //   ...
16666   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16667
16668   // Replace with:
16669   //   loop:
16670   //   %addend = phi [%entry, 0], [%loop, %result]
16671   //   ...
16672   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16673
16674   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16675     assert(AddendDef.getOperand(i).isReg());
16676     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16677     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16678     if (&PHISrcInst == MI) {
16679       // Found a matching instruction.
16680       unsigned NewFMAOpc = 0;
16681       switch (MI->getOpcode()) {
16682         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16683         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16684         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16685         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16686         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16687         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16688         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16689         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16690         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16691         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16692         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16693         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16694         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16695         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16696         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16697         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16698         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16699         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16700         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16701         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16702         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16703         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16704         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16705         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16706         default: llvm_unreachable("Unrecognized FMA variant.");
16707       }
16708
16709       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16710       MachineInstrBuilder MIB =
16711         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16712         .addOperand(MI->getOperand(0))
16713         .addOperand(MI->getOperand(3))
16714         .addOperand(MI->getOperand(2))
16715         .addOperand(MI->getOperand(1));
16716       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16717       MI->eraseFromParent();
16718     }
16719   }
16720
16721   return MBB;
16722 }
16723
16724 MachineBasicBlock *
16725 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16726                                                MachineBasicBlock *BB) const {
16727   switch (MI->getOpcode()) {
16728   default: llvm_unreachable("Unexpected instr type to insert");
16729   case X86::TAILJMPd64:
16730   case X86::TAILJMPr64:
16731   case X86::TAILJMPm64:
16732     llvm_unreachable("TAILJMP64 would not be touched here.");
16733   case X86::TCRETURNdi64:
16734   case X86::TCRETURNri64:
16735   case X86::TCRETURNmi64:
16736     return BB;
16737   case X86::WIN_ALLOCA:
16738     return EmitLoweredWinAlloca(MI, BB);
16739   case X86::SEG_ALLOCA_32:
16740     return EmitLoweredSegAlloca(MI, BB, false);
16741   case X86::SEG_ALLOCA_64:
16742     return EmitLoweredSegAlloca(MI, BB, true);
16743   case X86::TLSCall_32:
16744   case X86::TLSCall_64:
16745     return EmitLoweredTLSCall(MI, BB);
16746   case X86::CMOV_GR8:
16747   case X86::CMOV_FR32:
16748   case X86::CMOV_FR64:
16749   case X86::CMOV_V4F32:
16750   case X86::CMOV_V2F64:
16751   case X86::CMOV_V2I64:
16752   case X86::CMOV_V8F32:
16753   case X86::CMOV_V4F64:
16754   case X86::CMOV_V4I64:
16755   case X86::CMOV_V16F32:
16756   case X86::CMOV_V8F64:
16757   case X86::CMOV_V8I64:
16758   case X86::CMOV_GR16:
16759   case X86::CMOV_GR32:
16760   case X86::CMOV_RFP32:
16761   case X86::CMOV_RFP64:
16762   case X86::CMOV_RFP80:
16763     return EmitLoweredSelect(MI, BB);
16764
16765   case X86::FP32_TO_INT16_IN_MEM:
16766   case X86::FP32_TO_INT32_IN_MEM:
16767   case X86::FP32_TO_INT64_IN_MEM:
16768   case X86::FP64_TO_INT16_IN_MEM:
16769   case X86::FP64_TO_INT32_IN_MEM:
16770   case X86::FP64_TO_INT64_IN_MEM:
16771   case X86::FP80_TO_INT16_IN_MEM:
16772   case X86::FP80_TO_INT32_IN_MEM:
16773   case X86::FP80_TO_INT64_IN_MEM: {
16774     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16775     DebugLoc DL = MI->getDebugLoc();
16776
16777     // Change the floating point control register to use "round towards zero"
16778     // mode when truncating to an integer value.
16779     MachineFunction *F = BB->getParent();
16780     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16781     addFrameReference(BuildMI(*BB, MI, DL,
16782                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16783
16784     // Load the old value of the high byte of the control word...
16785     unsigned OldCW =
16786       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16787     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16788                       CWFrameIdx);
16789
16790     // Set the high part to be round to zero...
16791     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16792       .addImm(0xC7F);
16793
16794     // Reload the modified control word now...
16795     addFrameReference(BuildMI(*BB, MI, DL,
16796                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16797
16798     // Restore the memory image of control word to original value
16799     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16800       .addReg(OldCW);
16801
16802     // Get the X86 opcode to use.
16803     unsigned Opc;
16804     switch (MI->getOpcode()) {
16805     default: llvm_unreachable("illegal opcode!");
16806     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16807     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16808     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16809     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16810     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16811     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16812     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16813     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16814     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16815     }
16816
16817     X86AddressMode AM;
16818     MachineOperand &Op = MI->getOperand(0);
16819     if (Op.isReg()) {
16820       AM.BaseType = X86AddressMode::RegBase;
16821       AM.Base.Reg = Op.getReg();
16822     } else {
16823       AM.BaseType = X86AddressMode::FrameIndexBase;
16824       AM.Base.FrameIndex = Op.getIndex();
16825     }
16826     Op = MI->getOperand(1);
16827     if (Op.isImm())
16828       AM.Scale = Op.getImm();
16829     Op = MI->getOperand(2);
16830     if (Op.isImm())
16831       AM.IndexReg = Op.getImm();
16832     Op = MI->getOperand(3);
16833     if (Op.isGlobal()) {
16834       AM.GV = Op.getGlobal();
16835     } else {
16836       AM.Disp = Op.getImm();
16837     }
16838     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16839                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16840
16841     // Reload the original control word now.
16842     addFrameReference(BuildMI(*BB, MI, DL,
16843                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16844
16845     MI->eraseFromParent();   // The pseudo instruction is gone now.
16846     return BB;
16847   }
16848     // String/text processing lowering.
16849   case X86::PCMPISTRM128REG:
16850   case X86::VPCMPISTRM128REG:
16851   case X86::PCMPISTRM128MEM:
16852   case X86::VPCMPISTRM128MEM:
16853   case X86::PCMPESTRM128REG:
16854   case X86::VPCMPESTRM128REG:
16855   case X86::PCMPESTRM128MEM:
16856   case X86::VPCMPESTRM128MEM:
16857     assert(Subtarget->hasSSE42() &&
16858            "Target must have SSE4.2 or AVX features enabled");
16859     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16860
16861   // String/text processing lowering.
16862   case X86::PCMPISTRIREG:
16863   case X86::VPCMPISTRIREG:
16864   case X86::PCMPISTRIMEM:
16865   case X86::VPCMPISTRIMEM:
16866   case X86::PCMPESTRIREG:
16867   case X86::VPCMPESTRIREG:
16868   case X86::PCMPESTRIMEM:
16869   case X86::VPCMPESTRIMEM:
16870     assert(Subtarget->hasSSE42() &&
16871            "Target must have SSE4.2 or AVX features enabled");
16872     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16873
16874   // Thread synchronization.
16875   case X86::MONITOR:
16876     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16877
16878   // xbegin
16879   case X86::XBEGIN:
16880     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16881
16882   // Atomic Lowering.
16883   case X86::ATOMAND8:
16884   case X86::ATOMAND16:
16885   case X86::ATOMAND32:
16886   case X86::ATOMAND64:
16887     // Fall through
16888   case X86::ATOMOR8:
16889   case X86::ATOMOR16:
16890   case X86::ATOMOR32:
16891   case X86::ATOMOR64:
16892     // Fall through
16893   case X86::ATOMXOR16:
16894   case X86::ATOMXOR8:
16895   case X86::ATOMXOR32:
16896   case X86::ATOMXOR64:
16897     // Fall through
16898   case X86::ATOMNAND8:
16899   case X86::ATOMNAND16:
16900   case X86::ATOMNAND32:
16901   case X86::ATOMNAND64:
16902     // Fall through
16903   case X86::ATOMMAX8:
16904   case X86::ATOMMAX16:
16905   case X86::ATOMMAX32:
16906   case X86::ATOMMAX64:
16907     // Fall through
16908   case X86::ATOMMIN8:
16909   case X86::ATOMMIN16:
16910   case X86::ATOMMIN32:
16911   case X86::ATOMMIN64:
16912     // Fall through
16913   case X86::ATOMUMAX8:
16914   case X86::ATOMUMAX16:
16915   case X86::ATOMUMAX32:
16916   case X86::ATOMUMAX64:
16917     // Fall through
16918   case X86::ATOMUMIN8:
16919   case X86::ATOMUMIN16:
16920   case X86::ATOMUMIN32:
16921   case X86::ATOMUMIN64:
16922     return EmitAtomicLoadArith(MI, BB);
16923
16924   // This group does 64-bit operations on a 32-bit host.
16925   case X86::ATOMAND6432:
16926   case X86::ATOMOR6432:
16927   case X86::ATOMXOR6432:
16928   case X86::ATOMNAND6432:
16929   case X86::ATOMADD6432:
16930   case X86::ATOMSUB6432:
16931   case X86::ATOMMAX6432:
16932   case X86::ATOMMIN6432:
16933   case X86::ATOMUMAX6432:
16934   case X86::ATOMUMIN6432:
16935   case X86::ATOMSWAP6432:
16936     return EmitAtomicLoadArith6432(MI, BB);
16937
16938   case X86::VASTART_SAVE_XMM_REGS:
16939     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16940
16941   case X86::VAARG_64:
16942     return EmitVAARG64WithCustomInserter(MI, BB);
16943
16944   case X86::EH_SjLj_SetJmp32:
16945   case X86::EH_SjLj_SetJmp64:
16946     return emitEHSjLjSetJmp(MI, BB);
16947
16948   case X86::EH_SjLj_LongJmp32:
16949   case X86::EH_SjLj_LongJmp64:
16950     return emitEHSjLjLongJmp(MI, BB);
16951
16952   case TargetOpcode::STACKMAP:
16953   case TargetOpcode::PATCHPOINT:
16954     return emitPatchPoint(MI, BB);
16955
16956   case X86::VFMADDPDr213r:
16957   case X86::VFMADDPSr213r:
16958   case X86::VFMADDSDr213r:
16959   case X86::VFMADDSSr213r:
16960   case X86::VFMSUBPDr213r:
16961   case X86::VFMSUBPSr213r:
16962   case X86::VFMSUBSDr213r:
16963   case X86::VFMSUBSSr213r:
16964   case X86::VFNMADDPDr213r:
16965   case X86::VFNMADDPSr213r:
16966   case X86::VFNMADDSDr213r:
16967   case X86::VFNMADDSSr213r:
16968   case X86::VFNMSUBPDr213r:
16969   case X86::VFNMSUBPSr213r:
16970   case X86::VFNMSUBSDr213r:
16971   case X86::VFNMSUBSSr213r:
16972   case X86::VFMADDPDr213rY:
16973   case X86::VFMADDPSr213rY:
16974   case X86::VFMSUBPDr213rY:
16975   case X86::VFMSUBPSr213rY:
16976   case X86::VFNMADDPDr213rY:
16977   case X86::VFNMADDPSr213rY:
16978   case X86::VFNMSUBPDr213rY:
16979   case X86::VFNMSUBPSr213rY:
16980     return emitFMA3Instr(MI, BB);
16981   }
16982 }
16983
16984 //===----------------------------------------------------------------------===//
16985 //                           X86 Optimization Hooks
16986 //===----------------------------------------------------------------------===//
16987
16988 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16989                                                        APInt &KnownZero,
16990                                                        APInt &KnownOne,
16991                                                        const SelectionDAG &DAG,
16992                                                        unsigned Depth) const {
16993   unsigned BitWidth = KnownZero.getBitWidth();
16994   unsigned Opc = Op.getOpcode();
16995   assert((Opc >= ISD::BUILTIN_OP_END ||
16996           Opc == ISD::INTRINSIC_WO_CHAIN ||
16997           Opc == ISD::INTRINSIC_W_CHAIN ||
16998           Opc == ISD::INTRINSIC_VOID) &&
16999          "Should use MaskedValueIsZero if you don't know whether Op"
17000          " is a target node!");
17001
17002   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17003   switch (Opc) {
17004   default: break;
17005   case X86ISD::ADD:
17006   case X86ISD::SUB:
17007   case X86ISD::ADC:
17008   case X86ISD::SBB:
17009   case X86ISD::SMUL:
17010   case X86ISD::UMUL:
17011   case X86ISD::INC:
17012   case X86ISD::DEC:
17013   case X86ISD::OR:
17014   case X86ISD::XOR:
17015   case X86ISD::AND:
17016     // These nodes' second result is a boolean.
17017     if (Op.getResNo() == 0)
17018       break;
17019     // Fallthrough
17020   case X86ISD::SETCC:
17021     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17022     break;
17023   case ISD::INTRINSIC_WO_CHAIN: {
17024     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17025     unsigned NumLoBits = 0;
17026     switch (IntId) {
17027     default: break;
17028     case Intrinsic::x86_sse_movmsk_ps:
17029     case Intrinsic::x86_avx_movmsk_ps_256:
17030     case Intrinsic::x86_sse2_movmsk_pd:
17031     case Intrinsic::x86_avx_movmsk_pd_256:
17032     case Intrinsic::x86_mmx_pmovmskb:
17033     case Intrinsic::x86_sse2_pmovmskb_128:
17034     case Intrinsic::x86_avx2_pmovmskb: {
17035       // High bits of movmskp{s|d}, pmovmskb are known zero.
17036       switch (IntId) {
17037         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17038         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17039         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17040         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17041         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17042         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17043         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17044         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17045       }
17046       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17047       break;
17048     }
17049     }
17050     break;
17051   }
17052   }
17053 }
17054
17055 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17056   SDValue Op,
17057   const SelectionDAG &,
17058   unsigned Depth) const {
17059   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17060   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17061     return Op.getValueType().getScalarType().getSizeInBits();
17062
17063   // Fallback case.
17064   return 1;
17065 }
17066
17067 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17068 /// node is a GlobalAddress + offset.
17069 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17070                                        const GlobalValue* &GA,
17071                                        int64_t &Offset) const {
17072   if (N->getOpcode() == X86ISD::Wrapper) {
17073     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17074       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17075       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17076       return true;
17077     }
17078   }
17079   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17080 }
17081
17082 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17083 /// same as extracting the high 128-bit part of 256-bit vector and then
17084 /// inserting the result into the low part of a new 256-bit vector
17085 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17086   EVT VT = SVOp->getValueType(0);
17087   unsigned NumElems = VT.getVectorNumElements();
17088
17089   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17090   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17091     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17092         SVOp->getMaskElt(j) >= 0)
17093       return false;
17094
17095   return true;
17096 }
17097
17098 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17099 /// same as extracting the low 128-bit part of 256-bit vector and then
17100 /// inserting the result into the high part of a new 256-bit vector
17101 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17102   EVT VT = SVOp->getValueType(0);
17103   unsigned NumElems = VT.getVectorNumElements();
17104
17105   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17106   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17107     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17108         SVOp->getMaskElt(j) >= 0)
17109       return false;
17110
17111   return true;
17112 }
17113
17114 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17115 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17116                                         TargetLowering::DAGCombinerInfo &DCI,
17117                                         const X86Subtarget* Subtarget) {
17118   SDLoc dl(N);
17119   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17120   SDValue V1 = SVOp->getOperand(0);
17121   SDValue V2 = SVOp->getOperand(1);
17122   EVT VT = SVOp->getValueType(0);
17123   unsigned NumElems = VT.getVectorNumElements();
17124
17125   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17126       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17127     //
17128     //                   0,0,0,...
17129     //                      |
17130     //    V      UNDEF    BUILD_VECTOR    UNDEF
17131     //     \      /           \           /
17132     //  CONCAT_VECTOR         CONCAT_VECTOR
17133     //         \                  /
17134     //          \                /
17135     //          RESULT: V + zero extended
17136     //
17137     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17138         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17139         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17140       return SDValue();
17141
17142     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17143       return SDValue();
17144
17145     // To match the shuffle mask, the first half of the mask should
17146     // be exactly the first vector, and all the rest a splat with the
17147     // first element of the second one.
17148     for (unsigned i = 0; i != NumElems/2; ++i)
17149       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17150           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17151         return SDValue();
17152
17153     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17154     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17155       if (Ld->hasNUsesOfValue(1, 0)) {
17156         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17157         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17158         SDValue ResNode =
17159           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17160                                   Ld->getMemoryVT(),
17161                                   Ld->getPointerInfo(),
17162                                   Ld->getAlignment(),
17163                                   false/*isVolatile*/, true/*ReadMem*/,
17164                                   false/*WriteMem*/);
17165
17166         // Make sure the newly-created LOAD is in the same position as Ld in
17167         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17168         // and update uses of Ld's output chain to use the TokenFactor.
17169         if (Ld->hasAnyUseOfValue(1)) {
17170           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17171                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17172           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17173           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17174                                  SDValue(ResNode.getNode(), 1));
17175         }
17176
17177         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17178       }
17179     }
17180
17181     // Emit a zeroed vector and insert the desired subvector on its
17182     // first half.
17183     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17184     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17185     return DCI.CombineTo(N, InsV);
17186   }
17187
17188   //===--------------------------------------------------------------------===//
17189   // Combine some shuffles into subvector extracts and inserts:
17190   //
17191
17192   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17193   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17194     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17195     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17196     return DCI.CombineTo(N, InsV);
17197   }
17198
17199   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17200   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17201     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17202     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17203     return DCI.CombineTo(N, InsV);
17204   }
17205
17206   return SDValue();
17207 }
17208
17209 /// PerformShuffleCombine - Performs several different shuffle combines.
17210 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17211                                      TargetLowering::DAGCombinerInfo &DCI,
17212                                      const X86Subtarget *Subtarget) {
17213   SDLoc dl(N);
17214   EVT VT = N->getValueType(0);
17215
17216   // Don't create instructions with illegal types after legalize types has run.
17217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17218   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17219     return SDValue();
17220
17221   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17222   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17223       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17224     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17225
17226   // Only handle 128 wide vector from here on.
17227   if (!VT.is128BitVector())
17228     return SDValue();
17229
17230   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17231   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17232   // consecutive, non-overlapping, and in the right order.
17233   SmallVector<SDValue, 16> Elts;
17234   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17235     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17236
17237   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17238 }
17239
17240 /// PerformTruncateCombine - Converts truncate operation to
17241 /// a sequence of vector shuffle operations.
17242 /// It is possible when we truncate 256-bit vector to 128-bit vector
17243 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17244                                       TargetLowering::DAGCombinerInfo &DCI,
17245                                       const X86Subtarget *Subtarget)  {
17246   return SDValue();
17247 }
17248
17249 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17250 /// specific shuffle of a load can be folded into a single element load.
17251 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17252 /// shuffles have been customed lowered so we need to handle those here.
17253 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17254                                          TargetLowering::DAGCombinerInfo &DCI) {
17255   if (DCI.isBeforeLegalizeOps())
17256     return SDValue();
17257
17258   SDValue InVec = N->getOperand(0);
17259   SDValue EltNo = N->getOperand(1);
17260
17261   if (!isa<ConstantSDNode>(EltNo))
17262     return SDValue();
17263
17264   EVT VT = InVec.getValueType();
17265
17266   bool HasShuffleIntoBitcast = false;
17267   if (InVec.getOpcode() == ISD::BITCAST) {
17268     // Don't duplicate a load with other uses.
17269     if (!InVec.hasOneUse())
17270       return SDValue();
17271     EVT BCVT = InVec.getOperand(0).getValueType();
17272     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17273       return SDValue();
17274     InVec = InVec.getOperand(0);
17275     HasShuffleIntoBitcast = true;
17276   }
17277
17278   if (!isTargetShuffle(InVec.getOpcode()))
17279     return SDValue();
17280
17281   // Don't duplicate a load with other uses.
17282   if (!InVec.hasOneUse())
17283     return SDValue();
17284
17285   SmallVector<int, 16> ShuffleMask;
17286   bool UnaryShuffle;
17287   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17288                             UnaryShuffle))
17289     return SDValue();
17290
17291   // Select the input vector, guarding against out of range extract vector.
17292   unsigned NumElems = VT.getVectorNumElements();
17293   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17294   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17295   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17296                                          : InVec.getOperand(1);
17297
17298   // If inputs to shuffle are the same for both ops, then allow 2 uses
17299   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17300
17301   if (LdNode.getOpcode() == ISD::BITCAST) {
17302     // Don't duplicate a load with other uses.
17303     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17304       return SDValue();
17305
17306     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17307     LdNode = LdNode.getOperand(0);
17308   }
17309
17310   if (!ISD::isNormalLoad(LdNode.getNode()))
17311     return SDValue();
17312
17313   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17314
17315   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17316     return SDValue();
17317
17318   if (HasShuffleIntoBitcast) {
17319     // If there's a bitcast before the shuffle, check if the load type and
17320     // alignment is valid.
17321     unsigned Align = LN0->getAlignment();
17322     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17323     unsigned NewAlign = TLI.getDataLayout()->
17324       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17325
17326     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17327       return SDValue();
17328   }
17329
17330   // All checks match so transform back to vector_shuffle so that DAG combiner
17331   // can finish the job
17332   SDLoc dl(N);
17333
17334   // Create shuffle node taking into account the case that its a unary shuffle
17335   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17336   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17337                                  InVec.getOperand(0), Shuffle,
17338                                  &ShuffleMask[0]);
17339   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17340   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17341                      EltNo);
17342 }
17343
17344 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17345 /// generation and convert it from being a bunch of shuffles and extracts
17346 /// to a simple store and scalar loads to extract the elements.
17347 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17348                                          TargetLowering::DAGCombinerInfo &DCI) {
17349   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17350   if (NewOp.getNode())
17351     return NewOp;
17352
17353   SDValue InputVector = N->getOperand(0);
17354
17355   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17356   // from mmx to v2i32 has a single usage.
17357   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17358       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17359       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17360     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17361                        N->getValueType(0),
17362                        InputVector.getNode()->getOperand(0));
17363
17364   // Only operate on vectors of 4 elements, where the alternative shuffling
17365   // gets to be more expensive.
17366   if (InputVector.getValueType() != MVT::v4i32)
17367     return SDValue();
17368
17369   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17370   // single use which is a sign-extend or zero-extend, and all elements are
17371   // used.
17372   SmallVector<SDNode *, 4> Uses;
17373   unsigned ExtractedElements = 0;
17374   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17375        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17376     if (UI.getUse().getResNo() != InputVector.getResNo())
17377       return SDValue();
17378
17379     SDNode *Extract = *UI;
17380     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17381       return SDValue();
17382
17383     if (Extract->getValueType(0) != MVT::i32)
17384       return SDValue();
17385     if (!Extract->hasOneUse())
17386       return SDValue();
17387     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17388         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17389       return SDValue();
17390     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17391       return SDValue();
17392
17393     // Record which element was extracted.
17394     ExtractedElements |=
17395       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17396
17397     Uses.push_back(Extract);
17398   }
17399
17400   // If not all the elements were used, this may not be worthwhile.
17401   if (ExtractedElements != 15)
17402     return SDValue();
17403
17404   // Ok, we've now decided to do the transformation.
17405   SDLoc dl(InputVector);
17406
17407   // Store the value to a temporary stack slot.
17408   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17409   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17410                             MachinePointerInfo(), false, false, 0);
17411
17412   // Replace each use (extract) with a load of the appropriate element.
17413   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17414        UE = Uses.end(); UI != UE; ++UI) {
17415     SDNode *Extract = *UI;
17416
17417     // cOMpute the element's address.
17418     SDValue Idx = Extract->getOperand(1);
17419     unsigned EltSize =
17420         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17421     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17422     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17423     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17424
17425     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17426                                      StackPtr, OffsetVal);
17427
17428     // Load the scalar.
17429     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17430                                      ScalarAddr, MachinePointerInfo(),
17431                                      false, false, false, 0);
17432
17433     // Replace the exact with the load.
17434     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17435   }
17436
17437   // The replacement was made in place; don't return anything.
17438   return SDValue();
17439 }
17440
17441 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17442 static std::pair<unsigned, bool>
17443 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17444                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17445   if (!VT.isVector())
17446     return std::make_pair(0, false);
17447
17448   bool NeedSplit = false;
17449   switch (VT.getSimpleVT().SimpleTy) {
17450   default: return std::make_pair(0, false);
17451   case MVT::v32i8:
17452   case MVT::v16i16:
17453   case MVT::v8i32:
17454     if (!Subtarget->hasAVX2())
17455       NeedSplit = true;
17456     if (!Subtarget->hasAVX())
17457       return std::make_pair(0, false);
17458     break;
17459   case MVT::v16i8:
17460   case MVT::v8i16:
17461   case MVT::v4i32:
17462     if (!Subtarget->hasSSE2())
17463       return std::make_pair(0, false);
17464   }
17465
17466   // SSE2 has only a small subset of the operations.
17467   bool hasUnsigned = Subtarget->hasSSE41() ||
17468                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17469   bool hasSigned = Subtarget->hasSSE41() ||
17470                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17471
17472   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17473
17474   unsigned Opc = 0;
17475   // Check for x CC y ? x : y.
17476   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17477       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17478     switch (CC) {
17479     default: break;
17480     case ISD::SETULT:
17481     case ISD::SETULE:
17482       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17483     case ISD::SETUGT:
17484     case ISD::SETUGE:
17485       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17486     case ISD::SETLT:
17487     case ISD::SETLE:
17488       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17489     case ISD::SETGT:
17490     case ISD::SETGE:
17491       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17492     }
17493   // Check for x CC y ? y : x -- a min/max with reversed arms.
17494   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17495              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17496     switch (CC) {
17497     default: break;
17498     case ISD::SETULT:
17499     case ISD::SETULE:
17500       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17501     case ISD::SETUGT:
17502     case ISD::SETUGE:
17503       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17504     case ISD::SETLT:
17505     case ISD::SETLE:
17506       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17507     case ISD::SETGT:
17508     case ISD::SETGE:
17509       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17510     }
17511   }
17512
17513   return std::make_pair(Opc, NeedSplit);
17514 }
17515
17516 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17517 /// nodes.
17518 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17519                                     TargetLowering::DAGCombinerInfo &DCI,
17520                                     const X86Subtarget *Subtarget) {
17521   SDLoc DL(N);
17522   SDValue Cond = N->getOperand(0);
17523   // Get the LHS/RHS of the select.
17524   SDValue LHS = N->getOperand(1);
17525   SDValue RHS = N->getOperand(2);
17526   EVT VT = LHS.getValueType();
17527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17528
17529   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17530   // instructions match the semantics of the common C idiom x<y?x:y but not
17531   // x<=y?x:y, because of how they handle negative zero (which can be
17532   // ignored in unsafe-math mode).
17533   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17534       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17535       (Subtarget->hasSSE2() ||
17536        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17537     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17538
17539     unsigned Opcode = 0;
17540     // Check for x CC y ? x : y.
17541     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17542         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17543       switch (CC) {
17544       default: break;
17545       case ISD::SETULT:
17546         // Converting this to a min would handle NaNs incorrectly, and swapping
17547         // the operands would cause it to handle comparisons between positive
17548         // and negative zero incorrectly.
17549         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17550           if (!DAG.getTarget().Options.UnsafeFPMath &&
17551               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17552             break;
17553           std::swap(LHS, RHS);
17554         }
17555         Opcode = X86ISD::FMIN;
17556         break;
17557       case ISD::SETOLE:
17558         // Converting this to a min would handle comparisons between positive
17559         // and negative zero incorrectly.
17560         if (!DAG.getTarget().Options.UnsafeFPMath &&
17561             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17562           break;
17563         Opcode = X86ISD::FMIN;
17564         break;
17565       case ISD::SETULE:
17566         // Converting this to a min would handle both negative zeros and NaNs
17567         // incorrectly, but we can swap the operands to fix both.
17568         std::swap(LHS, RHS);
17569       case ISD::SETOLT:
17570       case ISD::SETLT:
17571       case ISD::SETLE:
17572         Opcode = X86ISD::FMIN;
17573         break;
17574
17575       case ISD::SETOGE:
17576         // Converting this to a max would handle comparisons between positive
17577         // and negative zero incorrectly.
17578         if (!DAG.getTarget().Options.UnsafeFPMath &&
17579             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17580           break;
17581         Opcode = X86ISD::FMAX;
17582         break;
17583       case ISD::SETUGT:
17584         // Converting this to a max would handle NaNs incorrectly, and swapping
17585         // the operands would cause it to handle comparisons between positive
17586         // and negative zero incorrectly.
17587         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17588           if (!DAG.getTarget().Options.UnsafeFPMath &&
17589               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17590             break;
17591           std::swap(LHS, RHS);
17592         }
17593         Opcode = X86ISD::FMAX;
17594         break;
17595       case ISD::SETUGE:
17596         // Converting this to a max would handle both negative zeros and NaNs
17597         // incorrectly, but we can swap the operands to fix both.
17598         std::swap(LHS, RHS);
17599       case ISD::SETOGT:
17600       case ISD::SETGT:
17601       case ISD::SETGE:
17602         Opcode = X86ISD::FMAX;
17603         break;
17604       }
17605     // Check for x CC y ? y : x -- a min/max with reversed arms.
17606     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17607                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17608       switch (CC) {
17609       default: break;
17610       case ISD::SETOGE:
17611         // Converting this to a min would handle comparisons between positive
17612         // and negative zero incorrectly, and swapping the operands would
17613         // cause it to handle NaNs incorrectly.
17614         if (!DAG.getTarget().Options.UnsafeFPMath &&
17615             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17616           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17617             break;
17618           std::swap(LHS, RHS);
17619         }
17620         Opcode = X86ISD::FMIN;
17621         break;
17622       case ISD::SETUGT:
17623         // Converting this to a min would handle NaNs incorrectly.
17624         if (!DAG.getTarget().Options.UnsafeFPMath &&
17625             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17626           break;
17627         Opcode = X86ISD::FMIN;
17628         break;
17629       case ISD::SETUGE:
17630         // Converting this to a min would handle both negative zeros and NaNs
17631         // incorrectly, but we can swap the operands to fix both.
17632         std::swap(LHS, RHS);
17633       case ISD::SETOGT:
17634       case ISD::SETGT:
17635       case ISD::SETGE:
17636         Opcode = X86ISD::FMIN;
17637         break;
17638
17639       case ISD::SETULT:
17640         // Converting this to a max would handle NaNs incorrectly.
17641         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17642           break;
17643         Opcode = X86ISD::FMAX;
17644         break;
17645       case ISD::SETOLE:
17646         // Converting this to a max would handle comparisons between positive
17647         // and negative zero incorrectly, and swapping the operands would
17648         // cause it to handle NaNs incorrectly.
17649         if (!DAG.getTarget().Options.UnsafeFPMath &&
17650             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17651           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17652             break;
17653           std::swap(LHS, RHS);
17654         }
17655         Opcode = X86ISD::FMAX;
17656         break;
17657       case ISD::SETULE:
17658         // Converting this to a max would handle both negative zeros and NaNs
17659         // incorrectly, but we can swap the operands to fix both.
17660         std::swap(LHS, RHS);
17661       case ISD::SETOLT:
17662       case ISD::SETLT:
17663       case ISD::SETLE:
17664         Opcode = X86ISD::FMAX;
17665         break;
17666       }
17667     }
17668
17669     if (Opcode)
17670       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17671   }
17672
17673   EVT CondVT = Cond.getValueType();
17674   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17675       CondVT.getVectorElementType() == MVT::i1) {
17676     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17677     // lowering on AVX-512. In this case we convert it to
17678     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17679     // The same situation for all 128 and 256-bit vectors of i8 and i16
17680     EVT OpVT = LHS.getValueType();
17681     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17682         (OpVT.getVectorElementType() == MVT::i8 ||
17683          OpVT.getVectorElementType() == MVT::i16)) {
17684       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17685       DCI.AddToWorklist(Cond.getNode());
17686       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17687     }
17688   }
17689   // If this is a select between two integer constants, try to do some
17690   // optimizations.
17691   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17692     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17693       // Don't do this for crazy integer types.
17694       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17695         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17696         // so that TrueC (the true value) is larger than FalseC.
17697         bool NeedsCondInvert = false;
17698
17699         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17700             // Efficiently invertible.
17701             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17702              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17703               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17704           NeedsCondInvert = true;
17705           std::swap(TrueC, FalseC);
17706         }
17707
17708         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17709         if (FalseC->getAPIntValue() == 0 &&
17710             TrueC->getAPIntValue().isPowerOf2()) {
17711           if (NeedsCondInvert) // Invert the condition if needed.
17712             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17713                                DAG.getConstant(1, Cond.getValueType()));
17714
17715           // Zero extend the condition if needed.
17716           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17717
17718           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17719           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17720                              DAG.getConstant(ShAmt, MVT::i8));
17721         }
17722
17723         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17724         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17725           if (NeedsCondInvert) // Invert the condition if needed.
17726             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17727                                DAG.getConstant(1, Cond.getValueType()));
17728
17729           // Zero extend the condition if needed.
17730           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17731                              FalseC->getValueType(0), Cond);
17732           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17733                              SDValue(FalseC, 0));
17734         }
17735
17736         // Optimize cases that will turn into an LEA instruction.  This requires
17737         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17738         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17739           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17740           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17741
17742           bool isFastMultiplier = false;
17743           if (Diff < 10) {
17744             switch ((unsigned char)Diff) {
17745               default: break;
17746               case 1:  // result = add base, cond
17747               case 2:  // result = lea base(    , cond*2)
17748               case 3:  // result = lea base(cond, cond*2)
17749               case 4:  // result = lea base(    , cond*4)
17750               case 5:  // result = lea base(cond, cond*4)
17751               case 8:  // result = lea base(    , cond*8)
17752               case 9:  // result = lea base(cond, cond*8)
17753                 isFastMultiplier = true;
17754                 break;
17755             }
17756           }
17757
17758           if (isFastMultiplier) {
17759             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17760             if (NeedsCondInvert) // Invert the condition if needed.
17761               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17762                                  DAG.getConstant(1, Cond.getValueType()));
17763
17764             // Zero extend the condition if needed.
17765             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17766                                Cond);
17767             // Scale the condition by the difference.
17768             if (Diff != 1)
17769               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17770                                  DAG.getConstant(Diff, Cond.getValueType()));
17771
17772             // Add the base if non-zero.
17773             if (FalseC->getAPIntValue() != 0)
17774               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17775                                  SDValue(FalseC, 0));
17776             return Cond;
17777           }
17778         }
17779       }
17780   }
17781
17782   // Canonicalize max and min:
17783   // (x > y) ? x : y -> (x >= y) ? x : y
17784   // (x < y) ? x : y -> (x <= y) ? x : y
17785   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17786   // the need for an extra compare
17787   // against zero. e.g.
17788   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17789   // subl   %esi, %edi
17790   // testl  %edi, %edi
17791   // movl   $0, %eax
17792   // cmovgl %edi, %eax
17793   // =>
17794   // xorl   %eax, %eax
17795   // subl   %esi, $edi
17796   // cmovsl %eax, %edi
17797   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17798       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17799       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17800     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17801     switch (CC) {
17802     default: break;
17803     case ISD::SETLT:
17804     case ISD::SETGT: {
17805       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17806       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17807                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17808       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17809     }
17810     }
17811   }
17812
17813   // Early exit check
17814   if (!TLI.isTypeLegal(VT))
17815     return SDValue();
17816
17817   // Match VSELECTs into subs with unsigned saturation.
17818   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17819       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17820       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17821        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17822     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17823
17824     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17825     // left side invert the predicate to simplify logic below.
17826     SDValue Other;
17827     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17828       Other = RHS;
17829       CC = ISD::getSetCCInverse(CC, true);
17830     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17831       Other = LHS;
17832     }
17833
17834     if (Other.getNode() && Other->getNumOperands() == 2 &&
17835         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17836       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17837       SDValue CondRHS = Cond->getOperand(1);
17838
17839       // Look for a general sub with unsigned saturation first.
17840       // x >= y ? x-y : 0 --> subus x, y
17841       // x >  y ? x-y : 0 --> subus x, y
17842       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17843           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17844         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17845
17846       // If the RHS is a constant we have to reverse the const canonicalization.
17847       // x > C-1 ? x+-C : 0 --> subus x, C
17848       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17849           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17850         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17851         if (CondRHS.getConstantOperandVal(0) == -A-1)
17852           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17853                              DAG.getConstant(-A, VT));
17854       }
17855
17856       // Another special case: If C was a sign bit, the sub has been
17857       // canonicalized into a xor.
17858       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17859       //        it's safe to decanonicalize the xor?
17860       // x s< 0 ? x^C : 0 --> subus x, C
17861       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17862           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17863           isSplatVector(OpRHS.getNode())) {
17864         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17865         if (A.isSignBit())
17866           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17867       }
17868     }
17869   }
17870
17871   // Try to match a min/max vector operation.
17872   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17873     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17874     unsigned Opc = ret.first;
17875     bool NeedSplit = ret.second;
17876
17877     if (Opc && NeedSplit) {
17878       unsigned NumElems = VT.getVectorNumElements();
17879       // Extract the LHS vectors
17880       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17881       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17882
17883       // Extract the RHS vectors
17884       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17885       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17886
17887       // Create min/max for each subvector
17888       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17889       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17890
17891       // Merge the result
17892       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17893     } else if (Opc)
17894       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17895   }
17896
17897   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17898   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17899       // Check if SETCC has already been promoted
17900       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17901       // Check that condition value type matches vselect operand type
17902       CondVT == VT) { 
17903
17904     assert(Cond.getValueType().isVector() &&
17905            "vector select expects a vector selector!");
17906
17907     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17908     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17909
17910     if (!TValIsAllOnes && !FValIsAllZeros) {
17911       // Try invert the condition if true value is not all 1s and false value
17912       // is not all 0s.
17913       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17914       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17915
17916       if (TValIsAllZeros || FValIsAllOnes) {
17917         SDValue CC = Cond.getOperand(2);
17918         ISD::CondCode NewCC =
17919           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17920                                Cond.getOperand(0).getValueType().isInteger());
17921         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17922         std::swap(LHS, RHS);
17923         TValIsAllOnes = FValIsAllOnes;
17924         FValIsAllZeros = TValIsAllZeros;
17925       }
17926     }
17927
17928     if (TValIsAllOnes || FValIsAllZeros) {
17929       SDValue Ret;
17930
17931       if (TValIsAllOnes && FValIsAllZeros)
17932         Ret = Cond;
17933       else if (TValIsAllOnes)
17934         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17935                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17936       else if (FValIsAllZeros)
17937         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17938                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17939
17940       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17941     }
17942   }
17943
17944   // Try to fold this VSELECT into a MOVSS/MOVSD
17945   if (N->getOpcode() == ISD::VSELECT &&
17946       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17947     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17948         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17949       bool CanFold = false;
17950       unsigned NumElems = Cond.getNumOperands();
17951       SDValue A = LHS;
17952       SDValue B = RHS;
17953       
17954       if (isZero(Cond.getOperand(0))) {
17955         CanFold = true;
17956
17957         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17958         // fold (vselect <0,-1> -> (movsd A, B)
17959         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17960           CanFold = isAllOnes(Cond.getOperand(i));
17961       } else if (isAllOnes(Cond.getOperand(0))) {
17962         CanFold = true;
17963         std::swap(A, B);
17964
17965         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17966         // fold (vselect <-1,0> -> (movsd B, A)
17967         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17968           CanFold = isZero(Cond.getOperand(i));
17969       }
17970
17971       if (CanFold) {
17972         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17973           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17974         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17975       }
17976
17977       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17978         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17979         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17980         //                             (v2i64 (bitcast B)))))
17981         //
17982         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17983         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17984         //                             (v2f64 (bitcast B)))))
17985         //
17986         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17987         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17988         //                             (v2i64 (bitcast A)))))
17989         //
17990         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17991         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17992         //                             (v2f64 (bitcast A)))))
17993
17994         CanFold = (isZero(Cond.getOperand(0)) &&
17995                    isZero(Cond.getOperand(1)) &&
17996                    isAllOnes(Cond.getOperand(2)) &&
17997                    isAllOnes(Cond.getOperand(3)));
17998
17999         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18000             isAllOnes(Cond.getOperand(1)) &&
18001             isZero(Cond.getOperand(2)) &&
18002             isZero(Cond.getOperand(3))) {
18003           CanFold = true;
18004           std::swap(LHS, RHS);
18005         }
18006
18007         if (CanFold) {
18008           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18009           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18010           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18011           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18012                                                 NewB, DAG);
18013           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18014         }
18015       }
18016     }
18017   }
18018
18019   // If we know that this node is legal then we know that it is going to be
18020   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18021   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18022   // to simplify previous instructions.
18023   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18024       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
18025     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18026
18027     // Don't optimize vector selects that map to mask-registers.
18028     if (BitWidth == 1)
18029       return SDValue();
18030
18031     // Check all uses of that condition operand to check whether it will be
18032     // consumed by non-BLEND instructions, which may depend on all bits are set
18033     // properly.
18034     for (SDNode::use_iterator I = Cond->use_begin(),
18035                               E = Cond->use_end(); I != E; ++I)
18036       if (I->getOpcode() != ISD::VSELECT)
18037         // TODO: Add other opcodes eventually lowered into BLEND.
18038         return SDValue();
18039
18040     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18041     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18042
18043     APInt KnownZero, KnownOne;
18044     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18045                                           DCI.isBeforeLegalizeOps());
18046     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18047         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18048       DCI.CommitTargetLoweringOpt(TLO);
18049   }
18050
18051   return SDValue();
18052 }
18053
18054 // Check whether a boolean test is testing a boolean value generated by
18055 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18056 // code.
18057 //
18058 // Simplify the following patterns:
18059 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18060 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18061 // to (Op EFLAGS Cond)
18062 //
18063 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18064 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18065 // to (Op EFLAGS !Cond)
18066 //
18067 // where Op could be BRCOND or CMOV.
18068 //
18069 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18070   // Quit if not CMP and SUB with its value result used.
18071   if (Cmp.getOpcode() != X86ISD::CMP &&
18072       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18073       return SDValue();
18074
18075   // Quit if not used as a boolean value.
18076   if (CC != X86::COND_E && CC != X86::COND_NE)
18077     return SDValue();
18078
18079   // Check CMP operands. One of them should be 0 or 1 and the other should be
18080   // an SetCC or extended from it.
18081   SDValue Op1 = Cmp.getOperand(0);
18082   SDValue Op2 = Cmp.getOperand(1);
18083
18084   SDValue SetCC;
18085   const ConstantSDNode* C = nullptr;
18086   bool needOppositeCond = (CC == X86::COND_E);
18087   bool checkAgainstTrue = false; // Is it a comparison against 1?
18088
18089   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18090     SetCC = Op2;
18091   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18092     SetCC = Op1;
18093   else // Quit if all operands are not constants.
18094     return SDValue();
18095
18096   if (C->getZExtValue() == 1) {
18097     needOppositeCond = !needOppositeCond;
18098     checkAgainstTrue = true;
18099   } else if (C->getZExtValue() != 0)
18100     // Quit if the constant is neither 0 or 1.
18101     return SDValue();
18102
18103   bool truncatedToBoolWithAnd = false;
18104   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18105   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18106          SetCC.getOpcode() == ISD::TRUNCATE ||
18107          SetCC.getOpcode() == ISD::AND) {
18108     if (SetCC.getOpcode() == ISD::AND) {
18109       int OpIdx = -1;
18110       ConstantSDNode *CS;
18111       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18112           CS->getZExtValue() == 1)
18113         OpIdx = 1;
18114       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18115           CS->getZExtValue() == 1)
18116         OpIdx = 0;
18117       if (OpIdx == -1)
18118         break;
18119       SetCC = SetCC.getOperand(OpIdx);
18120       truncatedToBoolWithAnd = true;
18121     } else
18122       SetCC = SetCC.getOperand(0);
18123   }
18124
18125   switch (SetCC.getOpcode()) {
18126   case X86ISD::SETCC_CARRY:
18127     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18128     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18129     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18130     // truncated to i1 using 'and'.
18131     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18132       break;
18133     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18134            "Invalid use of SETCC_CARRY!");
18135     // FALL THROUGH
18136   case X86ISD::SETCC:
18137     // Set the condition code or opposite one if necessary.
18138     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18139     if (needOppositeCond)
18140       CC = X86::GetOppositeBranchCondition(CC);
18141     return SetCC.getOperand(1);
18142   case X86ISD::CMOV: {
18143     // Check whether false/true value has canonical one, i.e. 0 or 1.
18144     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18145     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18146     // Quit if true value is not a constant.
18147     if (!TVal)
18148       return SDValue();
18149     // Quit if false value is not a constant.
18150     if (!FVal) {
18151       SDValue Op = SetCC.getOperand(0);
18152       // Skip 'zext' or 'trunc' node.
18153       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18154           Op.getOpcode() == ISD::TRUNCATE)
18155         Op = Op.getOperand(0);
18156       // A special case for rdrand/rdseed, where 0 is set if false cond is
18157       // found.
18158       if ((Op.getOpcode() != X86ISD::RDRAND &&
18159            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18160         return SDValue();
18161     }
18162     // Quit if false value is not the constant 0 or 1.
18163     bool FValIsFalse = true;
18164     if (FVal && FVal->getZExtValue() != 0) {
18165       if (FVal->getZExtValue() != 1)
18166         return SDValue();
18167       // If FVal is 1, opposite cond is needed.
18168       needOppositeCond = !needOppositeCond;
18169       FValIsFalse = false;
18170     }
18171     // Quit if TVal is not the constant opposite of FVal.
18172     if (FValIsFalse && TVal->getZExtValue() != 1)
18173       return SDValue();
18174     if (!FValIsFalse && TVal->getZExtValue() != 0)
18175       return SDValue();
18176     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18177     if (needOppositeCond)
18178       CC = X86::GetOppositeBranchCondition(CC);
18179     return SetCC.getOperand(3);
18180   }
18181   }
18182
18183   return SDValue();
18184 }
18185
18186 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18187 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18188                                   TargetLowering::DAGCombinerInfo &DCI,
18189                                   const X86Subtarget *Subtarget) {
18190   SDLoc DL(N);
18191
18192   // If the flag operand isn't dead, don't touch this CMOV.
18193   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18194     return SDValue();
18195
18196   SDValue FalseOp = N->getOperand(0);
18197   SDValue TrueOp = N->getOperand(1);
18198   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18199   SDValue Cond = N->getOperand(3);
18200
18201   if (CC == X86::COND_E || CC == X86::COND_NE) {
18202     switch (Cond.getOpcode()) {
18203     default: break;
18204     case X86ISD::BSR:
18205     case X86ISD::BSF:
18206       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18207       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18208         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18209     }
18210   }
18211
18212   SDValue Flags;
18213
18214   Flags = checkBoolTestSetCCCombine(Cond, CC);
18215   if (Flags.getNode() &&
18216       // Extra check as FCMOV only supports a subset of X86 cond.
18217       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18218     SDValue Ops[] = { FalseOp, TrueOp,
18219                       DAG.getConstant(CC, MVT::i8), Flags };
18220     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18221   }
18222
18223   // If this is a select between two integer constants, try to do some
18224   // optimizations.  Note that the operands are ordered the opposite of SELECT
18225   // operands.
18226   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18227     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18228       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18229       // larger than FalseC (the false value).
18230       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18231         CC = X86::GetOppositeBranchCondition(CC);
18232         std::swap(TrueC, FalseC);
18233         std::swap(TrueOp, FalseOp);
18234       }
18235
18236       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18237       // This is efficient for any integer data type (including i8/i16) and
18238       // shift amount.
18239       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18240         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18241                            DAG.getConstant(CC, MVT::i8), Cond);
18242
18243         // Zero extend the condition if needed.
18244         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18245
18246         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18247         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18248                            DAG.getConstant(ShAmt, MVT::i8));
18249         if (N->getNumValues() == 2)  // Dead flag value?
18250           return DCI.CombineTo(N, Cond, SDValue());
18251         return Cond;
18252       }
18253
18254       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18255       // for any integer data type, including i8/i16.
18256       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18257         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18258                            DAG.getConstant(CC, MVT::i8), Cond);
18259
18260         // Zero extend the condition if needed.
18261         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18262                            FalseC->getValueType(0), Cond);
18263         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18264                            SDValue(FalseC, 0));
18265
18266         if (N->getNumValues() == 2)  // Dead flag value?
18267           return DCI.CombineTo(N, Cond, SDValue());
18268         return Cond;
18269       }
18270
18271       // Optimize cases that will turn into an LEA instruction.  This requires
18272       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18273       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18274         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18275         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18276
18277         bool isFastMultiplier = false;
18278         if (Diff < 10) {
18279           switch ((unsigned char)Diff) {
18280           default: break;
18281           case 1:  // result = add base, cond
18282           case 2:  // result = lea base(    , cond*2)
18283           case 3:  // result = lea base(cond, cond*2)
18284           case 4:  // result = lea base(    , cond*4)
18285           case 5:  // result = lea base(cond, cond*4)
18286           case 8:  // result = lea base(    , cond*8)
18287           case 9:  // result = lea base(cond, cond*8)
18288             isFastMultiplier = true;
18289             break;
18290           }
18291         }
18292
18293         if (isFastMultiplier) {
18294           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18295           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18296                              DAG.getConstant(CC, MVT::i8), Cond);
18297           // Zero extend the condition if needed.
18298           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18299                              Cond);
18300           // Scale the condition by the difference.
18301           if (Diff != 1)
18302             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18303                                DAG.getConstant(Diff, Cond.getValueType()));
18304
18305           // Add the base if non-zero.
18306           if (FalseC->getAPIntValue() != 0)
18307             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18308                                SDValue(FalseC, 0));
18309           if (N->getNumValues() == 2)  // Dead flag value?
18310             return DCI.CombineTo(N, Cond, SDValue());
18311           return Cond;
18312         }
18313       }
18314     }
18315   }
18316
18317   // Handle these cases:
18318   //   (select (x != c), e, c) -> select (x != c), e, x),
18319   //   (select (x == c), c, e) -> select (x == c), x, e)
18320   // where the c is an integer constant, and the "select" is the combination
18321   // of CMOV and CMP.
18322   //
18323   // The rationale for this change is that the conditional-move from a constant
18324   // needs two instructions, however, conditional-move from a register needs
18325   // only one instruction.
18326   //
18327   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18328   //  some instruction-combining opportunities. This opt needs to be
18329   //  postponed as late as possible.
18330   //
18331   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18332     // the DCI.xxxx conditions are provided to postpone the optimization as
18333     // late as possible.
18334
18335     ConstantSDNode *CmpAgainst = nullptr;
18336     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18337         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18338         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18339
18340       if (CC == X86::COND_NE &&
18341           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18342         CC = X86::GetOppositeBranchCondition(CC);
18343         std::swap(TrueOp, FalseOp);
18344       }
18345
18346       if (CC == X86::COND_E &&
18347           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18348         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18349                           DAG.getConstant(CC, MVT::i8), Cond };
18350         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18351       }
18352     }
18353   }
18354
18355   return SDValue();
18356 }
18357
18358 /// PerformMulCombine - Optimize a single multiply with constant into two
18359 /// in order to implement it with two cheaper instructions, e.g.
18360 /// LEA + SHL, LEA + LEA.
18361 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18362                                  TargetLowering::DAGCombinerInfo &DCI) {
18363   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18364     return SDValue();
18365
18366   EVT VT = N->getValueType(0);
18367   if (VT != MVT::i64)
18368     return SDValue();
18369
18370   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18371   if (!C)
18372     return SDValue();
18373   uint64_t MulAmt = C->getZExtValue();
18374   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18375     return SDValue();
18376
18377   uint64_t MulAmt1 = 0;
18378   uint64_t MulAmt2 = 0;
18379   if ((MulAmt % 9) == 0) {
18380     MulAmt1 = 9;
18381     MulAmt2 = MulAmt / 9;
18382   } else if ((MulAmt % 5) == 0) {
18383     MulAmt1 = 5;
18384     MulAmt2 = MulAmt / 5;
18385   } else if ((MulAmt % 3) == 0) {
18386     MulAmt1 = 3;
18387     MulAmt2 = MulAmt / 3;
18388   }
18389   if (MulAmt2 &&
18390       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18391     SDLoc DL(N);
18392
18393     if (isPowerOf2_64(MulAmt2) &&
18394         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18395       // If second multiplifer is pow2, issue it first. We want the multiply by
18396       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18397       // is an add.
18398       std::swap(MulAmt1, MulAmt2);
18399
18400     SDValue NewMul;
18401     if (isPowerOf2_64(MulAmt1))
18402       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18403                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18404     else
18405       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18406                            DAG.getConstant(MulAmt1, VT));
18407
18408     if (isPowerOf2_64(MulAmt2))
18409       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18410                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18411     else
18412       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18413                            DAG.getConstant(MulAmt2, VT));
18414
18415     // Do not add new nodes to DAG combiner worklist.
18416     DCI.CombineTo(N, NewMul, false);
18417   }
18418   return SDValue();
18419 }
18420
18421 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18422   SDValue N0 = N->getOperand(0);
18423   SDValue N1 = N->getOperand(1);
18424   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18425   EVT VT = N0.getValueType();
18426
18427   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18428   // since the result of setcc_c is all zero's or all ones.
18429   if (VT.isInteger() && !VT.isVector() &&
18430       N1C && N0.getOpcode() == ISD::AND &&
18431       N0.getOperand(1).getOpcode() == ISD::Constant) {
18432     SDValue N00 = N0.getOperand(0);
18433     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18434         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18435           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18436          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18437       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18438       APInt ShAmt = N1C->getAPIntValue();
18439       Mask = Mask.shl(ShAmt);
18440       if (Mask != 0)
18441         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18442                            N00, DAG.getConstant(Mask, VT));
18443     }
18444   }
18445
18446   // Hardware support for vector shifts is sparse which makes us scalarize the
18447   // vector operations in many cases. Also, on sandybridge ADD is faster than
18448   // shl.
18449   // (shl V, 1) -> add V,V
18450   if (isSplatVector(N1.getNode())) {
18451     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18452     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18453     // We shift all of the values by one. In many cases we do not have
18454     // hardware support for this operation. This is better expressed as an ADD
18455     // of two values.
18456     if (N1C && (1 == N1C->getZExtValue())) {
18457       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18458     }
18459   }
18460
18461   return SDValue();
18462 }
18463
18464 /// \brief Returns a vector of 0s if the node in input is a vector logical
18465 /// shift by a constant amount which is known to be bigger than or equal
18466 /// to the vector element size in bits.
18467 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18468                                       const X86Subtarget *Subtarget) {
18469   EVT VT = N->getValueType(0);
18470
18471   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18472       (!Subtarget->hasInt256() ||
18473        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18474     return SDValue();
18475
18476   SDValue Amt = N->getOperand(1);
18477   SDLoc DL(N);
18478   if (isSplatVector(Amt.getNode())) {
18479     SDValue SclrAmt = Amt->getOperand(0);
18480     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18481       APInt ShiftAmt = C->getAPIntValue();
18482       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18483
18484       // SSE2/AVX2 logical shifts always return a vector of 0s
18485       // if the shift amount is bigger than or equal to
18486       // the element size. The constant shift amount will be
18487       // encoded as a 8-bit immediate.
18488       if (ShiftAmt.trunc(8).uge(MaxAmount))
18489         return getZeroVector(VT, Subtarget, DAG, DL);
18490     }
18491   }
18492
18493   return SDValue();
18494 }
18495
18496 /// PerformShiftCombine - Combine shifts.
18497 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18498                                    TargetLowering::DAGCombinerInfo &DCI,
18499                                    const X86Subtarget *Subtarget) {
18500   if (N->getOpcode() == ISD::SHL) {
18501     SDValue V = PerformSHLCombine(N, DAG);
18502     if (V.getNode()) return V;
18503   }
18504
18505   if (N->getOpcode() != ISD::SRA) {
18506     // Try to fold this logical shift into a zero vector.
18507     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18508     if (V.getNode()) return V;
18509   }
18510
18511   return SDValue();
18512 }
18513
18514 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18515 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18516 // and friends.  Likewise for OR -> CMPNEQSS.
18517 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18518                             TargetLowering::DAGCombinerInfo &DCI,
18519                             const X86Subtarget *Subtarget) {
18520   unsigned opcode;
18521
18522   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18523   // we're requiring SSE2 for both.
18524   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18525     SDValue N0 = N->getOperand(0);
18526     SDValue N1 = N->getOperand(1);
18527     SDValue CMP0 = N0->getOperand(1);
18528     SDValue CMP1 = N1->getOperand(1);
18529     SDLoc DL(N);
18530
18531     // The SETCCs should both refer to the same CMP.
18532     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18533       return SDValue();
18534
18535     SDValue CMP00 = CMP0->getOperand(0);
18536     SDValue CMP01 = CMP0->getOperand(1);
18537     EVT     VT    = CMP00.getValueType();
18538
18539     if (VT == MVT::f32 || VT == MVT::f64) {
18540       bool ExpectingFlags = false;
18541       // Check for any users that want flags:
18542       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18543            !ExpectingFlags && UI != UE; ++UI)
18544         switch (UI->getOpcode()) {
18545         default:
18546         case ISD::BR_CC:
18547         case ISD::BRCOND:
18548         case ISD::SELECT:
18549           ExpectingFlags = true;
18550           break;
18551         case ISD::CopyToReg:
18552         case ISD::SIGN_EXTEND:
18553         case ISD::ZERO_EXTEND:
18554         case ISD::ANY_EXTEND:
18555           break;
18556         }
18557
18558       if (!ExpectingFlags) {
18559         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18560         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18561
18562         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18563           X86::CondCode tmp = cc0;
18564           cc0 = cc1;
18565           cc1 = tmp;
18566         }
18567
18568         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18569             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18570           // FIXME: need symbolic constants for these magic numbers.
18571           // See X86ATTInstPrinter.cpp:printSSECC().
18572           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18573           if (Subtarget->hasAVX512()) {
18574             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18575                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18576             if (N->getValueType(0) != MVT::i1)
18577               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18578                                  FSetCC);
18579             return FSetCC;
18580           }
18581           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18582                                               CMP00.getValueType(), CMP00, CMP01,
18583                                               DAG.getConstant(x86cc, MVT::i8));
18584
18585           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18586           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18587
18588           if (is64BitFP && !Subtarget->is64Bit()) {
18589             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18590             // 64-bit integer, since that's not a legal type. Since
18591             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18592             // bits, but can do this little dance to extract the lowest 32 bits
18593             // and work with those going forward.
18594             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18595                                            OnesOrZeroesF);
18596             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18597                                            Vector64);
18598             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18599                                         Vector32, DAG.getIntPtrConstant(0));
18600             IntVT = MVT::i32;
18601           }
18602
18603           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18604           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18605                                       DAG.getConstant(1, IntVT));
18606           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18607           return OneBitOfTruth;
18608         }
18609       }
18610     }
18611   }
18612   return SDValue();
18613 }
18614
18615 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18616 /// so it can be folded inside ANDNP.
18617 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18618   EVT VT = N->getValueType(0);
18619
18620   // Match direct AllOnes for 128 and 256-bit vectors
18621   if (ISD::isBuildVectorAllOnes(N))
18622     return true;
18623
18624   // Look through a bit convert.
18625   if (N->getOpcode() == ISD::BITCAST)
18626     N = N->getOperand(0).getNode();
18627
18628   // Sometimes the operand may come from a insert_subvector building a 256-bit
18629   // allones vector
18630   if (VT.is256BitVector() &&
18631       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18632     SDValue V1 = N->getOperand(0);
18633     SDValue V2 = N->getOperand(1);
18634
18635     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18636         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18637         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18638         ISD::isBuildVectorAllOnes(V2.getNode()))
18639       return true;
18640   }
18641
18642   return false;
18643 }
18644
18645 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18646 // register. In most cases we actually compare or select YMM-sized registers
18647 // and mixing the two types creates horrible code. This method optimizes
18648 // some of the transition sequences.
18649 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18650                                  TargetLowering::DAGCombinerInfo &DCI,
18651                                  const X86Subtarget *Subtarget) {
18652   EVT VT = N->getValueType(0);
18653   if (!VT.is256BitVector())
18654     return SDValue();
18655
18656   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18657           N->getOpcode() == ISD::ZERO_EXTEND ||
18658           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18659
18660   SDValue Narrow = N->getOperand(0);
18661   EVT NarrowVT = Narrow->getValueType(0);
18662   if (!NarrowVT.is128BitVector())
18663     return SDValue();
18664
18665   if (Narrow->getOpcode() != ISD::XOR &&
18666       Narrow->getOpcode() != ISD::AND &&
18667       Narrow->getOpcode() != ISD::OR)
18668     return SDValue();
18669
18670   SDValue N0  = Narrow->getOperand(0);
18671   SDValue N1  = Narrow->getOperand(1);
18672   SDLoc DL(Narrow);
18673
18674   // The Left side has to be a trunc.
18675   if (N0.getOpcode() != ISD::TRUNCATE)
18676     return SDValue();
18677
18678   // The type of the truncated inputs.
18679   EVT WideVT = N0->getOperand(0)->getValueType(0);
18680   if (WideVT != VT)
18681     return SDValue();
18682
18683   // The right side has to be a 'trunc' or a constant vector.
18684   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18685   bool RHSConst = (isSplatVector(N1.getNode()) &&
18686                    isa<ConstantSDNode>(N1->getOperand(0)));
18687   if (!RHSTrunc && !RHSConst)
18688     return SDValue();
18689
18690   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18691
18692   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18693     return SDValue();
18694
18695   // Set N0 and N1 to hold the inputs to the new wide operation.
18696   N0 = N0->getOperand(0);
18697   if (RHSConst) {
18698     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18699                      N1->getOperand(0));
18700     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18701     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18702   } else if (RHSTrunc) {
18703     N1 = N1->getOperand(0);
18704   }
18705
18706   // Generate the wide operation.
18707   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18708   unsigned Opcode = N->getOpcode();
18709   switch (Opcode) {
18710   case ISD::ANY_EXTEND:
18711     return Op;
18712   case ISD::ZERO_EXTEND: {
18713     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18714     APInt Mask = APInt::getAllOnesValue(InBits);
18715     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18716     return DAG.getNode(ISD::AND, DL, VT,
18717                        Op, DAG.getConstant(Mask, VT));
18718   }
18719   case ISD::SIGN_EXTEND:
18720     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18721                        Op, DAG.getValueType(NarrowVT));
18722   default:
18723     llvm_unreachable("Unexpected opcode");
18724   }
18725 }
18726
18727 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18728                                  TargetLowering::DAGCombinerInfo &DCI,
18729                                  const X86Subtarget *Subtarget) {
18730   EVT VT = N->getValueType(0);
18731   if (DCI.isBeforeLegalizeOps())
18732     return SDValue();
18733
18734   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18735   if (R.getNode())
18736     return R;
18737
18738   // Create BEXTR instructions
18739   // BEXTR is ((X >> imm) & (2**size-1))
18740   if (VT == MVT::i32 || VT == MVT::i64) {
18741     SDValue N0 = N->getOperand(0);
18742     SDValue N1 = N->getOperand(1);
18743     SDLoc DL(N);
18744
18745     // Check for BEXTR.
18746     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18747         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18748       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18749       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18750       if (MaskNode && ShiftNode) {
18751         uint64_t Mask = MaskNode->getZExtValue();
18752         uint64_t Shift = ShiftNode->getZExtValue();
18753         if (isMask_64(Mask)) {
18754           uint64_t MaskSize = CountPopulation_64(Mask);
18755           if (Shift + MaskSize <= VT.getSizeInBits())
18756             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18757                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18758         }
18759       }
18760     } // BEXTR
18761
18762     return SDValue();
18763   }
18764
18765   // Want to form ANDNP nodes:
18766   // 1) In the hopes of then easily combining them with OR and AND nodes
18767   //    to form PBLEND/PSIGN.
18768   // 2) To match ANDN packed intrinsics
18769   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18770     return SDValue();
18771
18772   SDValue N0 = N->getOperand(0);
18773   SDValue N1 = N->getOperand(1);
18774   SDLoc DL(N);
18775
18776   // Check LHS for vnot
18777   if (N0.getOpcode() == ISD::XOR &&
18778       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18779       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18780     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18781
18782   // Check RHS for vnot
18783   if (N1.getOpcode() == ISD::XOR &&
18784       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18785       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18786     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18787
18788   return SDValue();
18789 }
18790
18791 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18792                                 TargetLowering::DAGCombinerInfo &DCI,
18793                                 const X86Subtarget *Subtarget) {
18794   if (DCI.isBeforeLegalizeOps())
18795     return SDValue();
18796
18797   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18798   if (R.getNode())
18799     return R;
18800
18801   SDValue N0 = N->getOperand(0);
18802   SDValue N1 = N->getOperand(1);
18803   EVT VT = N->getValueType(0);
18804
18805   // look for psign/blend
18806   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18807     if (!Subtarget->hasSSSE3() ||
18808         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18809       return SDValue();
18810
18811     // Canonicalize pandn to RHS
18812     if (N0.getOpcode() == X86ISD::ANDNP)
18813       std::swap(N0, N1);
18814     // or (and (m, y), (pandn m, x))
18815     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18816       SDValue Mask = N1.getOperand(0);
18817       SDValue X    = N1.getOperand(1);
18818       SDValue Y;
18819       if (N0.getOperand(0) == Mask)
18820         Y = N0.getOperand(1);
18821       if (N0.getOperand(1) == Mask)
18822         Y = N0.getOperand(0);
18823
18824       // Check to see if the mask appeared in both the AND and ANDNP and
18825       if (!Y.getNode())
18826         return SDValue();
18827
18828       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18829       // Look through mask bitcast.
18830       if (Mask.getOpcode() == ISD::BITCAST)
18831         Mask = Mask.getOperand(0);
18832       if (X.getOpcode() == ISD::BITCAST)
18833         X = X.getOperand(0);
18834       if (Y.getOpcode() == ISD::BITCAST)
18835         Y = Y.getOperand(0);
18836
18837       EVT MaskVT = Mask.getValueType();
18838
18839       // Validate that the Mask operand is a vector sra node.
18840       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18841       // there is no psrai.b
18842       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18843       unsigned SraAmt = ~0;
18844       if (Mask.getOpcode() == ISD::SRA) {
18845         SDValue Amt = Mask.getOperand(1);
18846         if (isSplatVector(Amt.getNode())) {
18847           SDValue SclrAmt = Amt->getOperand(0);
18848           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18849             SraAmt = C->getZExtValue();
18850         }
18851       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18852         SDValue SraC = Mask.getOperand(1);
18853         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18854       }
18855       if ((SraAmt + 1) != EltBits)
18856         return SDValue();
18857
18858       SDLoc DL(N);
18859
18860       // Now we know we at least have a plendvb with the mask val.  See if
18861       // we can form a psignb/w/d.
18862       // psign = x.type == y.type == mask.type && y = sub(0, x);
18863       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18864           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18865           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18866         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18867                "Unsupported VT for PSIGN");
18868         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18869         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18870       }
18871       // PBLENDVB only available on SSE 4.1
18872       if (!Subtarget->hasSSE41())
18873         return SDValue();
18874
18875       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18876
18877       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18878       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18879       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18880       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18881       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18882     }
18883   }
18884
18885   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18886     return SDValue();
18887
18888   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18889   MachineFunction &MF = DAG.getMachineFunction();
18890   bool OptForSize = MF.getFunction()->getAttributes().
18891     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18892
18893   // SHLD/SHRD instructions have lower register pressure, but on some
18894   // platforms they have higher latency than the equivalent
18895   // series of shifts/or that would otherwise be generated.
18896   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18897   // have higher latencies and we are not optimizing for size.
18898   if (!OptForSize && Subtarget->isSHLDSlow())
18899     return SDValue();
18900
18901   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18902     std::swap(N0, N1);
18903   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18904     return SDValue();
18905   if (!N0.hasOneUse() || !N1.hasOneUse())
18906     return SDValue();
18907
18908   SDValue ShAmt0 = N0.getOperand(1);
18909   if (ShAmt0.getValueType() != MVT::i8)
18910     return SDValue();
18911   SDValue ShAmt1 = N1.getOperand(1);
18912   if (ShAmt1.getValueType() != MVT::i8)
18913     return SDValue();
18914   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18915     ShAmt0 = ShAmt0.getOperand(0);
18916   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18917     ShAmt1 = ShAmt1.getOperand(0);
18918
18919   SDLoc DL(N);
18920   unsigned Opc = X86ISD::SHLD;
18921   SDValue Op0 = N0.getOperand(0);
18922   SDValue Op1 = N1.getOperand(0);
18923   if (ShAmt0.getOpcode() == ISD::SUB) {
18924     Opc = X86ISD::SHRD;
18925     std::swap(Op0, Op1);
18926     std::swap(ShAmt0, ShAmt1);
18927   }
18928
18929   unsigned Bits = VT.getSizeInBits();
18930   if (ShAmt1.getOpcode() == ISD::SUB) {
18931     SDValue Sum = ShAmt1.getOperand(0);
18932     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18933       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18934       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18935         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18936       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18937         return DAG.getNode(Opc, DL, VT,
18938                            Op0, Op1,
18939                            DAG.getNode(ISD::TRUNCATE, DL,
18940                                        MVT::i8, ShAmt0));
18941     }
18942   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18943     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18944     if (ShAmt0C &&
18945         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18946       return DAG.getNode(Opc, DL, VT,
18947                          N0.getOperand(0), N1.getOperand(0),
18948                          DAG.getNode(ISD::TRUNCATE, DL,
18949                                        MVT::i8, ShAmt0));
18950   }
18951
18952   return SDValue();
18953 }
18954
18955 // Generate NEG and CMOV for integer abs.
18956 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18957   EVT VT = N->getValueType(0);
18958
18959   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18960   // 8-bit integer abs to NEG and CMOV.
18961   if (VT.isInteger() && VT.getSizeInBits() == 8)
18962     return SDValue();
18963
18964   SDValue N0 = N->getOperand(0);
18965   SDValue N1 = N->getOperand(1);
18966   SDLoc DL(N);
18967
18968   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18969   // and change it to SUB and CMOV.
18970   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18971       N0.getOpcode() == ISD::ADD &&
18972       N0.getOperand(1) == N1 &&
18973       N1.getOpcode() == ISD::SRA &&
18974       N1.getOperand(0) == N0.getOperand(0))
18975     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18976       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18977         // Generate SUB & CMOV.
18978         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18979                                   DAG.getConstant(0, VT), N0.getOperand(0));
18980
18981         SDValue Ops[] = { N0.getOperand(0), Neg,
18982                           DAG.getConstant(X86::COND_GE, MVT::i8),
18983                           SDValue(Neg.getNode(), 1) };
18984         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18985       }
18986   return SDValue();
18987 }
18988
18989 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18990 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18991                                  TargetLowering::DAGCombinerInfo &DCI,
18992                                  const X86Subtarget *Subtarget) {
18993   if (DCI.isBeforeLegalizeOps())
18994     return SDValue();
18995
18996   if (Subtarget->hasCMov()) {
18997     SDValue RV = performIntegerAbsCombine(N, DAG);
18998     if (RV.getNode())
18999       return RV;
19000   }
19001
19002   return SDValue();
19003 }
19004
19005 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19006 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19007                                   TargetLowering::DAGCombinerInfo &DCI,
19008                                   const X86Subtarget *Subtarget) {
19009   LoadSDNode *Ld = cast<LoadSDNode>(N);
19010   EVT RegVT = Ld->getValueType(0);
19011   EVT MemVT = Ld->getMemoryVT();
19012   SDLoc dl(Ld);
19013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19014   unsigned RegSz = RegVT.getSizeInBits();
19015
19016   // On Sandybridge unaligned 256bit loads are inefficient.
19017   ISD::LoadExtType Ext = Ld->getExtensionType();
19018   unsigned Alignment = Ld->getAlignment();
19019   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19020   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19021       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19022     unsigned NumElems = RegVT.getVectorNumElements();
19023     if (NumElems < 2)
19024       return SDValue();
19025
19026     SDValue Ptr = Ld->getBasePtr();
19027     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19028
19029     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19030                                   NumElems/2);
19031     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19032                                 Ld->getPointerInfo(), Ld->isVolatile(),
19033                                 Ld->isNonTemporal(), Ld->isInvariant(),
19034                                 Alignment);
19035     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19036     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19037                                 Ld->getPointerInfo(), Ld->isVolatile(),
19038                                 Ld->isNonTemporal(), Ld->isInvariant(),
19039                                 std::min(16U, Alignment));
19040     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19041                              Load1.getValue(1),
19042                              Load2.getValue(1));
19043
19044     SDValue NewVec = DAG.getUNDEF(RegVT);
19045     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19046     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19047     return DCI.CombineTo(N, NewVec, TF, true);
19048   }
19049
19050   // If this is a vector EXT Load then attempt to optimize it using a
19051   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19052   // expansion is still better than scalar code.
19053   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19054   // emit a shuffle and a arithmetic shift.
19055   // TODO: It is possible to support ZExt by zeroing the undef values
19056   // during the shuffle phase or after the shuffle.
19057   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19058       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19059     assert(MemVT != RegVT && "Cannot extend to the same type");
19060     assert(MemVT.isVector() && "Must load a vector from memory");
19061
19062     unsigned NumElems = RegVT.getVectorNumElements();
19063     unsigned MemSz = MemVT.getSizeInBits();
19064     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19065
19066     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19067       return SDValue();
19068
19069     // All sizes must be a power of two.
19070     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19071       return SDValue();
19072
19073     // Attempt to load the original value using scalar loads.
19074     // Find the largest scalar type that divides the total loaded size.
19075     MVT SclrLoadTy = MVT::i8;
19076     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19077          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19078       MVT Tp = (MVT::SimpleValueType)tp;
19079       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19080         SclrLoadTy = Tp;
19081       }
19082     }
19083
19084     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19085     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19086         (64 <= MemSz))
19087       SclrLoadTy = MVT::f64;
19088
19089     // Calculate the number of scalar loads that we need to perform
19090     // in order to load our vector from memory.
19091     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19092     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19093       return SDValue();
19094
19095     unsigned loadRegZize = RegSz;
19096     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19097       loadRegZize /= 2;
19098
19099     // Represent our vector as a sequence of elements which are the
19100     // largest scalar that we can load.
19101     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19102       loadRegZize/SclrLoadTy.getSizeInBits());
19103
19104     // Represent the data using the same element type that is stored in
19105     // memory. In practice, we ''widen'' MemVT.
19106     EVT WideVecVT =
19107           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19108                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19109
19110     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19111       "Invalid vector type");
19112
19113     // We can't shuffle using an illegal type.
19114     if (!TLI.isTypeLegal(WideVecVT))
19115       return SDValue();
19116
19117     SmallVector<SDValue, 8> Chains;
19118     SDValue Ptr = Ld->getBasePtr();
19119     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19120                                         TLI.getPointerTy());
19121     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19122
19123     for (unsigned i = 0; i < NumLoads; ++i) {
19124       // Perform a single load.
19125       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19126                                        Ptr, Ld->getPointerInfo(),
19127                                        Ld->isVolatile(), Ld->isNonTemporal(),
19128                                        Ld->isInvariant(), Ld->getAlignment());
19129       Chains.push_back(ScalarLoad.getValue(1));
19130       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19131       // another round of DAGCombining.
19132       if (i == 0)
19133         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19134       else
19135         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19136                           ScalarLoad, DAG.getIntPtrConstant(i));
19137
19138       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19139     }
19140
19141     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19142
19143     // Bitcast the loaded value to a vector of the original element type, in
19144     // the size of the target vector type.
19145     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19146     unsigned SizeRatio = RegSz/MemSz;
19147
19148     if (Ext == ISD::SEXTLOAD) {
19149       // If we have SSE4.1 we can directly emit a VSEXT node.
19150       if (Subtarget->hasSSE41()) {
19151         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19152         return DCI.CombineTo(N, Sext, TF, true);
19153       }
19154
19155       // Otherwise we'll shuffle the small elements in the high bits of the
19156       // larger type and perform an arithmetic shift. If the shift is not legal
19157       // it's better to scalarize.
19158       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19159         return SDValue();
19160
19161       // Redistribute the loaded elements into the different locations.
19162       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19163       for (unsigned i = 0; i != NumElems; ++i)
19164         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19165
19166       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19167                                            DAG.getUNDEF(WideVecVT),
19168                                            &ShuffleVec[0]);
19169
19170       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19171
19172       // Build the arithmetic shift.
19173       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19174                      MemVT.getVectorElementType().getSizeInBits();
19175       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19176                           DAG.getConstant(Amt, RegVT));
19177
19178       return DCI.CombineTo(N, Shuff, TF, true);
19179     }
19180
19181     // Redistribute the loaded elements into the different locations.
19182     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19183     for (unsigned i = 0; i != NumElems; ++i)
19184       ShuffleVec[i*SizeRatio] = i;
19185
19186     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19187                                          DAG.getUNDEF(WideVecVT),
19188                                          &ShuffleVec[0]);
19189
19190     // Bitcast to the requested type.
19191     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19192     // Replace the original load with the new sequence
19193     // and return the new chain.
19194     return DCI.CombineTo(N, Shuff, TF, true);
19195   }
19196
19197   return SDValue();
19198 }
19199
19200 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19201 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19202                                    const X86Subtarget *Subtarget) {
19203   StoreSDNode *St = cast<StoreSDNode>(N);
19204   EVT VT = St->getValue().getValueType();
19205   EVT StVT = St->getMemoryVT();
19206   SDLoc dl(St);
19207   SDValue StoredVal = St->getOperand(1);
19208   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19209
19210   // If we are saving a concatenation of two XMM registers, perform two stores.
19211   // On Sandy Bridge, 256-bit memory operations are executed by two
19212   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19213   // memory  operation.
19214   unsigned Alignment = St->getAlignment();
19215   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19216   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19217       StVT == VT && !IsAligned) {
19218     unsigned NumElems = VT.getVectorNumElements();
19219     if (NumElems < 2)
19220       return SDValue();
19221
19222     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19223     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19224
19225     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19226     SDValue Ptr0 = St->getBasePtr();
19227     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19228
19229     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19230                                 St->getPointerInfo(), St->isVolatile(),
19231                                 St->isNonTemporal(), Alignment);
19232     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19233                                 St->getPointerInfo(), St->isVolatile(),
19234                                 St->isNonTemporal(),
19235                                 std::min(16U, Alignment));
19236     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19237   }
19238
19239   // Optimize trunc store (of multiple scalars) to shuffle and store.
19240   // First, pack all of the elements in one place. Next, store to memory
19241   // in fewer chunks.
19242   if (St->isTruncatingStore() && VT.isVector()) {
19243     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19244     unsigned NumElems = VT.getVectorNumElements();
19245     assert(StVT != VT && "Cannot truncate to the same type");
19246     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19247     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19248
19249     // From, To sizes and ElemCount must be pow of two
19250     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19251     // We are going to use the original vector elt for storing.
19252     // Accumulated smaller vector elements must be a multiple of the store size.
19253     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19254
19255     unsigned SizeRatio  = FromSz / ToSz;
19256
19257     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19258
19259     // Create a type on which we perform the shuffle
19260     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19261             StVT.getScalarType(), NumElems*SizeRatio);
19262
19263     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19264
19265     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19266     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19267     for (unsigned i = 0; i != NumElems; ++i)
19268       ShuffleVec[i] = i * SizeRatio;
19269
19270     // Can't shuffle using an illegal type.
19271     if (!TLI.isTypeLegal(WideVecVT))
19272       return SDValue();
19273
19274     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19275                                          DAG.getUNDEF(WideVecVT),
19276                                          &ShuffleVec[0]);
19277     // At this point all of the data is stored at the bottom of the
19278     // register. We now need to save it to mem.
19279
19280     // Find the largest store unit
19281     MVT StoreType = MVT::i8;
19282     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19283          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19284       MVT Tp = (MVT::SimpleValueType)tp;
19285       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19286         StoreType = Tp;
19287     }
19288
19289     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19290     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19291         (64 <= NumElems * ToSz))
19292       StoreType = MVT::f64;
19293
19294     // Bitcast the original vector into a vector of store-size units
19295     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19296             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19297     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19298     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19299     SmallVector<SDValue, 8> Chains;
19300     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19301                                         TLI.getPointerTy());
19302     SDValue Ptr = St->getBasePtr();
19303
19304     // Perform one or more big stores into memory.
19305     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19306       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19307                                    StoreType, ShuffWide,
19308                                    DAG.getIntPtrConstant(i));
19309       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19310                                 St->getPointerInfo(), St->isVolatile(),
19311                                 St->isNonTemporal(), St->getAlignment());
19312       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19313       Chains.push_back(Ch);
19314     }
19315
19316     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19317   }
19318
19319   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19320   // the FP state in cases where an emms may be missing.
19321   // A preferable solution to the general problem is to figure out the right
19322   // places to insert EMMS.  This qualifies as a quick hack.
19323
19324   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19325   if (VT.getSizeInBits() != 64)
19326     return SDValue();
19327
19328   const Function *F = DAG.getMachineFunction().getFunction();
19329   bool NoImplicitFloatOps = F->getAttributes().
19330     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19331   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19332                      && Subtarget->hasSSE2();
19333   if ((VT.isVector() ||
19334        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19335       isa<LoadSDNode>(St->getValue()) &&
19336       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19337       St->getChain().hasOneUse() && !St->isVolatile()) {
19338     SDNode* LdVal = St->getValue().getNode();
19339     LoadSDNode *Ld = nullptr;
19340     int TokenFactorIndex = -1;
19341     SmallVector<SDValue, 8> Ops;
19342     SDNode* ChainVal = St->getChain().getNode();
19343     // Must be a store of a load.  We currently handle two cases:  the load
19344     // is a direct child, and it's under an intervening TokenFactor.  It is
19345     // possible to dig deeper under nested TokenFactors.
19346     if (ChainVal == LdVal)
19347       Ld = cast<LoadSDNode>(St->getChain());
19348     else if (St->getValue().hasOneUse() &&
19349              ChainVal->getOpcode() == ISD::TokenFactor) {
19350       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19351         if (ChainVal->getOperand(i).getNode() == LdVal) {
19352           TokenFactorIndex = i;
19353           Ld = cast<LoadSDNode>(St->getValue());
19354         } else
19355           Ops.push_back(ChainVal->getOperand(i));
19356       }
19357     }
19358
19359     if (!Ld || !ISD::isNormalLoad(Ld))
19360       return SDValue();
19361
19362     // If this is not the MMX case, i.e. we are just turning i64 load/store
19363     // into f64 load/store, avoid the transformation if there are multiple
19364     // uses of the loaded value.
19365     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19366       return SDValue();
19367
19368     SDLoc LdDL(Ld);
19369     SDLoc StDL(N);
19370     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19371     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19372     // pair instead.
19373     if (Subtarget->is64Bit() || F64IsLegal) {
19374       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19375       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19376                                   Ld->getPointerInfo(), Ld->isVolatile(),
19377                                   Ld->isNonTemporal(), Ld->isInvariant(),
19378                                   Ld->getAlignment());
19379       SDValue NewChain = NewLd.getValue(1);
19380       if (TokenFactorIndex != -1) {
19381         Ops.push_back(NewChain);
19382         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19383       }
19384       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19385                           St->getPointerInfo(),
19386                           St->isVolatile(), St->isNonTemporal(),
19387                           St->getAlignment());
19388     }
19389
19390     // Otherwise, lower to two pairs of 32-bit loads / stores.
19391     SDValue LoAddr = Ld->getBasePtr();
19392     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19393                                  DAG.getConstant(4, MVT::i32));
19394
19395     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19396                                Ld->getPointerInfo(),
19397                                Ld->isVolatile(), Ld->isNonTemporal(),
19398                                Ld->isInvariant(), Ld->getAlignment());
19399     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19400                                Ld->getPointerInfo().getWithOffset(4),
19401                                Ld->isVolatile(), Ld->isNonTemporal(),
19402                                Ld->isInvariant(),
19403                                MinAlign(Ld->getAlignment(), 4));
19404
19405     SDValue NewChain = LoLd.getValue(1);
19406     if (TokenFactorIndex != -1) {
19407       Ops.push_back(LoLd);
19408       Ops.push_back(HiLd);
19409       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19410     }
19411
19412     LoAddr = St->getBasePtr();
19413     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19414                          DAG.getConstant(4, MVT::i32));
19415
19416     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19417                                 St->getPointerInfo(),
19418                                 St->isVolatile(), St->isNonTemporal(),
19419                                 St->getAlignment());
19420     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19421                                 St->getPointerInfo().getWithOffset(4),
19422                                 St->isVolatile(),
19423                                 St->isNonTemporal(),
19424                                 MinAlign(St->getAlignment(), 4));
19425     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19426   }
19427   return SDValue();
19428 }
19429
19430 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19431 /// and return the operands for the horizontal operation in LHS and RHS.  A
19432 /// horizontal operation performs the binary operation on successive elements
19433 /// of its first operand, then on successive elements of its second operand,
19434 /// returning the resulting values in a vector.  For example, if
19435 ///   A = < float a0, float a1, float a2, float a3 >
19436 /// and
19437 ///   B = < float b0, float b1, float b2, float b3 >
19438 /// then the result of doing a horizontal operation on A and B is
19439 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19440 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19441 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19442 /// set to A, RHS to B, and the routine returns 'true'.
19443 /// Note that the binary operation should have the property that if one of the
19444 /// operands is UNDEF then the result is UNDEF.
19445 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19446   // Look for the following pattern: if
19447   //   A = < float a0, float a1, float a2, float a3 >
19448   //   B = < float b0, float b1, float b2, float b3 >
19449   // and
19450   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19451   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19452   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19453   // which is A horizontal-op B.
19454
19455   // At least one of the operands should be a vector shuffle.
19456   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19457       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19458     return false;
19459
19460   MVT VT = LHS.getSimpleValueType();
19461
19462   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19463          "Unsupported vector type for horizontal add/sub");
19464
19465   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19466   // operate independently on 128-bit lanes.
19467   unsigned NumElts = VT.getVectorNumElements();
19468   unsigned NumLanes = VT.getSizeInBits()/128;
19469   unsigned NumLaneElts = NumElts / NumLanes;
19470   assert((NumLaneElts % 2 == 0) &&
19471          "Vector type should have an even number of elements in each lane");
19472   unsigned HalfLaneElts = NumLaneElts/2;
19473
19474   // View LHS in the form
19475   //   LHS = VECTOR_SHUFFLE A, B, LMask
19476   // If LHS is not a shuffle then pretend it is the shuffle
19477   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19478   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19479   // type VT.
19480   SDValue A, B;
19481   SmallVector<int, 16> LMask(NumElts);
19482   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19483     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19484       A = LHS.getOperand(0);
19485     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19486       B = LHS.getOperand(1);
19487     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19488     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19489   } else {
19490     if (LHS.getOpcode() != ISD::UNDEF)
19491       A = LHS;
19492     for (unsigned i = 0; i != NumElts; ++i)
19493       LMask[i] = i;
19494   }
19495
19496   // Likewise, view RHS in the form
19497   //   RHS = VECTOR_SHUFFLE C, D, RMask
19498   SDValue C, D;
19499   SmallVector<int, 16> RMask(NumElts);
19500   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19501     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19502       C = RHS.getOperand(0);
19503     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19504       D = RHS.getOperand(1);
19505     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19506     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19507   } else {
19508     if (RHS.getOpcode() != ISD::UNDEF)
19509       C = RHS;
19510     for (unsigned i = 0; i != NumElts; ++i)
19511       RMask[i] = i;
19512   }
19513
19514   // Check that the shuffles are both shuffling the same vectors.
19515   if (!(A == C && B == D) && !(A == D && B == C))
19516     return false;
19517
19518   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19519   if (!A.getNode() && !B.getNode())
19520     return false;
19521
19522   // If A and B occur in reverse order in RHS, then "swap" them (which means
19523   // rewriting the mask).
19524   if (A != C)
19525     CommuteVectorShuffleMask(RMask, NumElts);
19526
19527   // At this point LHS and RHS are equivalent to
19528   //   LHS = VECTOR_SHUFFLE A, B, LMask
19529   //   RHS = VECTOR_SHUFFLE A, B, RMask
19530   // Check that the masks correspond to performing a horizontal operation.
19531   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19532     for (unsigned i = 0; i != NumLaneElts; ++i) {
19533       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19534
19535       // Ignore any UNDEF components.
19536       if (LIdx < 0 || RIdx < 0 ||
19537           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19538           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19539         continue;
19540
19541       // Check that successive elements are being operated on.  If not, this is
19542       // not a horizontal operation.
19543       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19544       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19545       if (!(LIdx == Index && RIdx == Index + 1) &&
19546           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19547         return false;
19548     }
19549   }
19550
19551   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19552   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19553   return true;
19554 }
19555
19556 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19557 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19558                                   const X86Subtarget *Subtarget) {
19559   EVT VT = N->getValueType(0);
19560   SDValue LHS = N->getOperand(0);
19561   SDValue RHS = N->getOperand(1);
19562
19563   // Try to synthesize horizontal adds from adds of shuffles.
19564   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19565        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19566       isHorizontalBinOp(LHS, RHS, true))
19567     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19568   return SDValue();
19569 }
19570
19571 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19572 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19573                                   const X86Subtarget *Subtarget) {
19574   EVT VT = N->getValueType(0);
19575   SDValue LHS = N->getOperand(0);
19576   SDValue RHS = N->getOperand(1);
19577
19578   // Try to synthesize horizontal subs from subs of shuffles.
19579   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19580        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19581       isHorizontalBinOp(LHS, RHS, false))
19582     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19583   return SDValue();
19584 }
19585
19586 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19587 /// X86ISD::FXOR nodes.
19588 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19589   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19590   // F[X]OR(0.0, x) -> x
19591   // F[X]OR(x, 0.0) -> x
19592   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19593     if (C->getValueAPF().isPosZero())
19594       return N->getOperand(1);
19595   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19596     if (C->getValueAPF().isPosZero())
19597       return N->getOperand(0);
19598   return SDValue();
19599 }
19600
19601 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19602 /// X86ISD::FMAX nodes.
19603 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19604   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19605
19606   // Only perform optimizations if UnsafeMath is used.
19607   if (!DAG.getTarget().Options.UnsafeFPMath)
19608     return SDValue();
19609
19610   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19611   // into FMINC and FMAXC, which are Commutative operations.
19612   unsigned NewOp = 0;
19613   switch (N->getOpcode()) {
19614     default: llvm_unreachable("unknown opcode");
19615     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19616     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19617   }
19618
19619   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19620                      N->getOperand(0), N->getOperand(1));
19621 }
19622
19623 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19624 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19625   // FAND(0.0, x) -> 0.0
19626   // FAND(x, 0.0) -> 0.0
19627   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19628     if (C->getValueAPF().isPosZero())
19629       return N->getOperand(0);
19630   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19631     if (C->getValueAPF().isPosZero())
19632       return N->getOperand(1);
19633   return SDValue();
19634 }
19635
19636 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19637 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19638   // FANDN(x, 0.0) -> 0.0
19639   // FANDN(0.0, x) -> x
19640   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19641     if (C->getValueAPF().isPosZero())
19642       return N->getOperand(1);
19643   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19644     if (C->getValueAPF().isPosZero())
19645       return N->getOperand(1);
19646   return SDValue();
19647 }
19648
19649 static SDValue PerformBTCombine(SDNode *N,
19650                                 SelectionDAG &DAG,
19651                                 TargetLowering::DAGCombinerInfo &DCI) {
19652   // BT ignores high bits in the bit index operand.
19653   SDValue Op1 = N->getOperand(1);
19654   if (Op1.hasOneUse()) {
19655     unsigned BitWidth = Op1.getValueSizeInBits();
19656     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19657     APInt KnownZero, KnownOne;
19658     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19659                                           !DCI.isBeforeLegalizeOps());
19660     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19661     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19662         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19663       DCI.CommitTargetLoweringOpt(TLO);
19664   }
19665   return SDValue();
19666 }
19667
19668 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19669   SDValue Op = N->getOperand(0);
19670   if (Op.getOpcode() == ISD::BITCAST)
19671     Op = Op.getOperand(0);
19672   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19673   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19674       VT.getVectorElementType().getSizeInBits() ==
19675       OpVT.getVectorElementType().getSizeInBits()) {
19676     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19677   }
19678   return SDValue();
19679 }
19680
19681 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19682                                                const X86Subtarget *Subtarget) {
19683   EVT VT = N->getValueType(0);
19684   if (!VT.isVector())
19685     return SDValue();
19686
19687   SDValue N0 = N->getOperand(0);
19688   SDValue N1 = N->getOperand(1);
19689   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19690   SDLoc dl(N);
19691
19692   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19693   // both SSE and AVX2 since there is no sign-extended shift right
19694   // operation on a vector with 64-bit elements.
19695   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19696   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19697   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19698       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19699     SDValue N00 = N0.getOperand(0);
19700
19701     // EXTLOAD has a better solution on AVX2,
19702     // it may be replaced with X86ISD::VSEXT node.
19703     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19704       if (!ISD::isNormalLoad(N00.getNode()))
19705         return SDValue();
19706
19707     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19708         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19709                                   N00, N1);
19710       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19711     }
19712   }
19713   return SDValue();
19714 }
19715
19716 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19717                                   TargetLowering::DAGCombinerInfo &DCI,
19718                                   const X86Subtarget *Subtarget) {
19719   if (!DCI.isBeforeLegalizeOps())
19720     return SDValue();
19721
19722   if (!Subtarget->hasFp256())
19723     return SDValue();
19724
19725   EVT VT = N->getValueType(0);
19726   if (VT.isVector() && VT.getSizeInBits() == 256) {
19727     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19728     if (R.getNode())
19729       return R;
19730   }
19731
19732   return SDValue();
19733 }
19734
19735 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19736                                  const X86Subtarget* Subtarget) {
19737   SDLoc dl(N);
19738   EVT VT = N->getValueType(0);
19739
19740   // Let legalize expand this if it isn't a legal type yet.
19741   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19742     return SDValue();
19743
19744   EVT ScalarVT = VT.getScalarType();
19745   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19746       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19747     return SDValue();
19748
19749   SDValue A = N->getOperand(0);
19750   SDValue B = N->getOperand(1);
19751   SDValue C = N->getOperand(2);
19752
19753   bool NegA = (A.getOpcode() == ISD::FNEG);
19754   bool NegB = (B.getOpcode() == ISD::FNEG);
19755   bool NegC = (C.getOpcode() == ISD::FNEG);
19756
19757   // Negative multiplication when NegA xor NegB
19758   bool NegMul = (NegA != NegB);
19759   if (NegA)
19760     A = A.getOperand(0);
19761   if (NegB)
19762     B = B.getOperand(0);
19763   if (NegC)
19764     C = C.getOperand(0);
19765
19766   unsigned Opcode;
19767   if (!NegMul)
19768     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19769   else
19770     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19771
19772   return DAG.getNode(Opcode, dl, VT, A, B, C);
19773 }
19774
19775 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19776                                   TargetLowering::DAGCombinerInfo &DCI,
19777                                   const X86Subtarget *Subtarget) {
19778   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19779   //           (and (i32 x86isd::setcc_carry), 1)
19780   // This eliminates the zext. This transformation is necessary because
19781   // ISD::SETCC is always legalized to i8.
19782   SDLoc dl(N);
19783   SDValue N0 = N->getOperand(0);
19784   EVT VT = N->getValueType(0);
19785
19786   if (N0.getOpcode() == ISD::AND &&
19787       N0.hasOneUse() &&
19788       N0.getOperand(0).hasOneUse()) {
19789     SDValue N00 = N0.getOperand(0);
19790     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19791       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19792       if (!C || C->getZExtValue() != 1)
19793         return SDValue();
19794       return DAG.getNode(ISD::AND, dl, VT,
19795                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19796                                      N00.getOperand(0), N00.getOperand(1)),
19797                          DAG.getConstant(1, VT));
19798     }
19799   }
19800
19801   if (N0.getOpcode() == ISD::TRUNCATE &&
19802       N0.hasOneUse() &&
19803       N0.getOperand(0).hasOneUse()) {
19804     SDValue N00 = N0.getOperand(0);
19805     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19806       return DAG.getNode(ISD::AND, dl, VT,
19807                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19808                                      N00.getOperand(0), N00.getOperand(1)),
19809                          DAG.getConstant(1, VT));
19810     }
19811   }
19812   if (VT.is256BitVector()) {
19813     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19814     if (R.getNode())
19815       return R;
19816   }
19817
19818   return SDValue();
19819 }
19820
19821 // Optimize x == -y --> x+y == 0
19822 //          x != -y --> x+y != 0
19823 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19824                                       const X86Subtarget* Subtarget) {
19825   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19826   SDValue LHS = N->getOperand(0);
19827   SDValue RHS = N->getOperand(1);
19828   EVT VT = N->getValueType(0);
19829   SDLoc DL(N);
19830
19831   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19832     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19833       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19834         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19835                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19836         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19837                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19838       }
19839   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19840     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19841       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19842         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19843                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19844         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19845                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19846       }
19847
19848   if (VT.getScalarType() == MVT::i1) {
19849     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19850       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19851     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19852     if (!IsSEXT0 && !IsVZero0)
19853       return SDValue();
19854     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19855       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19856     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19857
19858     if (!IsSEXT1 && !IsVZero1)
19859       return SDValue();
19860
19861     if (IsSEXT0 && IsVZero1) {
19862       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19863       if (CC == ISD::SETEQ)
19864         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19865       return LHS.getOperand(0);
19866     }
19867     if (IsSEXT1 && IsVZero0) {
19868       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19869       if (CC == ISD::SETEQ)
19870         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19871       return RHS.getOperand(0);
19872     }
19873   }
19874
19875   return SDValue();
19876 }
19877
19878 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19879 // as "sbb reg,reg", since it can be extended without zext and produces
19880 // an all-ones bit which is more useful than 0/1 in some cases.
19881 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19882                                MVT VT) {
19883   if (VT == MVT::i8)
19884     return DAG.getNode(ISD::AND, DL, VT,
19885                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19886                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19887                        DAG.getConstant(1, VT));
19888   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19889   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19890                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19891                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19892 }
19893
19894 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19895 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19896                                    TargetLowering::DAGCombinerInfo &DCI,
19897                                    const X86Subtarget *Subtarget) {
19898   SDLoc DL(N);
19899   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19900   SDValue EFLAGS = N->getOperand(1);
19901
19902   if (CC == X86::COND_A) {
19903     // Try to convert COND_A into COND_B in an attempt to facilitate
19904     // materializing "setb reg".
19905     //
19906     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19907     // cannot take an immediate as its first operand.
19908     //
19909     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19910         EFLAGS.getValueType().isInteger() &&
19911         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19912       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19913                                    EFLAGS.getNode()->getVTList(),
19914                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19915       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19916       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19917     }
19918   }
19919
19920   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19921   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19922   // cases.
19923   if (CC == X86::COND_B)
19924     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19925
19926   SDValue Flags;
19927
19928   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19929   if (Flags.getNode()) {
19930     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19931     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19932   }
19933
19934   return SDValue();
19935 }
19936
19937 // Optimize branch condition evaluation.
19938 //
19939 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19940                                     TargetLowering::DAGCombinerInfo &DCI,
19941                                     const X86Subtarget *Subtarget) {
19942   SDLoc DL(N);
19943   SDValue Chain = N->getOperand(0);
19944   SDValue Dest = N->getOperand(1);
19945   SDValue EFLAGS = N->getOperand(3);
19946   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19947
19948   SDValue Flags;
19949
19950   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19951   if (Flags.getNode()) {
19952     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19953     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19954                        Flags);
19955   }
19956
19957   return SDValue();
19958 }
19959
19960 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19961                                         const X86TargetLowering *XTLI) {
19962   SDValue Op0 = N->getOperand(0);
19963   EVT InVT = Op0->getValueType(0);
19964
19965   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19966   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19967     SDLoc dl(N);
19968     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19969     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19970     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19971   }
19972
19973   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19974   // a 32-bit target where SSE doesn't support i64->FP operations.
19975   if (Op0.getOpcode() == ISD::LOAD) {
19976     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19977     EVT VT = Ld->getValueType(0);
19978     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19979         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19980         !XTLI->getSubtarget()->is64Bit() &&
19981         VT == MVT::i64) {
19982       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19983                                           Ld->getChain(), Op0, DAG);
19984       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19985       return FILDChain;
19986     }
19987   }
19988   return SDValue();
19989 }
19990
19991 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19992 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19993                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19994   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19995   // the result is either zero or one (depending on the input carry bit).
19996   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19997   if (X86::isZeroNode(N->getOperand(0)) &&
19998       X86::isZeroNode(N->getOperand(1)) &&
19999       // We don't have a good way to replace an EFLAGS use, so only do this when
20000       // dead right now.
20001       SDValue(N, 1).use_empty()) {
20002     SDLoc DL(N);
20003     EVT VT = N->getValueType(0);
20004     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20005     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20006                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20007                                            DAG.getConstant(X86::COND_B,MVT::i8),
20008                                            N->getOperand(2)),
20009                                DAG.getConstant(1, VT));
20010     return DCI.CombineTo(N, Res1, CarryOut);
20011   }
20012
20013   return SDValue();
20014 }
20015
20016 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20017 //      (add Y, (setne X, 0)) -> sbb -1, Y
20018 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20019 //      (sub (setne X, 0), Y) -> adc -1, Y
20020 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20021   SDLoc DL(N);
20022
20023   // Look through ZExts.
20024   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20025   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20026     return SDValue();
20027
20028   SDValue SetCC = Ext.getOperand(0);
20029   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20030     return SDValue();
20031
20032   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20033   if (CC != X86::COND_E && CC != X86::COND_NE)
20034     return SDValue();
20035
20036   SDValue Cmp = SetCC.getOperand(1);
20037   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20038       !X86::isZeroNode(Cmp.getOperand(1)) ||
20039       !Cmp.getOperand(0).getValueType().isInteger())
20040     return SDValue();
20041
20042   SDValue CmpOp0 = Cmp.getOperand(0);
20043   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20044                                DAG.getConstant(1, CmpOp0.getValueType()));
20045
20046   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20047   if (CC == X86::COND_NE)
20048     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20049                        DL, OtherVal.getValueType(), OtherVal,
20050                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20051   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20052                      DL, OtherVal.getValueType(), OtherVal,
20053                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20054 }
20055
20056 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20057 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20058                                  const X86Subtarget *Subtarget) {
20059   EVT VT = N->getValueType(0);
20060   SDValue Op0 = N->getOperand(0);
20061   SDValue Op1 = N->getOperand(1);
20062
20063   // Try to synthesize horizontal adds from adds of shuffles.
20064   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20065        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20066       isHorizontalBinOp(Op0, Op1, true))
20067     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20068
20069   return OptimizeConditionalInDecrement(N, DAG);
20070 }
20071
20072 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20073                                  const X86Subtarget *Subtarget) {
20074   SDValue Op0 = N->getOperand(0);
20075   SDValue Op1 = N->getOperand(1);
20076
20077   // X86 can't encode an immediate LHS of a sub. See if we can push the
20078   // negation into a preceding instruction.
20079   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20080     // If the RHS of the sub is a XOR with one use and a constant, invert the
20081     // immediate. Then add one to the LHS of the sub so we can turn
20082     // X-Y -> X+~Y+1, saving one register.
20083     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20084         isa<ConstantSDNode>(Op1.getOperand(1))) {
20085       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20086       EVT VT = Op0.getValueType();
20087       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20088                                    Op1.getOperand(0),
20089                                    DAG.getConstant(~XorC, VT));
20090       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20091                          DAG.getConstant(C->getAPIntValue()+1, VT));
20092     }
20093   }
20094
20095   // Try to synthesize horizontal adds from adds of shuffles.
20096   EVT VT = N->getValueType(0);
20097   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20098        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20099       isHorizontalBinOp(Op0, Op1, true))
20100     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20101
20102   return OptimizeConditionalInDecrement(N, DAG);
20103 }
20104
20105 /// performVZEXTCombine - Performs build vector combines
20106 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20107                                         TargetLowering::DAGCombinerInfo &DCI,
20108                                         const X86Subtarget *Subtarget) {
20109   // (vzext (bitcast (vzext (x)) -> (vzext x)
20110   SDValue In = N->getOperand(0);
20111   while (In.getOpcode() == ISD::BITCAST)
20112     In = In.getOperand(0);
20113
20114   if (In.getOpcode() != X86ISD::VZEXT)
20115     return SDValue();
20116
20117   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20118                      In.getOperand(0));
20119 }
20120
20121 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20122                                              DAGCombinerInfo &DCI) const {
20123   SelectionDAG &DAG = DCI.DAG;
20124   switch (N->getOpcode()) {
20125   default: break;
20126   case ISD::EXTRACT_VECTOR_ELT:
20127     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20128   case ISD::VSELECT:
20129   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20130   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20131   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20132   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20133   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20134   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20135   case ISD::SHL:
20136   case ISD::SRA:
20137   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20138   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20139   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20140   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20141   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20142   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20143   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20144   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20145   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20146   case X86ISD::FXOR:
20147   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20148   case X86ISD::FMIN:
20149   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20150   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20151   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20152   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20153   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20154   case ISD::ANY_EXTEND:
20155   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20156   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20157   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20158   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20159   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20160   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20161   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20162   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20163   case X86ISD::SHUFP:       // Handle all target specific shuffles
20164   case X86ISD::PALIGNR:
20165   case X86ISD::UNPCKH:
20166   case X86ISD::UNPCKL:
20167   case X86ISD::MOVHLPS:
20168   case X86ISD::MOVLHPS:
20169   case X86ISD::PSHUFD:
20170   case X86ISD::PSHUFHW:
20171   case X86ISD::PSHUFLW:
20172   case X86ISD::MOVSS:
20173   case X86ISD::MOVSD:
20174   case X86ISD::VPERMILP:
20175   case X86ISD::VPERM2X128:
20176   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20177   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20178   }
20179
20180   return SDValue();
20181 }
20182
20183 /// isTypeDesirableForOp - Return true if the target has native support for
20184 /// the specified value type and it is 'desirable' to use the type for the
20185 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20186 /// instruction encodings are longer and some i16 instructions are slow.
20187 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20188   if (!isTypeLegal(VT))
20189     return false;
20190   if (VT != MVT::i16)
20191     return true;
20192
20193   switch (Opc) {
20194   default:
20195     return true;
20196   case ISD::LOAD:
20197   case ISD::SIGN_EXTEND:
20198   case ISD::ZERO_EXTEND:
20199   case ISD::ANY_EXTEND:
20200   case ISD::SHL:
20201   case ISD::SRL:
20202   case ISD::SUB:
20203   case ISD::ADD:
20204   case ISD::MUL:
20205   case ISD::AND:
20206   case ISD::OR:
20207   case ISD::XOR:
20208     return false;
20209   }
20210 }
20211
20212 /// IsDesirableToPromoteOp - This method query the target whether it is
20213 /// beneficial for dag combiner to promote the specified node. If true, it
20214 /// should return the desired promotion type by reference.
20215 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20216   EVT VT = Op.getValueType();
20217   if (VT != MVT::i16)
20218     return false;
20219
20220   bool Promote = false;
20221   bool Commute = false;
20222   switch (Op.getOpcode()) {
20223   default: break;
20224   case ISD::LOAD: {
20225     LoadSDNode *LD = cast<LoadSDNode>(Op);
20226     // If the non-extending load has a single use and it's not live out, then it
20227     // might be folded.
20228     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20229                                                      Op.hasOneUse()*/) {
20230       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20231              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20232         // The only case where we'd want to promote LOAD (rather then it being
20233         // promoted as an operand is when it's only use is liveout.
20234         if (UI->getOpcode() != ISD::CopyToReg)
20235           return false;
20236       }
20237     }
20238     Promote = true;
20239     break;
20240   }
20241   case ISD::SIGN_EXTEND:
20242   case ISD::ZERO_EXTEND:
20243   case ISD::ANY_EXTEND:
20244     Promote = true;
20245     break;
20246   case ISD::SHL:
20247   case ISD::SRL: {
20248     SDValue N0 = Op.getOperand(0);
20249     // Look out for (store (shl (load), x)).
20250     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20251       return false;
20252     Promote = true;
20253     break;
20254   }
20255   case ISD::ADD:
20256   case ISD::MUL:
20257   case ISD::AND:
20258   case ISD::OR:
20259   case ISD::XOR:
20260     Commute = true;
20261     // fallthrough
20262   case ISD::SUB: {
20263     SDValue N0 = Op.getOperand(0);
20264     SDValue N1 = Op.getOperand(1);
20265     if (!Commute && MayFoldLoad(N1))
20266       return false;
20267     // Avoid disabling potential load folding opportunities.
20268     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20269       return false;
20270     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20271       return false;
20272     Promote = true;
20273   }
20274   }
20275
20276   PVT = MVT::i32;
20277   return Promote;
20278 }
20279
20280 //===----------------------------------------------------------------------===//
20281 //                           X86 Inline Assembly Support
20282 //===----------------------------------------------------------------------===//
20283
20284 namespace {
20285   // Helper to match a string separated by whitespace.
20286   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20287     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20288
20289     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20290       StringRef piece(*args[i]);
20291       if (!s.startswith(piece)) // Check if the piece matches.
20292         return false;
20293
20294       s = s.substr(piece.size());
20295       StringRef::size_type pos = s.find_first_not_of(" \t");
20296       if (pos == 0) // We matched a prefix.
20297         return false;
20298
20299       s = s.substr(pos);
20300     }
20301
20302     return s.empty();
20303   }
20304   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20305 }
20306
20307 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20308
20309   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20310     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20311         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20312         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20313
20314       if (AsmPieces.size() == 3)
20315         return true;
20316       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20317         return true;
20318     }
20319   }
20320   return false;
20321 }
20322
20323 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20324   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20325
20326   std::string AsmStr = IA->getAsmString();
20327
20328   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20329   if (!Ty || Ty->getBitWidth() % 16 != 0)
20330     return false;
20331
20332   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20333   SmallVector<StringRef, 4> AsmPieces;
20334   SplitString(AsmStr, AsmPieces, ";\n");
20335
20336   switch (AsmPieces.size()) {
20337   default: return false;
20338   case 1:
20339     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20340     // we will turn this bswap into something that will be lowered to logical
20341     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20342     // lower so don't worry about this.
20343     // bswap $0
20344     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20345         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20346         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20347         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20348         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20349         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20350       // No need to check constraints, nothing other than the equivalent of
20351       // "=r,0" would be valid here.
20352       return IntrinsicLowering::LowerToByteSwap(CI);
20353     }
20354
20355     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20356     if (CI->getType()->isIntegerTy(16) &&
20357         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20358         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20359          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20360       AsmPieces.clear();
20361       const std::string &ConstraintsStr = IA->getConstraintString();
20362       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20363       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20364       if (clobbersFlagRegisters(AsmPieces))
20365         return IntrinsicLowering::LowerToByteSwap(CI);
20366     }
20367     break;
20368   case 3:
20369     if (CI->getType()->isIntegerTy(32) &&
20370         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20371         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20372         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20373         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20374       AsmPieces.clear();
20375       const std::string &ConstraintsStr = IA->getConstraintString();
20376       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20377       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20378       if (clobbersFlagRegisters(AsmPieces))
20379         return IntrinsicLowering::LowerToByteSwap(CI);
20380     }
20381
20382     if (CI->getType()->isIntegerTy(64)) {
20383       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20384       if (Constraints.size() >= 2 &&
20385           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20386           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20387         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20388         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20389             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20390             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20391           return IntrinsicLowering::LowerToByteSwap(CI);
20392       }
20393     }
20394     break;
20395   }
20396   return false;
20397 }
20398
20399 /// getConstraintType - Given a constraint letter, return the type of
20400 /// constraint it is for this target.
20401 X86TargetLowering::ConstraintType
20402 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20403   if (Constraint.size() == 1) {
20404     switch (Constraint[0]) {
20405     case 'R':
20406     case 'q':
20407     case 'Q':
20408     case 'f':
20409     case 't':
20410     case 'u':
20411     case 'y':
20412     case 'x':
20413     case 'Y':
20414     case 'l':
20415       return C_RegisterClass;
20416     case 'a':
20417     case 'b':
20418     case 'c':
20419     case 'd':
20420     case 'S':
20421     case 'D':
20422     case 'A':
20423       return C_Register;
20424     case 'I':
20425     case 'J':
20426     case 'K':
20427     case 'L':
20428     case 'M':
20429     case 'N':
20430     case 'G':
20431     case 'C':
20432     case 'e':
20433     case 'Z':
20434       return C_Other;
20435     default:
20436       break;
20437     }
20438   }
20439   return TargetLowering::getConstraintType(Constraint);
20440 }
20441
20442 /// Examine constraint type and operand type and determine a weight value.
20443 /// This object must already have been set up with the operand type
20444 /// and the current alternative constraint selected.
20445 TargetLowering::ConstraintWeight
20446   X86TargetLowering::getSingleConstraintMatchWeight(
20447     AsmOperandInfo &info, const char *constraint) const {
20448   ConstraintWeight weight = CW_Invalid;
20449   Value *CallOperandVal = info.CallOperandVal;
20450     // If we don't have a value, we can't do a match,
20451     // but allow it at the lowest weight.
20452   if (!CallOperandVal)
20453     return CW_Default;
20454   Type *type = CallOperandVal->getType();
20455   // Look at the constraint type.
20456   switch (*constraint) {
20457   default:
20458     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20459   case 'R':
20460   case 'q':
20461   case 'Q':
20462   case 'a':
20463   case 'b':
20464   case 'c':
20465   case 'd':
20466   case 'S':
20467   case 'D':
20468   case 'A':
20469     if (CallOperandVal->getType()->isIntegerTy())
20470       weight = CW_SpecificReg;
20471     break;
20472   case 'f':
20473   case 't':
20474   case 'u':
20475     if (type->isFloatingPointTy())
20476       weight = CW_SpecificReg;
20477     break;
20478   case 'y':
20479     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20480       weight = CW_SpecificReg;
20481     break;
20482   case 'x':
20483   case 'Y':
20484     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20485         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20486       weight = CW_Register;
20487     break;
20488   case 'I':
20489     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20490       if (C->getZExtValue() <= 31)
20491         weight = CW_Constant;
20492     }
20493     break;
20494   case 'J':
20495     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20496       if (C->getZExtValue() <= 63)
20497         weight = CW_Constant;
20498     }
20499     break;
20500   case 'K':
20501     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20502       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20503         weight = CW_Constant;
20504     }
20505     break;
20506   case 'L':
20507     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20508       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20509         weight = CW_Constant;
20510     }
20511     break;
20512   case 'M':
20513     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20514       if (C->getZExtValue() <= 3)
20515         weight = CW_Constant;
20516     }
20517     break;
20518   case 'N':
20519     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20520       if (C->getZExtValue() <= 0xff)
20521         weight = CW_Constant;
20522     }
20523     break;
20524   case 'G':
20525   case 'C':
20526     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20527       weight = CW_Constant;
20528     }
20529     break;
20530   case 'e':
20531     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20532       if ((C->getSExtValue() >= -0x80000000LL) &&
20533           (C->getSExtValue() <= 0x7fffffffLL))
20534         weight = CW_Constant;
20535     }
20536     break;
20537   case 'Z':
20538     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20539       if (C->getZExtValue() <= 0xffffffff)
20540         weight = CW_Constant;
20541     }
20542     break;
20543   }
20544   return weight;
20545 }
20546
20547 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20548 /// with another that has more specific requirements based on the type of the
20549 /// corresponding operand.
20550 const char *X86TargetLowering::
20551 LowerXConstraint(EVT ConstraintVT) const {
20552   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20553   // 'f' like normal targets.
20554   if (ConstraintVT.isFloatingPoint()) {
20555     if (Subtarget->hasSSE2())
20556       return "Y";
20557     if (Subtarget->hasSSE1())
20558       return "x";
20559   }
20560
20561   return TargetLowering::LowerXConstraint(ConstraintVT);
20562 }
20563
20564 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20565 /// vector.  If it is invalid, don't add anything to Ops.
20566 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20567                                                      std::string &Constraint,
20568                                                      std::vector<SDValue>&Ops,
20569                                                      SelectionDAG &DAG) const {
20570   SDValue Result;
20571
20572   // Only support length 1 constraints for now.
20573   if (Constraint.length() > 1) return;
20574
20575   char ConstraintLetter = Constraint[0];
20576   switch (ConstraintLetter) {
20577   default: break;
20578   case 'I':
20579     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20580       if (C->getZExtValue() <= 31) {
20581         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20582         break;
20583       }
20584     }
20585     return;
20586   case 'J':
20587     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20588       if (C->getZExtValue() <= 63) {
20589         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20590         break;
20591       }
20592     }
20593     return;
20594   case 'K':
20595     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20596       if (isInt<8>(C->getSExtValue())) {
20597         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20598         break;
20599       }
20600     }
20601     return;
20602   case 'N':
20603     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20604       if (C->getZExtValue() <= 255) {
20605         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20606         break;
20607       }
20608     }
20609     return;
20610   case 'e': {
20611     // 32-bit signed value
20612     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20613       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20614                                            C->getSExtValue())) {
20615         // Widen to 64 bits here to get it sign extended.
20616         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20617         break;
20618       }
20619     // FIXME gcc accepts some relocatable values here too, but only in certain
20620     // memory models; it's complicated.
20621     }
20622     return;
20623   }
20624   case 'Z': {
20625     // 32-bit unsigned value
20626     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20627       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20628                                            C->getZExtValue())) {
20629         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20630         break;
20631       }
20632     }
20633     // FIXME gcc accepts some relocatable values here too, but only in certain
20634     // memory models; it's complicated.
20635     return;
20636   }
20637   case 'i': {
20638     // Literal immediates are always ok.
20639     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20640       // Widen to 64 bits here to get it sign extended.
20641       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20642       break;
20643     }
20644
20645     // In any sort of PIC mode addresses need to be computed at runtime by
20646     // adding in a register or some sort of table lookup.  These can't
20647     // be used as immediates.
20648     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20649       return;
20650
20651     // If we are in non-pic codegen mode, we allow the address of a global (with
20652     // an optional displacement) to be used with 'i'.
20653     GlobalAddressSDNode *GA = nullptr;
20654     int64_t Offset = 0;
20655
20656     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20657     while (1) {
20658       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20659         Offset += GA->getOffset();
20660         break;
20661       } else if (Op.getOpcode() == ISD::ADD) {
20662         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20663           Offset += C->getZExtValue();
20664           Op = Op.getOperand(0);
20665           continue;
20666         }
20667       } else if (Op.getOpcode() == ISD::SUB) {
20668         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20669           Offset += -C->getZExtValue();
20670           Op = Op.getOperand(0);
20671           continue;
20672         }
20673       }
20674
20675       // Otherwise, this isn't something we can handle, reject it.
20676       return;
20677     }
20678
20679     const GlobalValue *GV = GA->getGlobal();
20680     // If we require an extra load to get this address, as in PIC mode, we
20681     // can't accept it.
20682     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20683                                                         getTargetMachine())))
20684       return;
20685
20686     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20687                                         GA->getValueType(0), Offset);
20688     break;
20689   }
20690   }
20691
20692   if (Result.getNode()) {
20693     Ops.push_back(Result);
20694     return;
20695   }
20696   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20697 }
20698
20699 std::pair<unsigned, const TargetRegisterClass*>
20700 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20701                                                 MVT VT) const {
20702   // First, see if this is a constraint that directly corresponds to an LLVM
20703   // register class.
20704   if (Constraint.size() == 1) {
20705     // GCC Constraint Letters
20706     switch (Constraint[0]) {
20707     default: break;
20708       // TODO: Slight differences here in allocation order and leaving
20709       // RIP in the class. Do they matter any more here than they do
20710       // in the normal allocation?
20711     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20712       if (Subtarget->is64Bit()) {
20713         if (VT == MVT::i32 || VT == MVT::f32)
20714           return std::make_pair(0U, &X86::GR32RegClass);
20715         if (VT == MVT::i16)
20716           return std::make_pair(0U, &X86::GR16RegClass);
20717         if (VT == MVT::i8 || VT == MVT::i1)
20718           return std::make_pair(0U, &X86::GR8RegClass);
20719         if (VT == MVT::i64 || VT == MVT::f64)
20720           return std::make_pair(0U, &X86::GR64RegClass);
20721         break;
20722       }
20723       // 32-bit fallthrough
20724     case 'Q':   // Q_REGS
20725       if (VT == MVT::i32 || VT == MVT::f32)
20726         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20727       if (VT == MVT::i16)
20728         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20729       if (VT == MVT::i8 || VT == MVT::i1)
20730         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20731       if (VT == MVT::i64)
20732         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20733       break;
20734     case 'r':   // GENERAL_REGS
20735     case 'l':   // INDEX_REGS
20736       if (VT == MVT::i8 || VT == MVT::i1)
20737         return std::make_pair(0U, &X86::GR8RegClass);
20738       if (VT == MVT::i16)
20739         return std::make_pair(0U, &X86::GR16RegClass);
20740       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20741         return std::make_pair(0U, &X86::GR32RegClass);
20742       return std::make_pair(0U, &X86::GR64RegClass);
20743     case 'R':   // LEGACY_REGS
20744       if (VT == MVT::i8 || VT == MVT::i1)
20745         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20746       if (VT == MVT::i16)
20747         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20748       if (VT == MVT::i32 || !Subtarget->is64Bit())
20749         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20750       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20751     case 'f':  // FP Stack registers.
20752       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20753       // value to the correct fpstack register class.
20754       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20755         return std::make_pair(0U, &X86::RFP32RegClass);
20756       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20757         return std::make_pair(0U, &X86::RFP64RegClass);
20758       return std::make_pair(0U, &X86::RFP80RegClass);
20759     case 'y':   // MMX_REGS if MMX allowed.
20760       if (!Subtarget->hasMMX()) break;
20761       return std::make_pair(0U, &X86::VR64RegClass);
20762     case 'Y':   // SSE_REGS if SSE2 allowed
20763       if (!Subtarget->hasSSE2()) break;
20764       // FALL THROUGH.
20765     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20766       if (!Subtarget->hasSSE1()) break;
20767
20768       switch (VT.SimpleTy) {
20769       default: break;
20770       // Scalar SSE types.
20771       case MVT::f32:
20772       case MVT::i32:
20773         return std::make_pair(0U, &X86::FR32RegClass);
20774       case MVT::f64:
20775       case MVT::i64:
20776         return std::make_pair(0U, &X86::FR64RegClass);
20777       // Vector types.
20778       case MVT::v16i8:
20779       case MVT::v8i16:
20780       case MVT::v4i32:
20781       case MVT::v2i64:
20782       case MVT::v4f32:
20783       case MVT::v2f64:
20784         return std::make_pair(0U, &X86::VR128RegClass);
20785       // AVX types.
20786       case MVT::v32i8:
20787       case MVT::v16i16:
20788       case MVT::v8i32:
20789       case MVT::v4i64:
20790       case MVT::v8f32:
20791       case MVT::v4f64:
20792         return std::make_pair(0U, &X86::VR256RegClass);
20793       case MVT::v8f64:
20794       case MVT::v16f32:
20795       case MVT::v16i32:
20796       case MVT::v8i64:
20797         return std::make_pair(0U, &X86::VR512RegClass);
20798       }
20799       break;
20800     }
20801   }
20802
20803   // Use the default implementation in TargetLowering to convert the register
20804   // constraint into a member of a register class.
20805   std::pair<unsigned, const TargetRegisterClass*> Res;
20806   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20807
20808   // Not found as a standard register?
20809   if (!Res.second) {
20810     // Map st(0) -> st(7) -> ST0
20811     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20812         tolower(Constraint[1]) == 's' &&
20813         tolower(Constraint[2]) == 't' &&
20814         Constraint[3] == '(' &&
20815         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20816         Constraint[5] == ')' &&
20817         Constraint[6] == '}') {
20818
20819       Res.first = X86::ST0+Constraint[4]-'0';
20820       Res.second = &X86::RFP80RegClass;
20821       return Res;
20822     }
20823
20824     // GCC allows "st(0)" to be called just plain "st".
20825     if (StringRef("{st}").equals_lower(Constraint)) {
20826       Res.first = X86::ST0;
20827       Res.second = &X86::RFP80RegClass;
20828       return Res;
20829     }
20830
20831     // flags -> EFLAGS
20832     if (StringRef("{flags}").equals_lower(Constraint)) {
20833       Res.first = X86::EFLAGS;
20834       Res.second = &X86::CCRRegClass;
20835       return Res;
20836     }
20837
20838     // 'A' means EAX + EDX.
20839     if (Constraint == "A") {
20840       Res.first = X86::EAX;
20841       Res.second = &X86::GR32_ADRegClass;
20842       return Res;
20843     }
20844     return Res;
20845   }
20846
20847   // Otherwise, check to see if this is a register class of the wrong value
20848   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20849   // turn into {ax},{dx}.
20850   if (Res.second->hasType(VT))
20851     return Res;   // Correct type already, nothing to do.
20852
20853   // All of the single-register GCC register classes map their values onto
20854   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20855   // really want an 8-bit or 32-bit register, map to the appropriate register
20856   // class and return the appropriate register.
20857   if (Res.second == &X86::GR16RegClass) {
20858     if (VT == MVT::i8 || VT == MVT::i1) {
20859       unsigned DestReg = 0;
20860       switch (Res.first) {
20861       default: break;
20862       case X86::AX: DestReg = X86::AL; break;
20863       case X86::DX: DestReg = X86::DL; break;
20864       case X86::CX: DestReg = X86::CL; break;
20865       case X86::BX: DestReg = X86::BL; break;
20866       }
20867       if (DestReg) {
20868         Res.first = DestReg;
20869         Res.second = &X86::GR8RegClass;
20870       }
20871     } else if (VT == MVT::i32 || VT == MVT::f32) {
20872       unsigned DestReg = 0;
20873       switch (Res.first) {
20874       default: break;
20875       case X86::AX: DestReg = X86::EAX; break;
20876       case X86::DX: DestReg = X86::EDX; break;
20877       case X86::CX: DestReg = X86::ECX; break;
20878       case X86::BX: DestReg = X86::EBX; break;
20879       case X86::SI: DestReg = X86::ESI; break;
20880       case X86::DI: DestReg = X86::EDI; break;
20881       case X86::BP: DestReg = X86::EBP; break;
20882       case X86::SP: DestReg = X86::ESP; break;
20883       }
20884       if (DestReg) {
20885         Res.first = DestReg;
20886         Res.second = &X86::GR32RegClass;
20887       }
20888     } else if (VT == MVT::i64 || VT == MVT::f64) {
20889       unsigned DestReg = 0;
20890       switch (Res.first) {
20891       default: break;
20892       case X86::AX: DestReg = X86::RAX; break;
20893       case X86::DX: DestReg = X86::RDX; break;
20894       case X86::CX: DestReg = X86::RCX; break;
20895       case X86::BX: DestReg = X86::RBX; break;
20896       case X86::SI: DestReg = X86::RSI; break;
20897       case X86::DI: DestReg = X86::RDI; break;
20898       case X86::BP: DestReg = X86::RBP; break;
20899       case X86::SP: DestReg = X86::RSP; break;
20900       }
20901       if (DestReg) {
20902         Res.first = DestReg;
20903         Res.second = &X86::GR64RegClass;
20904       }
20905     }
20906   } else if (Res.second == &X86::FR32RegClass ||
20907              Res.second == &X86::FR64RegClass ||
20908              Res.second == &X86::VR128RegClass ||
20909              Res.second == &X86::VR256RegClass ||
20910              Res.second == &X86::FR32XRegClass ||
20911              Res.second == &X86::FR64XRegClass ||
20912              Res.second == &X86::VR128XRegClass ||
20913              Res.second == &X86::VR256XRegClass ||
20914              Res.second == &X86::VR512RegClass) {
20915     // Handle references to XMM physical registers that got mapped into the
20916     // wrong class.  This can happen with constraints like {xmm0} where the
20917     // target independent register mapper will just pick the first match it can
20918     // find, ignoring the required type.
20919
20920     if (VT == MVT::f32 || VT == MVT::i32)
20921       Res.second = &X86::FR32RegClass;
20922     else if (VT == MVT::f64 || VT == MVT::i64)
20923       Res.second = &X86::FR64RegClass;
20924     else if (X86::VR128RegClass.hasType(VT))
20925       Res.second = &X86::VR128RegClass;
20926     else if (X86::VR256RegClass.hasType(VT))
20927       Res.second = &X86::VR256RegClass;
20928     else if (X86::VR512RegClass.hasType(VT))
20929       Res.second = &X86::VR512RegClass;
20930   }
20931
20932   return Res;
20933 }
20934
20935 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20936                                             Type *Ty) const {
20937   // Scaling factors are not free at all.
20938   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20939   // will take 2 allocations in the out of order engine instead of 1
20940   // for plain addressing mode, i.e. inst (reg1).
20941   // E.g.,
20942   // vaddps (%rsi,%drx), %ymm0, %ymm1
20943   // Requires two allocations (one for the load, one for the computation)
20944   // whereas:
20945   // vaddps (%rsi), %ymm0, %ymm1
20946   // Requires just 1 allocation, i.e., freeing allocations for other operations
20947   // and having less micro operations to execute.
20948   //
20949   // For some X86 architectures, this is even worse because for instance for
20950   // stores, the complex addressing mode forces the instruction to use the
20951   // "load" ports instead of the dedicated "store" port.
20952   // E.g., on Haswell:
20953   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
20954   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
20955   if (isLegalAddressingMode(AM, Ty))
20956     // Scale represents reg2 * scale, thus account for 1
20957     // as soon as we use a second register.
20958     return AM.Scale != 0;
20959   return -1;
20960 }