Use makeArrayRef insted of calling ArrayRef<T> constructor directly. I introduced...
[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   // We have target-specific dag combine patterns for the following nodes:
1524   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1525   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1526   setTargetDAGCombine(ISD::VSELECT);
1527   setTargetDAGCombine(ISD::SELECT);
1528   setTargetDAGCombine(ISD::SHL);
1529   setTargetDAGCombine(ISD::SRA);
1530   setTargetDAGCombine(ISD::SRL);
1531   setTargetDAGCombine(ISD::OR);
1532   setTargetDAGCombine(ISD::AND);
1533   setTargetDAGCombine(ISD::ADD);
1534   setTargetDAGCombine(ISD::FADD);
1535   setTargetDAGCombine(ISD::FSUB);
1536   setTargetDAGCombine(ISD::FMA);
1537   setTargetDAGCombine(ISD::SUB);
1538   setTargetDAGCombine(ISD::LOAD);
1539   setTargetDAGCombine(ISD::STORE);
1540   setTargetDAGCombine(ISD::ZERO_EXTEND);
1541   setTargetDAGCombine(ISD::ANY_EXTEND);
1542   setTargetDAGCombine(ISD::SIGN_EXTEND);
1543   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1544   setTargetDAGCombine(ISD::TRUNCATE);
1545   setTargetDAGCombine(ISD::SINT_TO_FP);
1546   setTargetDAGCombine(ISD::SETCC);
1547   if (Subtarget->is64Bit())
1548     setTargetDAGCombine(ISD::MUL);
1549   setTargetDAGCombine(ISD::XOR);
1550
1551   computeRegisterProperties();
1552
1553   // On Darwin, -Os means optimize for size without hurting performance,
1554   // do not reduce the limit.
1555   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1556   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1557   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1558   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1559   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1560   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1561   setPrefLoopAlignment(4); // 2^4 bytes.
1562
1563   // Predictable cmov don't hurt on atom because it's in-order.
1564   PredictableSelectIsExpensive = !Subtarget->isAtom();
1565
1566   setPrefFunctionAlignment(4); // 2^4 bytes.
1567 }
1568
1569 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1570   if (!VT.isVector())
1571     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1572
1573   if (Subtarget->hasAVX512())
1574     switch(VT.getVectorNumElements()) {
1575     case  8: return MVT::v8i1;
1576     case 16: return MVT::v16i1;
1577   }
1578
1579   return VT.changeVectorElementTypeToInteger();
1580 }
1581
1582 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1583 /// the desired ByVal argument alignment.
1584 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1585   if (MaxAlign == 16)
1586     return;
1587   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1588     if (VTy->getBitWidth() == 128)
1589       MaxAlign = 16;
1590   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1591     unsigned EltAlign = 0;
1592     getMaxByValAlign(ATy->getElementType(), EltAlign);
1593     if (EltAlign > MaxAlign)
1594       MaxAlign = EltAlign;
1595   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1596     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1597       unsigned EltAlign = 0;
1598       getMaxByValAlign(STy->getElementType(i), EltAlign);
1599       if (EltAlign > MaxAlign)
1600         MaxAlign = EltAlign;
1601       if (MaxAlign == 16)
1602         break;
1603     }
1604   }
1605 }
1606
1607 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1608 /// function arguments in the caller parameter area. For X86, aggregates
1609 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1610 /// are at 4-byte boundaries.
1611 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1612   if (Subtarget->is64Bit()) {
1613     // Max of 8 and alignment of type.
1614     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1615     if (TyAlign > 8)
1616       return TyAlign;
1617     return 8;
1618   }
1619
1620   unsigned Align = 4;
1621   if (Subtarget->hasSSE1())
1622     getMaxByValAlign(Ty, Align);
1623   return Align;
1624 }
1625
1626 /// getOptimalMemOpType - Returns the target specific optimal type for load
1627 /// and store operations as a result of memset, memcpy, and memmove
1628 /// lowering. If DstAlign is zero that means it's safe to destination
1629 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1630 /// means there isn't a need to check it against alignment requirement,
1631 /// probably because the source does not need to be loaded. If 'IsMemset' is
1632 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1633 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1634 /// source is constant so it does not need to be loaded.
1635 /// It returns EVT::Other if the type should be determined using generic
1636 /// target-independent logic.
1637 EVT
1638 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1639                                        unsigned DstAlign, unsigned SrcAlign,
1640                                        bool IsMemset, bool ZeroMemset,
1641                                        bool MemcpyStrSrc,
1642                                        MachineFunction &MF) const {
1643   const Function *F = MF.getFunction();
1644   if ((!IsMemset || ZeroMemset) &&
1645       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1646                                        Attribute::NoImplicitFloat)) {
1647     if (Size >= 16 &&
1648         (Subtarget->isUnalignedMemAccessFast() ||
1649          ((DstAlign == 0 || DstAlign >= 16) &&
1650           (SrcAlign == 0 || SrcAlign >= 16)))) {
1651       if (Size >= 32) {
1652         if (Subtarget->hasInt256())
1653           return MVT::v8i32;
1654         if (Subtarget->hasFp256())
1655           return MVT::v8f32;
1656       }
1657       if (Subtarget->hasSSE2())
1658         return MVT::v4i32;
1659       if (Subtarget->hasSSE1())
1660         return MVT::v4f32;
1661     } else if (!MemcpyStrSrc && Size >= 8 &&
1662                !Subtarget->is64Bit() &&
1663                Subtarget->hasSSE2()) {
1664       // Do not use f64 to lower memcpy if source is string constant. It's
1665       // better to use i32 to avoid the loads.
1666       return MVT::f64;
1667     }
1668   }
1669   if (Subtarget->is64Bit() && Size >= 8)
1670     return MVT::i64;
1671   return MVT::i32;
1672 }
1673
1674 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1675   if (VT == MVT::f32)
1676     return X86ScalarSSEf32;
1677   else if (VT == MVT::f64)
1678     return X86ScalarSSEf64;
1679   return true;
1680 }
1681
1682 bool
1683 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1684                                                  unsigned,
1685                                                  bool *Fast) const {
1686   if (Fast)
1687     *Fast = Subtarget->isUnalignedMemAccessFast();
1688   return true;
1689 }
1690
1691 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1692 /// current function.  The returned value is a member of the
1693 /// MachineJumpTableInfo::JTEntryKind enum.
1694 unsigned X86TargetLowering::getJumpTableEncoding() const {
1695   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1696   // symbol.
1697   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1698       Subtarget->isPICStyleGOT())
1699     return MachineJumpTableInfo::EK_Custom32;
1700
1701   // Otherwise, use the normal jump table encoding heuristics.
1702   return TargetLowering::getJumpTableEncoding();
1703 }
1704
1705 const MCExpr *
1706 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1707                                              const MachineBasicBlock *MBB,
1708                                              unsigned uid,MCContext &Ctx) const{
1709   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1710          Subtarget->isPICStyleGOT());
1711   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1712   // entries.
1713   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1714                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1715 }
1716
1717 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1718 /// jumptable.
1719 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1720                                                     SelectionDAG &DAG) const {
1721   if (!Subtarget->is64Bit())
1722     // This doesn't have SDLoc associated with it, but is not really the
1723     // same as a Register.
1724     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1725   return Table;
1726 }
1727
1728 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1729 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1730 /// MCExpr.
1731 const MCExpr *X86TargetLowering::
1732 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1733                              MCContext &Ctx) const {
1734   // X86-64 uses RIP relative addressing based on the jump table label.
1735   if (Subtarget->isPICStyleRIPRel())
1736     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1737
1738   // Otherwise, the reference is relative to the PIC base.
1739   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1740 }
1741
1742 // FIXME: Why this routine is here? Move to RegInfo!
1743 std::pair<const TargetRegisterClass*, uint8_t>
1744 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1745   const TargetRegisterClass *RRC = nullptr;
1746   uint8_t Cost = 1;
1747   switch (VT.SimpleTy) {
1748   default:
1749     return TargetLowering::findRepresentativeClass(VT);
1750   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1751     RRC = Subtarget->is64Bit() ?
1752       (const TargetRegisterClass*)&X86::GR64RegClass :
1753       (const TargetRegisterClass*)&X86::GR32RegClass;
1754     break;
1755   case MVT::x86mmx:
1756     RRC = &X86::VR64RegClass;
1757     break;
1758   case MVT::f32: case MVT::f64:
1759   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1760   case MVT::v4f32: case MVT::v2f64:
1761   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1762   case MVT::v4f64:
1763     RRC = &X86::VR128RegClass;
1764     break;
1765   }
1766   return std::make_pair(RRC, Cost);
1767 }
1768
1769 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1770                                                unsigned &Offset) const {
1771   if (!Subtarget->isTargetLinux())
1772     return false;
1773
1774   if (Subtarget->is64Bit()) {
1775     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1776     Offset = 0x28;
1777     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1778       AddressSpace = 256;
1779     else
1780       AddressSpace = 257;
1781   } else {
1782     // %gs:0x14 on i386
1783     Offset = 0x14;
1784     AddressSpace = 256;
1785   }
1786   return true;
1787 }
1788
1789 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1790                                             unsigned DestAS) const {
1791   assert(SrcAS != DestAS && "Expected different address spaces!");
1792
1793   return SrcAS < 256 && DestAS < 256;
1794 }
1795
1796 //===----------------------------------------------------------------------===//
1797 //               Return Value Calling Convention Implementation
1798 //===----------------------------------------------------------------------===//
1799
1800 #include "X86GenCallingConv.inc"
1801
1802 bool
1803 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1804                                   MachineFunction &MF, bool isVarArg,
1805                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1806                         LLVMContext &Context) const {
1807   SmallVector<CCValAssign, 16> RVLocs;
1808   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1809                  RVLocs, Context);
1810   return CCInfo.CheckReturn(Outs, RetCC_X86);
1811 }
1812
1813 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1814   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1815   return ScratchRegs;
1816 }
1817
1818 SDValue
1819 X86TargetLowering::LowerReturn(SDValue Chain,
1820                                CallingConv::ID CallConv, bool isVarArg,
1821                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1822                                const SmallVectorImpl<SDValue> &OutVals,
1823                                SDLoc dl, SelectionDAG &DAG) const {
1824   MachineFunction &MF = DAG.getMachineFunction();
1825   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1826
1827   SmallVector<CCValAssign, 16> RVLocs;
1828   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1829                  RVLocs, *DAG.getContext());
1830   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1831
1832   SDValue Flag;
1833   SmallVector<SDValue, 6> RetOps;
1834   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1835   // Operand #1 = Bytes To Pop
1836   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1837                    MVT::i16));
1838
1839   // Copy the result values into the output registers.
1840   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1841     CCValAssign &VA = RVLocs[i];
1842     assert(VA.isRegLoc() && "Can only return in registers!");
1843     SDValue ValToCopy = OutVals[i];
1844     EVT ValVT = ValToCopy.getValueType();
1845
1846     // Promote values to the appropriate types
1847     if (VA.getLocInfo() == CCValAssign::SExt)
1848       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1849     else if (VA.getLocInfo() == CCValAssign::ZExt)
1850       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1851     else if (VA.getLocInfo() == CCValAssign::AExt)
1852       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1853     else if (VA.getLocInfo() == CCValAssign::BCvt)
1854       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1855
1856     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1857            "Unexpected FP-extend for return value.");  
1858
1859     // If this is x86-64, and we disabled SSE, we can't return FP values,
1860     // or SSE or MMX vectors.
1861     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1862          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1863           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1864       report_fatal_error("SSE register return with SSE disabled");
1865     }
1866     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1867     // llvm-gcc has never done it right and no one has noticed, so this
1868     // should be OK for now.
1869     if (ValVT == MVT::f64 &&
1870         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1871       report_fatal_error("SSE2 register return with SSE2 disabled");
1872
1873     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1874     // the RET instruction and handled by the FP Stackifier.
1875     if (VA.getLocReg() == X86::ST0 ||
1876         VA.getLocReg() == X86::ST1) {
1877       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1878       // change the value to the FP stack register class.
1879       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1880         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1881       RetOps.push_back(ValToCopy);
1882       // Don't emit a copytoreg.
1883       continue;
1884     }
1885
1886     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1887     // which is returned in RAX / RDX.
1888     if (Subtarget->is64Bit()) {
1889       if (ValVT == MVT::x86mmx) {
1890         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1891           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1892           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1893                                   ValToCopy);
1894           // If we don't have SSE2 available, convert to v4f32 so the generated
1895           // register is legal.
1896           if (!Subtarget->hasSSE2())
1897             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1898         }
1899       }
1900     }
1901
1902     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1903     Flag = Chain.getValue(1);
1904     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1905   }
1906
1907   // The x86-64 ABIs require that for returning structs by value we copy
1908   // the sret argument into %rax/%eax (depending on ABI) for the return.
1909   // Win32 requires us to put the sret argument to %eax as well.
1910   // We saved the argument into a virtual register in the entry block,
1911   // so now we copy the value out and into %rax/%eax.
1912   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1913       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1914     MachineFunction &MF = DAG.getMachineFunction();
1915     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1916     unsigned Reg = FuncInfo->getSRetReturnReg();
1917     assert(Reg &&
1918            "SRetReturnReg should have been set in LowerFormalArguments().");
1919     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1920
1921     unsigned RetValReg
1922         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1923           X86::RAX : X86::EAX;
1924     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1925     Flag = Chain.getValue(1);
1926
1927     // RAX/EAX now acts like a return value.
1928     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1929   }
1930
1931   RetOps[0] = Chain;  // Update chain.
1932
1933   // Add the flag if we have it.
1934   if (Flag.getNode())
1935     RetOps.push_back(Flag);
1936
1937   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1938 }
1939
1940 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1941   if (N->getNumValues() != 1)
1942     return false;
1943   if (!N->hasNUsesOfValue(1, 0))
1944     return false;
1945
1946   SDValue TCChain = Chain;
1947   SDNode *Copy = *N->use_begin();
1948   if (Copy->getOpcode() == ISD::CopyToReg) {
1949     // If the copy has a glue operand, we conservatively assume it isn't safe to
1950     // perform a tail call.
1951     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1952       return false;
1953     TCChain = Copy->getOperand(0);
1954   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1955     return false;
1956
1957   bool HasRet = false;
1958   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1959        UI != UE; ++UI) {
1960     if (UI->getOpcode() != X86ISD::RET_FLAG)
1961       return false;
1962     HasRet = true;
1963   }
1964
1965   if (!HasRet)
1966     return false;
1967
1968   Chain = TCChain;
1969   return true;
1970 }
1971
1972 MVT
1973 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1974                                             ISD::NodeType ExtendKind) const {
1975   MVT ReturnMVT;
1976   // TODO: Is this also valid on 32-bit?
1977   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1978     ReturnMVT = MVT::i8;
1979   else
1980     ReturnMVT = MVT::i32;
1981
1982   MVT MinVT = getRegisterType(ReturnMVT);
1983   return VT.bitsLT(MinVT) ? MinVT : VT;
1984 }
1985
1986 /// LowerCallResult - Lower the result values of a call into the
1987 /// appropriate copies out of appropriate physical registers.
1988 ///
1989 SDValue
1990 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1991                                    CallingConv::ID CallConv, bool isVarArg,
1992                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1993                                    SDLoc dl, SelectionDAG &DAG,
1994                                    SmallVectorImpl<SDValue> &InVals) const {
1995
1996   // Assign locations to each value returned by this call.
1997   SmallVector<CCValAssign, 16> RVLocs;
1998   bool Is64Bit = Subtarget->is64Bit();
1999   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2000                  getTargetMachine(), RVLocs, *DAG.getContext());
2001   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2002
2003   // Copy all of the result registers out of their specified physreg.
2004   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2005     CCValAssign &VA = RVLocs[i];
2006     EVT CopyVT = VA.getValVT();
2007
2008     // If this is x86-64, and we disabled SSE, we can't return FP values
2009     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2010         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2011       report_fatal_error("SSE register return with SSE disabled");
2012     }
2013
2014     SDValue Val;
2015
2016     // If this is a call to a function that returns an fp value on the floating
2017     // point stack, we must guarantee the value is popped from the stack, so
2018     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2019     // if the return value is not used. We use the FpPOP_RETVAL instruction
2020     // instead.
2021     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2022       // If we prefer to use the value in xmm registers, copy it out as f80 and
2023       // use a truncate to move it from fp stack reg to xmm reg.
2024       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2025       SDValue Ops[] = { Chain, InFlag };
2026       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2027                                          MVT::Other, MVT::Glue, Ops), 1);
2028       Val = Chain.getValue(0);
2029
2030       // Round the f80 to the right size, which also moves it to the appropriate
2031       // xmm register.
2032       if (CopyVT != VA.getValVT())
2033         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2034                           // This truncation won't change the value.
2035                           DAG.getIntPtrConstant(1));
2036     } else {
2037       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2038                                  CopyVT, InFlag).getValue(1);
2039       Val = Chain.getValue(0);
2040     }
2041     InFlag = Chain.getValue(2);
2042     InVals.push_back(Val);
2043   }
2044
2045   return Chain;
2046 }
2047
2048 //===----------------------------------------------------------------------===//
2049 //                C & StdCall & Fast Calling Convention implementation
2050 //===----------------------------------------------------------------------===//
2051 //  StdCall calling convention seems to be standard for many Windows' API
2052 //  routines and around. It differs from C calling convention just a little:
2053 //  callee should clean up the stack, not caller. Symbols should be also
2054 //  decorated in some fancy way :) It doesn't support any vector arguments.
2055 //  For info on fast calling convention see Fast Calling Convention (tail call)
2056 //  implementation LowerX86_32FastCCCallTo.
2057
2058 /// CallIsStructReturn - Determines whether a call uses struct return
2059 /// semantics.
2060 enum StructReturnType {
2061   NotStructReturn,
2062   RegStructReturn,
2063   StackStructReturn
2064 };
2065 static StructReturnType
2066 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2067   if (Outs.empty())
2068     return NotStructReturn;
2069
2070   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2071   if (!Flags.isSRet())
2072     return NotStructReturn;
2073   if (Flags.isInReg())
2074     return RegStructReturn;
2075   return StackStructReturn;
2076 }
2077
2078 /// ArgsAreStructReturn - Determines whether a function uses struct
2079 /// return semantics.
2080 static StructReturnType
2081 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2082   if (Ins.empty())
2083     return NotStructReturn;
2084
2085   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2086   if (!Flags.isSRet())
2087     return NotStructReturn;
2088   if (Flags.isInReg())
2089     return RegStructReturn;
2090   return StackStructReturn;
2091 }
2092
2093 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2094 /// by "Src" to address "Dst" with size and alignment information specified by
2095 /// the specific parameter attribute. The copy will be passed as a byval
2096 /// function parameter.
2097 static SDValue
2098 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2099                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2100                           SDLoc dl) {
2101   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2102
2103   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2104                        /*isVolatile*/false, /*AlwaysInline=*/true,
2105                        MachinePointerInfo(), MachinePointerInfo());
2106 }
2107
2108 /// IsTailCallConvention - Return true if the calling convention is one that
2109 /// supports tail call optimization.
2110 static bool IsTailCallConvention(CallingConv::ID CC) {
2111   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2112           CC == CallingConv::HiPE);
2113 }
2114
2115 /// \brief Return true if the calling convention is a C calling convention.
2116 static bool IsCCallConvention(CallingConv::ID CC) {
2117   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2118           CC == CallingConv::X86_64_SysV);
2119 }
2120
2121 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2122   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2123     return false;
2124
2125   CallSite CS(CI);
2126   CallingConv::ID CalleeCC = CS.getCallingConv();
2127   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2128     return false;
2129
2130   return true;
2131 }
2132
2133 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2134 /// a tailcall target by changing its ABI.
2135 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2136                                    bool GuaranteedTailCallOpt) {
2137   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2138 }
2139
2140 SDValue
2141 X86TargetLowering::LowerMemArgument(SDValue Chain,
2142                                     CallingConv::ID CallConv,
2143                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2144                                     SDLoc dl, SelectionDAG &DAG,
2145                                     const CCValAssign &VA,
2146                                     MachineFrameInfo *MFI,
2147                                     unsigned i) const {
2148   // Create the nodes corresponding to a load from this parameter slot.
2149   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2150   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2151                               getTargetMachine().Options.GuaranteedTailCallOpt);
2152   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2153   EVT ValVT;
2154
2155   // If value is passed by pointer we have address passed instead of the value
2156   // itself.
2157   if (VA.getLocInfo() == CCValAssign::Indirect)
2158     ValVT = VA.getLocVT();
2159   else
2160     ValVT = VA.getValVT();
2161
2162   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2163   // changed with more analysis.
2164   // In case of tail call optimization mark all arguments mutable. Since they
2165   // could be overwritten by lowering of arguments in case of a tail call.
2166   if (Flags.isByVal()) {
2167     unsigned Bytes = Flags.getByValSize();
2168     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2169     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2170     return DAG.getFrameIndex(FI, getPointerTy());
2171   } else {
2172     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2173                                     VA.getLocMemOffset(), isImmutable);
2174     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2175     return DAG.getLoad(ValVT, dl, Chain, FIN,
2176                        MachinePointerInfo::getFixedStack(FI),
2177                        false, false, false, 0);
2178   }
2179 }
2180
2181 SDValue
2182 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2183                                         CallingConv::ID CallConv,
2184                                         bool isVarArg,
2185                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2186                                         SDLoc dl,
2187                                         SelectionDAG &DAG,
2188                                         SmallVectorImpl<SDValue> &InVals)
2189                                           const {
2190   MachineFunction &MF = DAG.getMachineFunction();
2191   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2192
2193   const Function* Fn = MF.getFunction();
2194   if (Fn->hasExternalLinkage() &&
2195       Subtarget->isTargetCygMing() &&
2196       Fn->getName() == "main")
2197     FuncInfo->setForceFramePointer(true);
2198
2199   MachineFrameInfo *MFI = MF.getFrameInfo();
2200   bool Is64Bit = Subtarget->is64Bit();
2201   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2202
2203   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2204          "Var args not supported with calling convention fastcc, ghc or hipe");
2205
2206   // Assign locations to all of the incoming arguments.
2207   SmallVector<CCValAssign, 16> ArgLocs;
2208   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2209                  ArgLocs, *DAG.getContext());
2210
2211   // Allocate shadow area for Win64
2212   if (IsWin64)
2213     CCInfo.AllocateStack(32, 8);
2214
2215   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2216
2217   unsigned LastVal = ~0U;
2218   SDValue ArgValue;
2219   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2220     CCValAssign &VA = ArgLocs[i];
2221     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2222     // places.
2223     assert(VA.getValNo() != LastVal &&
2224            "Don't support value assigned to multiple locs yet");
2225     (void)LastVal;
2226     LastVal = VA.getValNo();
2227
2228     if (VA.isRegLoc()) {
2229       EVT RegVT = VA.getLocVT();
2230       const TargetRegisterClass *RC;
2231       if (RegVT == MVT::i32)
2232         RC = &X86::GR32RegClass;
2233       else if (Is64Bit && RegVT == MVT::i64)
2234         RC = &X86::GR64RegClass;
2235       else if (RegVT == MVT::f32)
2236         RC = &X86::FR32RegClass;
2237       else if (RegVT == MVT::f64)
2238         RC = &X86::FR64RegClass;
2239       else if (RegVT.is512BitVector())
2240         RC = &X86::VR512RegClass;
2241       else if (RegVT.is256BitVector())
2242         RC = &X86::VR256RegClass;
2243       else if (RegVT.is128BitVector())
2244         RC = &X86::VR128RegClass;
2245       else if (RegVT == MVT::x86mmx)
2246         RC = &X86::VR64RegClass;
2247       else if (RegVT == MVT::i1)
2248         RC = &X86::VK1RegClass;
2249       else if (RegVT == MVT::v8i1)
2250         RC = &X86::VK8RegClass;
2251       else if (RegVT == MVT::v16i1)
2252         RC = &X86::VK16RegClass;
2253       else
2254         llvm_unreachable("Unknown argument type!");
2255
2256       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2257       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2258
2259       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2260       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2261       // right size.
2262       if (VA.getLocInfo() == CCValAssign::SExt)
2263         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2264                                DAG.getValueType(VA.getValVT()));
2265       else if (VA.getLocInfo() == CCValAssign::ZExt)
2266         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2267                                DAG.getValueType(VA.getValVT()));
2268       else if (VA.getLocInfo() == CCValAssign::BCvt)
2269         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2270
2271       if (VA.isExtInLoc()) {
2272         // Handle MMX values passed in XMM regs.
2273         if (RegVT.isVector())
2274           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2275         else
2276           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2277       }
2278     } else {
2279       assert(VA.isMemLoc());
2280       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2281     }
2282
2283     // If value is passed via pointer - do a load.
2284     if (VA.getLocInfo() == CCValAssign::Indirect)
2285       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2286                              MachinePointerInfo(), false, false, false, 0);
2287
2288     InVals.push_back(ArgValue);
2289   }
2290
2291   // The x86-64 ABIs require that for returning structs by value we copy
2292   // the sret argument into %rax/%eax (depending on ABI) for the return.
2293   // Win32 requires us to put the sret argument to %eax as well.
2294   // Save the argument into a virtual register so that we can access it
2295   // from the return points.
2296   if (MF.getFunction()->hasStructRetAttr() &&
2297       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2298     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2299     unsigned Reg = FuncInfo->getSRetReturnReg();
2300     if (!Reg) {
2301       MVT PtrTy = getPointerTy();
2302       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2303       FuncInfo->setSRetReturnReg(Reg);
2304     }
2305     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2306     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2307   }
2308
2309   unsigned StackSize = CCInfo.getNextStackOffset();
2310   // Align stack specially for tail calls.
2311   if (FuncIsMadeTailCallSafe(CallConv,
2312                              MF.getTarget().Options.GuaranteedTailCallOpt))
2313     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2314
2315   // If the function takes variable number of arguments, make a frame index for
2316   // the start of the first vararg value... for expansion of llvm.va_start.
2317   if (isVarArg) {
2318     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2319                     CallConv != CallingConv::X86_ThisCall)) {
2320       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2321     }
2322     if (Is64Bit) {
2323       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2324
2325       // FIXME: We should really autogenerate these arrays
2326       static const MCPhysReg GPR64ArgRegsWin64[] = {
2327         X86::RCX, X86::RDX, X86::R8,  X86::R9
2328       };
2329       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2330         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2331       };
2332       static const MCPhysReg XMMArgRegs64Bit[] = {
2333         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2334         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2335       };
2336       const MCPhysReg *GPR64ArgRegs;
2337       unsigned NumXMMRegs = 0;
2338
2339       if (IsWin64) {
2340         // The XMM registers which might contain var arg parameters are shadowed
2341         // in their paired GPR.  So we only need to save the GPR to their home
2342         // slots.
2343         TotalNumIntRegs = 4;
2344         GPR64ArgRegs = GPR64ArgRegsWin64;
2345       } else {
2346         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2347         GPR64ArgRegs = GPR64ArgRegs64Bit;
2348
2349         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2350                                                 TotalNumXMMRegs);
2351       }
2352       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2353                                                        TotalNumIntRegs);
2354
2355       bool NoImplicitFloatOps = Fn->getAttributes().
2356         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2357       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2358              "SSE register cannot be used when SSE is disabled!");
2359       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2360                NoImplicitFloatOps) &&
2361              "SSE register cannot be used when SSE is disabled!");
2362       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2363           !Subtarget->hasSSE1())
2364         // Kernel mode asks for SSE to be disabled, so don't push them
2365         // on the stack.
2366         TotalNumXMMRegs = 0;
2367
2368       if (IsWin64) {
2369         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2370         // Get to the caller-allocated home save location.  Add 8 to account
2371         // for the return address.
2372         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2373         FuncInfo->setRegSaveFrameIndex(
2374           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2375         // Fixup to set vararg frame on shadow area (4 x i64).
2376         if (NumIntRegs < 4)
2377           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2378       } else {
2379         // For X86-64, if there are vararg parameters that are passed via
2380         // registers, then we must store them to their spots on the stack so
2381         // they may be loaded by deferencing the result of va_next.
2382         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2383         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2384         FuncInfo->setRegSaveFrameIndex(
2385           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2386                                false));
2387       }
2388
2389       // Store the integer parameter registers.
2390       SmallVector<SDValue, 8> MemOps;
2391       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2392                                         getPointerTy());
2393       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2394       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2395         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2396                                   DAG.getIntPtrConstant(Offset));
2397         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2398                                      &X86::GR64RegClass);
2399         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2400         SDValue Store =
2401           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2402                        MachinePointerInfo::getFixedStack(
2403                          FuncInfo->getRegSaveFrameIndex(), Offset),
2404                        false, false, 0);
2405         MemOps.push_back(Store);
2406         Offset += 8;
2407       }
2408
2409       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2410         // Now store the XMM (fp + vector) parameter registers.
2411         SmallVector<SDValue, 11> SaveXMMOps;
2412         SaveXMMOps.push_back(Chain);
2413
2414         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2415         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2416         SaveXMMOps.push_back(ALVal);
2417
2418         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2419                                FuncInfo->getRegSaveFrameIndex()));
2420         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2421                                FuncInfo->getVarArgsFPOffset()));
2422
2423         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2424           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2425                                        &X86::VR128RegClass);
2426           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2427           SaveXMMOps.push_back(Val);
2428         }
2429         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2430                                      MVT::Other, SaveXMMOps));
2431       }
2432
2433       if (!MemOps.empty())
2434         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2435     }
2436   }
2437
2438   // Some CCs need callee pop.
2439   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2440                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2441     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2442   } else {
2443     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2444     // If this is an sret function, the return should pop the hidden pointer.
2445     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2446         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2447         argsAreStructReturn(Ins) == StackStructReturn)
2448       FuncInfo->setBytesToPopOnReturn(4);
2449   }
2450
2451   if (!Is64Bit) {
2452     // RegSaveFrameIndex is X86-64 only.
2453     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2454     if (CallConv == CallingConv::X86_FastCall ||
2455         CallConv == CallingConv::X86_ThisCall)
2456       // fastcc functions can't have varargs.
2457       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2458   }
2459
2460   FuncInfo->setArgumentStackSize(StackSize);
2461
2462   return Chain;
2463 }
2464
2465 SDValue
2466 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2467                                     SDValue StackPtr, SDValue Arg,
2468                                     SDLoc dl, SelectionDAG &DAG,
2469                                     const CCValAssign &VA,
2470                                     ISD::ArgFlagsTy Flags) const {
2471   unsigned LocMemOffset = VA.getLocMemOffset();
2472   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2473   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2474   if (Flags.isByVal())
2475     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2476
2477   return DAG.getStore(Chain, dl, Arg, PtrOff,
2478                       MachinePointerInfo::getStack(LocMemOffset),
2479                       false, false, 0);
2480 }
2481
2482 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2483 /// optimization is performed and it is required.
2484 SDValue
2485 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2486                                            SDValue &OutRetAddr, SDValue Chain,
2487                                            bool IsTailCall, bool Is64Bit,
2488                                            int FPDiff, SDLoc dl) const {
2489   // Adjust the Return address stack slot.
2490   EVT VT = getPointerTy();
2491   OutRetAddr = getReturnAddressFrameIndex(DAG);
2492
2493   // Load the "old" Return address.
2494   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2495                            false, false, false, 0);
2496   return SDValue(OutRetAddr.getNode(), 1);
2497 }
2498
2499 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2500 /// optimization is performed and it is required (FPDiff!=0).
2501 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2502                                         SDValue Chain, SDValue RetAddrFrIdx,
2503                                         EVT PtrVT, unsigned SlotSize,
2504                                         int FPDiff, SDLoc dl) {
2505   // Store the return address to the appropriate stack slot.
2506   if (!FPDiff) return Chain;
2507   // Calculate the new stack slot for the return address.
2508   int NewReturnAddrFI =
2509     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2510                                          false);
2511   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2512   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2513                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2514                        false, false, 0);
2515   return Chain;
2516 }
2517
2518 SDValue
2519 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2520                              SmallVectorImpl<SDValue> &InVals) const {
2521   SelectionDAG &DAG                     = CLI.DAG;
2522   SDLoc &dl                             = CLI.DL;
2523   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2524   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2525   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2526   SDValue Chain                         = CLI.Chain;
2527   SDValue Callee                        = CLI.Callee;
2528   CallingConv::ID CallConv              = CLI.CallConv;
2529   bool &isTailCall                      = CLI.IsTailCall;
2530   bool isVarArg                         = CLI.IsVarArg;
2531
2532   MachineFunction &MF = DAG.getMachineFunction();
2533   bool Is64Bit        = Subtarget->is64Bit();
2534   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2535   StructReturnType SR = callIsStructReturn(Outs);
2536   bool IsSibcall      = false;
2537
2538   if (MF.getTarget().Options.DisableTailCalls)
2539     isTailCall = false;
2540
2541   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2542   if (IsMustTail) {
2543     // Force this to be a tail call.  The verifier rules are enough to ensure
2544     // that we can lower this successfully without moving the return address
2545     // around.
2546     isTailCall = true;
2547   } else if (isTailCall) {
2548     // Check if it's really possible to do a tail call.
2549     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2550                     isVarArg, SR != NotStructReturn,
2551                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2552                     Outs, OutVals, Ins, DAG);
2553
2554     // Sibcalls are automatically detected tailcalls which do not require
2555     // ABI changes.
2556     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2557       IsSibcall = true;
2558
2559     if (isTailCall)
2560       ++NumTailCalls;
2561   }
2562
2563   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2564          "Var args not supported with calling convention fastcc, ghc or hipe");
2565
2566   // Analyze operands of the call, assigning locations to each operand.
2567   SmallVector<CCValAssign, 16> ArgLocs;
2568   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2569                  ArgLocs, *DAG.getContext());
2570
2571   // Allocate shadow area for Win64
2572   if (IsWin64)
2573     CCInfo.AllocateStack(32, 8);
2574
2575   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2576
2577   // Get a count of how many bytes are to be pushed on the stack.
2578   unsigned NumBytes = CCInfo.getNextStackOffset();
2579   if (IsSibcall)
2580     // This is a sibcall. The memory operands are available in caller's
2581     // own caller's stack.
2582     NumBytes = 0;
2583   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2584            IsTailCallConvention(CallConv))
2585     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2586
2587   int FPDiff = 0;
2588   if (isTailCall && !IsSibcall && !IsMustTail) {
2589     // Lower arguments at fp - stackoffset + fpdiff.
2590     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2591     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2592
2593     FPDiff = NumBytesCallerPushed - NumBytes;
2594
2595     // Set the delta of movement of the returnaddr stackslot.
2596     // But only set if delta is greater than previous delta.
2597     if (FPDiff < X86Info->getTCReturnAddrDelta())
2598       X86Info->setTCReturnAddrDelta(FPDiff);
2599   }
2600
2601   unsigned NumBytesToPush = NumBytes;
2602   unsigned NumBytesToPop = NumBytes;
2603
2604   // If we have an inalloca argument, all stack space has already been allocated
2605   // for us and be right at the top of the stack.  We don't support multiple
2606   // arguments passed in memory when using inalloca.
2607   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2608     NumBytesToPush = 0;
2609     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2610            "an inalloca argument must be the only memory argument");
2611   }
2612
2613   if (!IsSibcall)
2614     Chain = DAG.getCALLSEQ_START(
2615         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2616
2617   SDValue RetAddrFrIdx;
2618   // Load return address for tail calls.
2619   if (isTailCall && FPDiff)
2620     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2621                                     Is64Bit, FPDiff, dl);
2622
2623   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2624   SmallVector<SDValue, 8> MemOpChains;
2625   SDValue StackPtr;
2626
2627   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2628   // of tail call optimization arguments are handle later.
2629   const X86RegisterInfo *RegInfo =
2630     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2631   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2632     // Skip inalloca arguments, they have already been written.
2633     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2634     if (Flags.isInAlloca())
2635       continue;
2636
2637     CCValAssign &VA = ArgLocs[i];
2638     EVT RegVT = VA.getLocVT();
2639     SDValue Arg = OutVals[i];
2640     bool isByVal = Flags.isByVal();
2641
2642     // Promote the value if needed.
2643     switch (VA.getLocInfo()) {
2644     default: llvm_unreachable("Unknown loc info!");
2645     case CCValAssign::Full: break;
2646     case CCValAssign::SExt:
2647       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2648       break;
2649     case CCValAssign::ZExt:
2650       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2651       break;
2652     case CCValAssign::AExt:
2653       if (RegVT.is128BitVector()) {
2654         // Special case: passing MMX values in XMM registers.
2655         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2656         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2657         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2658       } else
2659         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2660       break;
2661     case CCValAssign::BCvt:
2662       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2663       break;
2664     case CCValAssign::Indirect: {
2665       // Store the argument.
2666       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2667       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2668       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2669                            MachinePointerInfo::getFixedStack(FI),
2670                            false, false, 0);
2671       Arg = SpillSlot;
2672       break;
2673     }
2674     }
2675
2676     if (VA.isRegLoc()) {
2677       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2678       if (isVarArg && IsWin64) {
2679         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2680         // shadow reg if callee is a varargs function.
2681         unsigned ShadowReg = 0;
2682         switch (VA.getLocReg()) {
2683         case X86::XMM0: ShadowReg = X86::RCX; break;
2684         case X86::XMM1: ShadowReg = X86::RDX; break;
2685         case X86::XMM2: ShadowReg = X86::R8; break;
2686         case X86::XMM3: ShadowReg = X86::R9; break;
2687         }
2688         if (ShadowReg)
2689           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2690       }
2691     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2692       assert(VA.isMemLoc());
2693       if (!StackPtr.getNode())
2694         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2695                                       getPointerTy());
2696       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2697                                              dl, DAG, VA, Flags));
2698     }
2699   }
2700
2701   if (!MemOpChains.empty())
2702     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2703
2704   if (Subtarget->isPICStyleGOT()) {
2705     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2706     // GOT pointer.
2707     if (!isTailCall) {
2708       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2709                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2710     } else {
2711       // If we are tail calling and generating PIC/GOT style code load the
2712       // address of the callee into ECX. The value in ecx is used as target of
2713       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2714       // for tail calls on PIC/GOT architectures. Normally we would just put the
2715       // address of GOT into ebx and then call target@PLT. But for tail calls
2716       // ebx would be restored (since ebx is callee saved) before jumping to the
2717       // target@PLT.
2718
2719       // Note: The actual moving to ECX is done further down.
2720       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2721       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2722           !G->getGlobal()->hasProtectedVisibility())
2723         Callee = LowerGlobalAddress(Callee, DAG);
2724       else if (isa<ExternalSymbolSDNode>(Callee))
2725         Callee = LowerExternalSymbol(Callee, DAG);
2726     }
2727   }
2728
2729   if (Is64Bit && isVarArg && !IsWin64) {
2730     // From AMD64 ABI document:
2731     // For calls that may call functions that use varargs or stdargs
2732     // (prototype-less calls or calls to functions containing ellipsis (...) in
2733     // the declaration) %al is used as hidden argument to specify the number
2734     // of SSE registers used. The contents of %al do not need to match exactly
2735     // the number of registers, but must be an ubound on the number of SSE
2736     // registers used and is in the range 0 - 8 inclusive.
2737
2738     // Count the number of XMM registers allocated.
2739     static const MCPhysReg XMMArgRegs[] = {
2740       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2741       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2742     };
2743     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2744     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2745            && "SSE registers cannot be used when SSE is disabled");
2746
2747     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2748                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2749   }
2750
2751   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2752   // don't need this because the eligibility check rejects calls that require
2753   // shuffling arguments passed in memory.
2754   if (!IsSibcall && isTailCall) {
2755     // Force all the incoming stack arguments to be loaded from the stack
2756     // before any new outgoing arguments are stored to the stack, because the
2757     // outgoing stack slots may alias the incoming argument stack slots, and
2758     // the alias isn't otherwise explicit. This is slightly more conservative
2759     // than necessary, because it means that each store effectively depends
2760     // on every argument instead of just those arguments it would clobber.
2761     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2762
2763     SmallVector<SDValue, 8> MemOpChains2;
2764     SDValue FIN;
2765     int FI = 0;
2766     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2767       CCValAssign &VA = ArgLocs[i];
2768       if (VA.isRegLoc())
2769         continue;
2770       assert(VA.isMemLoc());
2771       SDValue Arg = OutVals[i];
2772       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2773       // Skip inalloca arguments.  They don't require any work.
2774       if (Flags.isInAlloca())
2775         continue;
2776       // Create frame index.
2777       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2778       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2779       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2780       FIN = DAG.getFrameIndex(FI, getPointerTy());
2781
2782       if (Flags.isByVal()) {
2783         // Copy relative to framepointer.
2784         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2785         if (!StackPtr.getNode())
2786           StackPtr = DAG.getCopyFromReg(Chain, dl,
2787                                         RegInfo->getStackRegister(),
2788                                         getPointerTy());
2789         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2790
2791         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2792                                                          ArgChain,
2793                                                          Flags, DAG, dl));
2794       } else {
2795         // Store relative to framepointer.
2796         MemOpChains2.push_back(
2797           DAG.getStore(ArgChain, dl, Arg, FIN,
2798                        MachinePointerInfo::getFixedStack(FI),
2799                        false, false, 0));
2800       }
2801     }
2802
2803     if (!MemOpChains2.empty())
2804       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2805
2806     // Store the return address to the appropriate stack slot.
2807     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2808                                      getPointerTy(), RegInfo->getSlotSize(),
2809                                      FPDiff, dl);
2810   }
2811
2812   // Build a sequence of copy-to-reg nodes chained together with token chain
2813   // and flag operands which copy the outgoing args into registers.
2814   SDValue InFlag;
2815   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2816     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2817                              RegsToPass[i].second, InFlag);
2818     InFlag = Chain.getValue(1);
2819   }
2820
2821   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2822     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2823     // In the 64-bit large code model, we have to make all calls
2824     // through a register, since the call instruction's 32-bit
2825     // pc-relative offset may not be large enough to hold the whole
2826     // address.
2827   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2828     // If the callee is a GlobalAddress node (quite common, every direct call
2829     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2830     // it.
2831
2832     // We should use extra load for direct calls to dllimported functions in
2833     // non-JIT mode.
2834     const GlobalValue *GV = G->getGlobal();
2835     if (!GV->hasDLLImportStorageClass()) {
2836       unsigned char OpFlags = 0;
2837       bool ExtraLoad = false;
2838       unsigned WrapperKind = ISD::DELETED_NODE;
2839
2840       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2841       // external symbols most go through the PLT in PIC mode.  If the symbol
2842       // has hidden or protected visibility, or if it is static or local, then
2843       // we don't need to use the PLT - we can directly call it.
2844       if (Subtarget->isTargetELF() &&
2845           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2846           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2847         OpFlags = X86II::MO_PLT;
2848       } else if (Subtarget->isPICStyleStubAny() &&
2849                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2850                  (!Subtarget->getTargetTriple().isMacOSX() ||
2851                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2852         // PC-relative references to external symbols should go through $stub,
2853         // unless we're building with the leopard linker or later, which
2854         // automatically synthesizes these stubs.
2855         OpFlags = X86II::MO_DARWIN_STUB;
2856       } else if (Subtarget->isPICStyleRIPRel() &&
2857                  isa<Function>(GV) &&
2858                  cast<Function>(GV)->getAttributes().
2859                    hasAttribute(AttributeSet::FunctionIndex,
2860                                 Attribute::NonLazyBind)) {
2861         // If the function is marked as non-lazy, generate an indirect call
2862         // which loads from the GOT directly. This avoids runtime overhead
2863         // at the cost of eager binding (and one extra byte of encoding).
2864         OpFlags = X86II::MO_GOTPCREL;
2865         WrapperKind = X86ISD::WrapperRIP;
2866         ExtraLoad = true;
2867       }
2868
2869       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2870                                           G->getOffset(), OpFlags);
2871
2872       // Add a wrapper if needed.
2873       if (WrapperKind != ISD::DELETED_NODE)
2874         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2875       // Add extra indirection if needed.
2876       if (ExtraLoad)
2877         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2878                              MachinePointerInfo::getGOT(),
2879                              false, false, false, 0);
2880     }
2881   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2882     unsigned char OpFlags = 0;
2883
2884     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2885     // external symbols should go through the PLT.
2886     if (Subtarget->isTargetELF() &&
2887         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2888       OpFlags = X86II::MO_PLT;
2889     } else if (Subtarget->isPICStyleStubAny() &&
2890                (!Subtarget->getTargetTriple().isMacOSX() ||
2891                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2892       // PC-relative references to external symbols should go through $stub,
2893       // unless we're building with the leopard linker or later, which
2894       // automatically synthesizes these stubs.
2895       OpFlags = X86II::MO_DARWIN_STUB;
2896     }
2897
2898     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2899                                          OpFlags);
2900   }
2901
2902   // Returns a chain & a flag for retval copy to use.
2903   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2904   SmallVector<SDValue, 8> Ops;
2905
2906   if (!IsSibcall && isTailCall) {
2907     Chain = DAG.getCALLSEQ_END(Chain,
2908                                DAG.getIntPtrConstant(NumBytesToPop, true),
2909                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2910     InFlag = Chain.getValue(1);
2911   }
2912
2913   Ops.push_back(Chain);
2914   Ops.push_back(Callee);
2915
2916   if (isTailCall)
2917     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2918
2919   // Add argument registers to the end of the list so that they are known live
2920   // into the call.
2921   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2922     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2923                                   RegsToPass[i].second.getValueType()));
2924
2925   // Add a register mask operand representing the call-preserved registers.
2926   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2927   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2928   assert(Mask && "Missing call preserved mask for calling convention");
2929   Ops.push_back(DAG.getRegisterMask(Mask));
2930
2931   if (InFlag.getNode())
2932     Ops.push_back(InFlag);
2933
2934   if (isTailCall) {
2935     // We used to do:
2936     //// If this is the first return lowered for this function, add the regs
2937     //// to the liveout set for the function.
2938     // This isn't right, although it's probably harmless on x86; liveouts
2939     // should be computed from returns not tail calls.  Consider a void
2940     // function making a tail call to a function returning int.
2941     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2942   }
2943
2944   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2945   InFlag = Chain.getValue(1);
2946
2947   // Create the CALLSEQ_END node.
2948   unsigned NumBytesForCalleeToPop;
2949   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2950                        getTargetMachine().Options.GuaranteedTailCallOpt))
2951     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2952   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2953            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2954            SR == StackStructReturn)
2955     // If this is a call to a struct-return function, the callee
2956     // pops the hidden struct pointer, so we have to push it back.
2957     // This is common for Darwin/X86, Linux & Mingw32 targets.
2958     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2959     NumBytesForCalleeToPop = 4;
2960   else
2961     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2962
2963   // Returns a flag for retval copy to use.
2964   if (!IsSibcall) {
2965     Chain = DAG.getCALLSEQ_END(Chain,
2966                                DAG.getIntPtrConstant(NumBytesToPop, true),
2967                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2968                                                      true),
2969                                InFlag, dl);
2970     InFlag = Chain.getValue(1);
2971   }
2972
2973   // Handle result values, copying them out of physregs into vregs that we
2974   // return.
2975   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2976                          Ins, dl, DAG, InVals);
2977 }
2978
2979 //===----------------------------------------------------------------------===//
2980 //                Fast Calling Convention (tail call) implementation
2981 //===----------------------------------------------------------------------===//
2982
2983 //  Like std call, callee cleans arguments, convention except that ECX is
2984 //  reserved for storing the tail called function address. Only 2 registers are
2985 //  free for argument passing (inreg). Tail call optimization is performed
2986 //  provided:
2987 //                * tailcallopt is enabled
2988 //                * caller/callee are fastcc
2989 //  On X86_64 architecture with GOT-style position independent code only local
2990 //  (within module) calls are supported at the moment.
2991 //  To keep the stack aligned according to platform abi the function
2992 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2993 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2994 //  If a tail called function callee has more arguments than the caller the
2995 //  caller needs to make sure that there is room to move the RETADDR to. This is
2996 //  achieved by reserving an area the size of the argument delta right after the
2997 //  original REtADDR, but before the saved framepointer or the spilled registers
2998 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2999 //  stack layout:
3000 //    arg1
3001 //    arg2
3002 //    RETADDR
3003 //    [ new RETADDR
3004 //      move area ]
3005 //    (possible EBP)
3006 //    ESI
3007 //    EDI
3008 //    local1 ..
3009
3010 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3011 /// for a 16 byte align requirement.
3012 unsigned
3013 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3014                                                SelectionDAG& DAG) const {
3015   MachineFunction &MF = DAG.getMachineFunction();
3016   const TargetMachine &TM = MF.getTarget();
3017   const X86RegisterInfo *RegInfo =
3018     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3019   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3020   unsigned StackAlignment = TFI.getStackAlignment();
3021   uint64_t AlignMask = StackAlignment - 1;
3022   int64_t Offset = StackSize;
3023   unsigned SlotSize = RegInfo->getSlotSize();
3024   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3025     // Number smaller than 12 so just add the difference.
3026     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3027   } else {
3028     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3029     Offset = ((~AlignMask) & Offset) + StackAlignment +
3030       (StackAlignment-SlotSize);
3031   }
3032   return Offset;
3033 }
3034
3035 /// MatchingStackOffset - Return true if the given stack call argument is
3036 /// already available in the same position (relatively) of the caller's
3037 /// incoming argument stack.
3038 static
3039 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3040                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3041                          const X86InstrInfo *TII) {
3042   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3043   int FI = INT_MAX;
3044   if (Arg.getOpcode() == ISD::CopyFromReg) {
3045     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3046     if (!TargetRegisterInfo::isVirtualRegister(VR))
3047       return false;
3048     MachineInstr *Def = MRI->getVRegDef(VR);
3049     if (!Def)
3050       return false;
3051     if (!Flags.isByVal()) {
3052       if (!TII->isLoadFromStackSlot(Def, FI))
3053         return false;
3054     } else {
3055       unsigned Opcode = Def->getOpcode();
3056       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3057           Def->getOperand(1).isFI()) {
3058         FI = Def->getOperand(1).getIndex();
3059         Bytes = Flags.getByValSize();
3060       } else
3061         return false;
3062     }
3063   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3064     if (Flags.isByVal())
3065       // ByVal argument is passed in as a pointer but it's now being
3066       // dereferenced. e.g.
3067       // define @foo(%struct.X* %A) {
3068       //   tail call @bar(%struct.X* byval %A)
3069       // }
3070       return false;
3071     SDValue Ptr = Ld->getBasePtr();
3072     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3073     if (!FINode)
3074       return false;
3075     FI = FINode->getIndex();
3076   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3077     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3078     FI = FINode->getIndex();
3079     Bytes = Flags.getByValSize();
3080   } else
3081     return false;
3082
3083   assert(FI != INT_MAX);
3084   if (!MFI->isFixedObjectIndex(FI))
3085     return false;
3086   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3087 }
3088
3089 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3090 /// for tail call optimization. Targets which want to do tail call
3091 /// optimization should implement this function.
3092 bool
3093 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3094                                                      CallingConv::ID CalleeCC,
3095                                                      bool isVarArg,
3096                                                      bool isCalleeStructRet,
3097                                                      bool isCallerStructRet,
3098                                                      Type *RetTy,
3099                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3100                                     const SmallVectorImpl<SDValue> &OutVals,
3101                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3102                                                      SelectionDAG &DAG) const {
3103   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3104     return false;
3105
3106   // If -tailcallopt is specified, make fastcc functions tail-callable.
3107   const MachineFunction &MF = DAG.getMachineFunction();
3108   const Function *CallerF = MF.getFunction();
3109
3110   // If the function return type is x86_fp80 and the callee return type is not,
3111   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3112   // perform a tailcall optimization here.
3113   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3114     return false;
3115
3116   CallingConv::ID CallerCC = CallerF->getCallingConv();
3117   bool CCMatch = CallerCC == CalleeCC;
3118   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3119   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3120
3121   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3122     if (IsTailCallConvention(CalleeCC) && CCMatch)
3123       return true;
3124     return false;
3125   }
3126
3127   // Look for obvious safe cases to perform tail call optimization that do not
3128   // require ABI changes. This is what gcc calls sibcall.
3129
3130   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3131   // emit a special epilogue.
3132   const X86RegisterInfo *RegInfo =
3133     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3134   if (RegInfo->needsStackRealignment(MF))
3135     return false;
3136
3137   // Also avoid sibcall optimization if either caller or callee uses struct
3138   // return semantics.
3139   if (isCalleeStructRet || isCallerStructRet)
3140     return false;
3141
3142   // An stdcall/thiscall caller is expected to clean up its arguments; the
3143   // callee isn't going to do that.
3144   // FIXME: this is more restrictive than needed. We could produce a tailcall
3145   // when the stack adjustment matches. For example, with a thiscall that takes
3146   // only one argument.
3147   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3148                    CallerCC == CallingConv::X86_ThisCall))
3149     return false;
3150
3151   // Do not sibcall optimize vararg calls unless all arguments are passed via
3152   // registers.
3153   if (isVarArg && !Outs.empty()) {
3154
3155     // Optimizing for varargs on Win64 is unlikely to be safe without
3156     // additional testing.
3157     if (IsCalleeWin64 || IsCallerWin64)
3158       return false;
3159
3160     SmallVector<CCValAssign, 16> ArgLocs;
3161     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3162                    getTargetMachine(), ArgLocs, *DAG.getContext());
3163
3164     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3165     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3166       if (!ArgLocs[i].isRegLoc())
3167         return false;
3168   }
3169
3170   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3171   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3172   // this into a sibcall.
3173   bool Unused = false;
3174   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3175     if (!Ins[i].Used) {
3176       Unused = true;
3177       break;
3178     }
3179   }
3180   if (Unused) {
3181     SmallVector<CCValAssign, 16> RVLocs;
3182     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3183                    getTargetMachine(), RVLocs, *DAG.getContext());
3184     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3185     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3186       CCValAssign &VA = RVLocs[i];
3187       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3188         return false;
3189     }
3190   }
3191
3192   // If the calling conventions do not match, then we'd better make sure the
3193   // results are returned in the same way as what the caller expects.
3194   if (!CCMatch) {
3195     SmallVector<CCValAssign, 16> RVLocs1;
3196     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3197                     getTargetMachine(), RVLocs1, *DAG.getContext());
3198     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3199
3200     SmallVector<CCValAssign, 16> RVLocs2;
3201     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3202                     getTargetMachine(), RVLocs2, *DAG.getContext());
3203     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3204
3205     if (RVLocs1.size() != RVLocs2.size())
3206       return false;
3207     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3208       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3209         return false;
3210       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3211         return false;
3212       if (RVLocs1[i].isRegLoc()) {
3213         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3214           return false;
3215       } else {
3216         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3217           return false;
3218       }
3219     }
3220   }
3221
3222   // If the callee takes no arguments then go on to check the results of the
3223   // call.
3224   if (!Outs.empty()) {
3225     // Check if stack adjustment is needed. For now, do not do this if any
3226     // argument is passed on the stack.
3227     SmallVector<CCValAssign, 16> ArgLocs;
3228     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3229                    getTargetMachine(), ArgLocs, *DAG.getContext());
3230
3231     // Allocate shadow area for Win64
3232     if (IsCalleeWin64)
3233       CCInfo.AllocateStack(32, 8);
3234
3235     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3236     if (CCInfo.getNextStackOffset()) {
3237       MachineFunction &MF = DAG.getMachineFunction();
3238       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3239         return false;
3240
3241       // Check if the arguments are already laid out in the right way as
3242       // the caller's fixed stack objects.
3243       MachineFrameInfo *MFI = MF.getFrameInfo();
3244       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3245       const X86InstrInfo *TII =
3246         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3247       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3248         CCValAssign &VA = ArgLocs[i];
3249         SDValue Arg = OutVals[i];
3250         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3251         if (VA.getLocInfo() == CCValAssign::Indirect)
3252           return false;
3253         if (!VA.isRegLoc()) {
3254           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3255                                    MFI, MRI, TII))
3256             return false;
3257         }
3258       }
3259     }
3260
3261     // If the tailcall address may be in a register, then make sure it's
3262     // possible to register allocate for it. In 32-bit, the call address can
3263     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3264     // callee-saved registers are restored. These happen to be the same
3265     // registers used to pass 'inreg' arguments so watch out for those.
3266     if (!Subtarget->is64Bit() &&
3267         ((!isa<GlobalAddressSDNode>(Callee) &&
3268           !isa<ExternalSymbolSDNode>(Callee)) ||
3269          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3270       unsigned NumInRegs = 0;
3271       // In PIC we need an extra register to formulate the address computation
3272       // for the callee.
3273       unsigned MaxInRegs =
3274           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3275
3276       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3277         CCValAssign &VA = ArgLocs[i];
3278         if (!VA.isRegLoc())
3279           continue;
3280         unsigned Reg = VA.getLocReg();
3281         switch (Reg) {
3282         default: break;
3283         case X86::EAX: case X86::EDX: case X86::ECX:
3284           if (++NumInRegs == MaxInRegs)
3285             return false;
3286           break;
3287         }
3288       }
3289     }
3290   }
3291
3292   return true;
3293 }
3294
3295 FastISel *
3296 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3297                                   const TargetLibraryInfo *libInfo) const {
3298   return X86::createFastISel(funcInfo, libInfo);
3299 }
3300
3301 //===----------------------------------------------------------------------===//
3302 //                           Other Lowering Hooks
3303 //===----------------------------------------------------------------------===//
3304
3305 static bool MayFoldLoad(SDValue Op) {
3306   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3307 }
3308
3309 static bool MayFoldIntoStore(SDValue Op) {
3310   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3311 }
3312
3313 static bool isTargetShuffle(unsigned Opcode) {
3314   switch(Opcode) {
3315   default: return false;
3316   case X86ISD::PSHUFD:
3317   case X86ISD::PSHUFHW:
3318   case X86ISD::PSHUFLW:
3319   case X86ISD::SHUFP:
3320   case X86ISD::PALIGNR:
3321   case X86ISD::MOVLHPS:
3322   case X86ISD::MOVLHPD:
3323   case X86ISD::MOVHLPS:
3324   case X86ISD::MOVLPS:
3325   case X86ISD::MOVLPD:
3326   case X86ISD::MOVSHDUP:
3327   case X86ISD::MOVSLDUP:
3328   case X86ISD::MOVDDUP:
3329   case X86ISD::MOVSS:
3330   case X86ISD::MOVSD:
3331   case X86ISD::UNPCKL:
3332   case X86ISD::UNPCKH:
3333   case X86ISD::VPERMILP:
3334   case X86ISD::VPERM2X128:
3335   case X86ISD::VPERMI:
3336     return true;
3337   }
3338 }
3339
3340 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3341                                     SDValue V1, SelectionDAG &DAG) {
3342   switch(Opc) {
3343   default: llvm_unreachable("Unknown x86 shuffle node");
3344   case X86ISD::MOVSHDUP:
3345   case X86ISD::MOVSLDUP:
3346   case X86ISD::MOVDDUP:
3347     return DAG.getNode(Opc, dl, VT, V1);
3348   }
3349 }
3350
3351 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3352                                     SDValue V1, unsigned TargetMask,
3353                                     SelectionDAG &DAG) {
3354   switch(Opc) {
3355   default: llvm_unreachable("Unknown x86 shuffle node");
3356   case X86ISD::PSHUFD:
3357   case X86ISD::PSHUFHW:
3358   case X86ISD::PSHUFLW:
3359   case X86ISD::VPERMILP:
3360   case X86ISD::VPERMI:
3361     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3362   }
3363 }
3364
3365 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3366                                     SDValue V1, SDValue V2, unsigned TargetMask,
3367                                     SelectionDAG &DAG) {
3368   switch(Opc) {
3369   default: llvm_unreachable("Unknown x86 shuffle node");
3370   case X86ISD::PALIGNR:
3371   case X86ISD::SHUFP:
3372   case X86ISD::VPERM2X128:
3373     return DAG.getNode(Opc, dl, VT, V1, V2,
3374                        DAG.getConstant(TargetMask, MVT::i8));
3375   }
3376 }
3377
3378 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3379                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3380   switch(Opc) {
3381   default: llvm_unreachable("Unknown x86 shuffle node");
3382   case X86ISD::MOVLHPS:
3383   case X86ISD::MOVLHPD:
3384   case X86ISD::MOVHLPS:
3385   case X86ISD::MOVLPS:
3386   case X86ISD::MOVLPD:
3387   case X86ISD::MOVSS:
3388   case X86ISD::MOVSD:
3389   case X86ISD::UNPCKL:
3390   case X86ISD::UNPCKH:
3391     return DAG.getNode(Opc, dl, VT, V1, V2);
3392   }
3393 }
3394
3395 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3396   MachineFunction &MF = DAG.getMachineFunction();
3397   const X86RegisterInfo *RegInfo =
3398     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3399   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3400   int ReturnAddrIndex = FuncInfo->getRAIndex();
3401
3402   if (ReturnAddrIndex == 0) {
3403     // Set up a frame object for the return address.
3404     unsigned SlotSize = RegInfo->getSlotSize();
3405     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3406                                                            -(int64_t)SlotSize,
3407                                                            false);
3408     FuncInfo->setRAIndex(ReturnAddrIndex);
3409   }
3410
3411   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3412 }
3413
3414 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3415                                        bool hasSymbolicDisplacement) {
3416   // Offset should fit into 32 bit immediate field.
3417   if (!isInt<32>(Offset))
3418     return false;
3419
3420   // If we don't have a symbolic displacement - we don't have any extra
3421   // restrictions.
3422   if (!hasSymbolicDisplacement)
3423     return true;
3424
3425   // FIXME: Some tweaks might be needed for medium code model.
3426   if (M != CodeModel::Small && M != CodeModel::Kernel)
3427     return false;
3428
3429   // For small code model we assume that latest object is 16MB before end of 31
3430   // bits boundary. We may also accept pretty large negative constants knowing
3431   // that all objects are in the positive half of address space.
3432   if (M == CodeModel::Small && Offset < 16*1024*1024)
3433     return true;
3434
3435   // For kernel code model we know that all object resist in the negative half
3436   // of 32bits address space. We may not accept negative offsets, since they may
3437   // be just off and we may accept pretty large positive ones.
3438   if (M == CodeModel::Kernel && Offset > 0)
3439     return true;
3440
3441   return false;
3442 }
3443
3444 /// isCalleePop - Determines whether the callee is required to pop its
3445 /// own arguments. Callee pop is necessary to support tail calls.
3446 bool X86::isCalleePop(CallingConv::ID CallingConv,
3447                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3448   if (IsVarArg)
3449     return false;
3450
3451   switch (CallingConv) {
3452   default:
3453     return false;
3454   case CallingConv::X86_StdCall:
3455     return !is64Bit;
3456   case CallingConv::X86_FastCall:
3457     return !is64Bit;
3458   case CallingConv::X86_ThisCall:
3459     return !is64Bit;
3460   case CallingConv::Fast:
3461     return TailCallOpt;
3462   case CallingConv::GHC:
3463     return TailCallOpt;
3464   case CallingConv::HiPE:
3465     return TailCallOpt;
3466   }
3467 }
3468
3469 /// \brief Return true if the condition is an unsigned comparison operation.
3470 static bool isX86CCUnsigned(unsigned X86CC) {
3471   switch (X86CC) {
3472   default: llvm_unreachable("Invalid integer condition!");
3473   case X86::COND_E:     return true;
3474   case X86::COND_G:     return false;
3475   case X86::COND_GE:    return false;
3476   case X86::COND_L:     return false;
3477   case X86::COND_LE:    return false;
3478   case X86::COND_NE:    return true;
3479   case X86::COND_B:     return true;
3480   case X86::COND_A:     return true;
3481   case X86::COND_BE:    return true;
3482   case X86::COND_AE:    return true;
3483   }
3484   llvm_unreachable("covered switch fell through?!");
3485 }
3486
3487 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3488 /// specific condition code, returning the condition code and the LHS/RHS of the
3489 /// comparison to make.
3490 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3491                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3492   if (!isFP) {
3493     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3494       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3495         // X > -1   -> X == 0, jump !sign.
3496         RHS = DAG.getConstant(0, RHS.getValueType());
3497         return X86::COND_NS;
3498       }
3499       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3500         // X < 0   -> X == 0, jump on sign.
3501         return X86::COND_S;
3502       }
3503       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3504         // X < 1   -> X <= 0
3505         RHS = DAG.getConstant(0, RHS.getValueType());
3506         return X86::COND_LE;
3507       }
3508     }
3509
3510     switch (SetCCOpcode) {
3511     default: llvm_unreachable("Invalid integer condition!");
3512     case ISD::SETEQ:  return X86::COND_E;
3513     case ISD::SETGT:  return X86::COND_G;
3514     case ISD::SETGE:  return X86::COND_GE;
3515     case ISD::SETLT:  return X86::COND_L;
3516     case ISD::SETLE:  return X86::COND_LE;
3517     case ISD::SETNE:  return X86::COND_NE;
3518     case ISD::SETULT: return X86::COND_B;
3519     case ISD::SETUGT: return X86::COND_A;
3520     case ISD::SETULE: return X86::COND_BE;
3521     case ISD::SETUGE: return X86::COND_AE;
3522     }
3523   }
3524
3525   // First determine if it is required or is profitable to flip the operands.
3526
3527   // If LHS is a foldable load, but RHS is not, flip the condition.
3528   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3529       !ISD::isNON_EXTLoad(RHS.getNode())) {
3530     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3531     std::swap(LHS, RHS);
3532   }
3533
3534   switch (SetCCOpcode) {
3535   default: break;
3536   case ISD::SETOLT:
3537   case ISD::SETOLE:
3538   case ISD::SETUGT:
3539   case ISD::SETUGE:
3540     std::swap(LHS, RHS);
3541     break;
3542   }
3543
3544   // On a floating point condition, the flags are set as follows:
3545   // ZF  PF  CF   op
3546   //  0 | 0 | 0 | X > Y
3547   //  0 | 0 | 1 | X < Y
3548   //  1 | 0 | 0 | X == Y
3549   //  1 | 1 | 1 | unordered
3550   switch (SetCCOpcode) {
3551   default: llvm_unreachable("Condcode should be pre-legalized away");
3552   case ISD::SETUEQ:
3553   case ISD::SETEQ:   return X86::COND_E;
3554   case ISD::SETOLT:              // flipped
3555   case ISD::SETOGT:
3556   case ISD::SETGT:   return X86::COND_A;
3557   case ISD::SETOLE:              // flipped
3558   case ISD::SETOGE:
3559   case ISD::SETGE:   return X86::COND_AE;
3560   case ISD::SETUGT:              // flipped
3561   case ISD::SETULT:
3562   case ISD::SETLT:   return X86::COND_B;
3563   case ISD::SETUGE:              // flipped
3564   case ISD::SETULE:
3565   case ISD::SETLE:   return X86::COND_BE;
3566   case ISD::SETONE:
3567   case ISD::SETNE:   return X86::COND_NE;
3568   case ISD::SETUO:   return X86::COND_P;
3569   case ISD::SETO:    return X86::COND_NP;
3570   case ISD::SETOEQ:
3571   case ISD::SETUNE:  return X86::COND_INVALID;
3572   }
3573 }
3574
3575 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3576 /// code. Current x86 isa includes the following FP cmov instructions:
3577 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3578 static bool hasFPCMov(unsigned X86CC) {
3579   switch (X86CC) {
3580   default:
3581     return false;
3582   case X86::COND_B:
3583   case X86::COND_BE:
3584   case X86::COND_E:
3585   case X86::COND_P:
3586   case X86::COND_A:
3587   case X86::COND_AE:
3588   case X86::COND_NE:
3589   case X86::COND_NP:
3590     return true;
3591   }
3592 }
3593
3594 /// isFPImmLegal - Returns true if the target can instruction select the
3595 /// specified FP immediate natively. If false, the legalizer will
3596 /// materialize the FP immediate as a load from a constant pool.
3597 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3598   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3599     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3600       return true;
3601   }
3602   return false;
3603 }
3604
3605 /// \brief Returns true if it is beneficial to convert a load of a constant
3606 /// to just the constant itself.
3607 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3608                                                           Type *Ty) const {
3609   assert(Ty->isIntegerTy());
3610
3611   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3612   if (BitSize == 0 || BitSize > 64)
3613     return false;
3614   return true;
3615 }
3616
3617 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3618 /// the specified range (L, H].
3619 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3620   return (Val < 0) || (Val >= Low && Val < Hi);
3621 }
3622
3623 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3624 /// specified value.
3625 static bool isUndefOrEqual(int Val, int CmpVal) {
3626   return (Val < 0 || Val == CmpVal);
3627 }
3628
3629 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3630 /// from position Pos and ending in Pos+Size, falls within the specified
3631 /// sequential range (L, L+Pos]. or is undef.
3632 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3633                                        unsigned Pos, unsigned Size, int Low) {
3634   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3635     if (!isUndefOrEqual(Mask[i], Low))
3636       return false;
3637   return true;
3638 }
3639
3640 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3641 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3642 /// the second operand.
3643 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3644   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3645     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3646   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3647     return (Mask[0] < 2 && Mask[1] < 2);
3648   return false;
3649 }
3650
3651 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3652 /// is suitable for input to PSHUFHW.
3653 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3654   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3655     return false;
3656
3657   // Lower quadword copied in order or undef.
3658   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3659     return false;
3660
3661   // Upper quadword shuffled.
3662   for (unsigned i = 4; i != 8; ++i)
3663     if (!isUndefOrInRange(Mask[i], 4, 8))
3664       return false;
3665
3666   if (VT == MVT::v16i16) {
3667     // Lower quadword copied in order or undef.
3668     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3669       return false;
3670
3671     // Upper quadword shuffled.
3672     for (unsigned i = 12; i != 16; ++i)
3673       if (!isUndefOrInRange(Mask[i], 12, 16))
3674         return false;
3675   }
3676
3677   return true;
3678 }
3679
3680 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3681 /// is suitable for input to PSHUFLW.
3682 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3683   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3684     return false;
3685
3686   // Upper quadword copied in order.
3687   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3688     return false;
3689
3690   // Lower quadword shuffled.
3691   for (unsigned i = 0; i != 4; ++i)
3692     if (!isUndefOrInRange(Mask[i], 0, 4))
3693       return false;
3694
3695   if (VT == MVT::v16i16) {
3696     // Upper quadword copied in order.
3697     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3698       return false;
3699
3700     // Lower quadword shuffled.
3701     for (unsigned i = 8; i != 12; ++i)
3702       if (!isUndefOrInRange(Mask[i], 8, 12))
3703         return false;
3704   }
3705
3706   return true;
3707 }
3708
3709 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3710 /// is suitable for input to PALIGNR.
3711 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3712                           const X86Subtarget *Subtarget) {
3713   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3714       (VT.is256BitVector() && !Subtarget->hasInt256()))
3715     return false;
3716
3717   unsigned NumElts = VT.getVectorNumElements();
3718   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3719   unsigned NumLaneElts = NumElts/NumLanes;
3720
3721   // Do not handle 64-bit element shuffles with palignr.
3722   if (NumLaneElts == 2)
3723     return false;
3724
3725   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3726     unsigned i;
3727     for (i = 0; i != NumLaneElts; ++i) {
3728       if (Mask[i+l] >= 0)
3729         break;
3730     }
3731
3732     // Lane is all undef, go to next lane
3733     if (i == NumLaneElts)
3734       continue;
3735
3736     int Start = Mask[i+l];
3737
3738     // Make sure its in this lane in one of the sources
3739     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3740         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3741       return false;
3742
3743     // If not lane 0, then we must match lane 0
3744     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3745       return false;
3746
3747     // Correct second source to be contiguous with first source
3748     if (Start >= (int)NumElts)
3749       Start -= NumElts - NumLaneElts;
3750
3751     // Make sure we're shifting in the right direction.
3752     if (Start <= (int)(i+l))
3753       return false;
3754
3755     Start -= i;
3756
3757     // Check the rest of the elements to see if they are consecutive.
3758     for (++i; i != NumLaneElts; ++i) {
3759       int Idx = Mask[i+l];
3760
3761       // Make sure its in this lane
3762       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3763           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3764         return false;
3765
3766       // If not lane 0, then we must match lane 0
3767       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3768         return false;
3769
3770       if (Idx >= (int)NumElts)
3771         Idx -= NumElts - NumLaneElts;
3772
3773       if (!isUndefOrEqual(Idx, Start+i))
3774         return false;
3775
3776     }
3777   }
3778
3779   return true;
3780 }
3781
3782 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3783 /// the two vector operands have swapped position.
3784 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3785                                      unsigned NumElems) {
3786   for (unsigned i = 0; i != NumElems; ++i) {
3787     int idx = Mask[i];
3788     if (idx < 0)
3789       continue;
3790     else if (idx < (int)NumElems)
3791       Mask[i] = idx + NumElems;
3792     else
3793       Mask[i] = idx - NumElems;
3794   }
3795 }
3796
3797 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3798 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3799 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3800 /// reverse of what x86 shuffles want.
3801 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3802
3803   unsigned NumElems = VT.getVectorNumElements();
3804   unsigned NumLanes = VT.getSizeInBits()/128;
3805   unsigned NumLaneElems = NumElems/NumLanes;
3806
3807   if (NumLaneElems != 2 && NumLaneElems != 4)
3808     return false;
3809
3810   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3811   bool symetricMaskRequired =
3812     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3813
3814   // VSHUFPSY divides the resulting vector into 4 chunks.
3815   // The sources are also splitted into 4 chunks, and each destination
3816   // chunk must come from a different source chunk.
3817   //
3818   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3819   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3820   //
3821   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3822   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3823   //
3824   // VSHUFPDY divides the resulting vector into 4 chunks.
3825   // The sources are also splitted into 4 chunks, and each destination
3826   // chunk must come from a different source chunk.
3827   //
3828   //  SRC1 =>      X3       X2       X1       X0
3829   //  SRC2 =>      Y3       Y2       Y1       Y0
3830   //
3831   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3832   //
3833   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3834   unsigned HalfLaneElems = NumLaneElems/2;
3835   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3836     for (unsigned i = 0; i != NumLaneElems; ++i) {
3837       int Idx = Mask[i+l];
3838       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3839       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3840         return false;
3841       // For VSHUFPSY, the mask of the second half must be the same as the
3842       // first but with the appropriate offsets. This works in the same way as
3843       // VPERMILPS works with masks.
3844       if (!symetricMaskRequired || Idx < 0)
3845         continue;
3846       if (MaskVal[i] < 0) {
3847         MaskVal[i] = Idx - l;
3848         continue;
3849       }
3850       if ((signed)(Idx - l) != MaskVal[i])
3851         return false;
3852     }
3853   }
3854
3855   return true;
3856 }
3857
3858 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3859 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3860 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3861   if (!VT.is128BitVector())
3862     return false;
3863
3864   unsigned NumElems = VT.getVectorNumElements();
3865
3866   if (NumElems != 4)
3867     return false;
3868
3869   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3870   return isUndefOrEqual(Mask[0], 6) &&
3871          isUndefOrEqual(Mask[1], 7) &&
3872          isUndefOrEqual(Mask[2], 2) &&
3873          isUndefOrEqual(Mask[3], 3);
3874 }
3875
3876 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3877 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3878 /// <2, 3, 2, 3>
3879 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3880   if (!VT.is128BitVector())
3881     return false;
3882
3883   unsigned NumElems = VT.getVectorNumElements();
3884
3885   if (NumElems != 4)
3886     return false;
3887
3888   return isUndefOrEqual(Mask[0], 2) &&
3889          isUndefOrEqual(Mask[1], 3) &&
3890          isUndefOrEqual(Mask[2], 2) &&
3891          isUndefOrEqual(Mask[3], 3);
3892 }
3893
3894 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3895 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3896 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3897   if (!VT.is128BitVector())
3898     return false;
3899
3900   unsigned NumElems = VT.getVectorNumElements();
3901
3902   if (NumElems != 2 && NumElems != 4)
3903     return false;
3904
3905   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3906     if (!isUndefOrEqual(Mask[i], i + NumElems))
3907       return false;
3908
3909   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3910     if (!isUndefOrEqual(Mask[i], i))
3911       return false;
3912
3913   return true;
3914 }
3915
3916 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3917 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3918 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3919   if (!VT.is128BitVector())
3920     return false;
3921
3922   unsigned NumElems = VT.getVectorNumElements();
3923
3924   if (NumElems != 2 && NumElems != 4)
3925     return false;
3926
3927   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3928     if (!isUndefOrEqual(Mask[i], i))
3929       return false;
3930
3931   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3932     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3933       return false;
3934
3935   return true;
3936 }
3937
3938 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3939 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3940 /// i. e: If all but one element come from the same vector.
3941 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3942   // TODO: Deal with AVX's VINSERTPS
3943   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3944     return false;
3945
3946   unsigned CorrectPosV1 = 0;
3947   unsigned CorrectPosV2 = 0;
3948   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3949     if (Mask[i] == i)
3950       ++CorrectPosV1;
3951     else if (Mask[i] == i + 4)
3952       ++CorrectPosV2;
3953
3954   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3955     // We have 3 elements from one vector, and one from another.
3956     return true;
3957
3958   return false;
3959 }
3960
3961 //
3962 // Some special combinations that can be optimized.
3963 //
3964 static
3965 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3966                                SelectionDAG &DAG) {
3967   MVT VT = SVOp->getSimpleValueType(0);
3968   SDLoc dl(SVOp);
3969
3970   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3971     return SDValue();
3972
3973   ArrayRef<int> Mask = SVOp->getMask();
3974
3975   // These are the special masks that may be optimized.
3976   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3977   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3978   bool MatchEvenMask = true;
3979   bool MatchOddMask  = true;
3980   for (int i=0; i<8; ++i) {
3981     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3982       MatchEvenMask = false;
3983     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3984       MatchOddMask = false;
3985   }
3986
3987   if (!MatchEvenMask && !MatchOddMask)
3988     return SDValue();
3989
3990   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3991
3992   SDValue Op0 = SVOp->getOperand(0);
3993   SDValue Op1 = SVOp->getOperand(1);
3994
3995   if (MatchEvenMask) {
3996     // Shift the second operand right to 32 bits.
3997     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3998     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3999   } else {
4000     // Shift the first operand left to 32 bits.
4001     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4002     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4003   }
4004   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4005   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4006 }
4007
4008 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4009 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4010 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4011                          bool HasInt256, bool V2IsSplat = false) {
4012
4013   assert(VT.getSizeInBits() >= 128 &&
4014          "Unsupported vector type for unpckl");
4015
4016   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4017   unsigned NumLanes;
4018   unsigned NumOf256BitLanes;
4019   unsigned NumElts = VT.getVectorNumElements();
4020   if (VT.is256BitVector()) {
4021     if (NumElts != 4 && NumElts != 8 &&
4022         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4023     return false;
4024     NumLanes = 2;
4025     NumOf256BitLanes = 1;
4026   } else if (VT.is512BitVector()) {
4027     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4028            "Unsupported vector type for unpckh");
4029     NumLanes = 2;
4030     NumOf256BitLanes = 2;
4031   } else {
4032     NumLanes = 1;
4033     NumOf256BitLanes = 1;
4034   }
4035
4036   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4037   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4038
4039   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4040     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4041       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4042         int BitI  = Mask[l256*NumEltsInStride+l+i];
4043         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4044         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4045           return false;
4046         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4047           return false;
4048         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4049           return false;
4050       }
4051     }
4052   }
4053   return true;
4054 }
4055
4056 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4057 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4058 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4059                          bool HasInt256, bool V2IsSplat = false) {
4060   assert(VT.getSizeInBits() >= 128 &&
4061          "Unsupported vector type for unpckh");
4062
4063   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4064   unsigned NumLanes;
4065   unsigned NumOf256BitLanes;
4066   unsigned NumElts = VT.getVectorNumElements();
4067   if (VT.is256BitVector()) {
4068     if (NumElts != 4 && NumElts != 8 &&
4069         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4070     return false;
4071     NumLanes = 2;
4072     NumOf256BitLanes = 1;
4073   } else if (VT.is512BitVector()) {
4074     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4075            "Unsupported vector type for unpckh");
4076     NumLanes = 2;
4077     NumOf256BitLanes = 2;
4078   } else {
4079     NumLanes = 1;
4080     NumOf256BitLanes = 1;
4081   }
4082
4083   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4084   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4085
4086   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4087     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4088       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4089         int BitI  = Mask[l256*NumEltsInStride+l+i];
4090         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4091         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4092           return false;
4093         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4094           return false;
4095         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4096           return false;
4097       }
4098     }
4099   }
4100   return true;
4101 }
4102
4103 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4104 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4105 /// <0, 0, 1, 1>
4106 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4107   unsigned NumElts = VT.getVectorNumElements();
4108   bool Is256BitVec = VT.is256BitVector();
4109
4110   if (VT.is512BitVector())
4111     return false;
4112   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4113          "Unsupported vector type for unpckh");
4114
4115   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4116       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4117     return false;
4118
4119   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4120   // FIXME: Need a better way to get rid of this, there's no latency difference
4121   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4122   // the former later. We should also remove the "_undef" special mask.
4123   if (NumElts == 4 && Is256BitVec)
4124     return false;
4125
4126   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4127   // independently on 128-bit lanes.
4128   unsigned NumLanes = VT.getSizeInBits()/128;
4129   unsigned NumLaneElts = NumElts/NumLanes;
4130
4131   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4132     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4133       int BitI  = Mask[l+i];
4134       int BitI1 = Mask[l+i+1];
4135
4136       if (!isUndefOrEqual(BitI, j))
4137         return false;
4138       if (!isUndefOrEqual(BitI1, j))
4139         return false;
4140     }
4141   }
4142
4143   return true;
4144 }
4145
4146 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4147 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4148 /// <2, 2, 3, 3>
4149 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4150   unsigned NumElts = VT.getVectorNumElements();
4151
4152   if (VT.is512BitVector())
4153     return false;
4154
4155   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4156          "Unsupported vector type for unpckh");
4157
4158   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4159       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4160     return false;
4161
4162   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4163   // independently on 128-bit lanes.
4164   unsigned NumLanes = VT.getSizeInBits()/128;
4165   unsigned NumLaneElts = NumElts/NumLanes;
4166
4167   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4168     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4169       int BitI  = Mask[l+i];
4170       int BitI1 = Mask[l+i+1];
4171       if (!isUndefOrEqual(BitI, j))
4172         return false;
4173       if (!isUndefOrEqual(BitI1, j))
4174         return false;
4175     }
4176   }
4177   return true;
4178 }
4179
4180 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4181 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4182 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4183   if (!VT.is512BitVector())
4184     return false;
4185
4186   unsigned NumElts = VT.getVectorNumElements();
4187   unsigned HalfSize = NumElts/2;
4188   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4189     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4190       *Imm = 1;
4191       return true;
4192     }
4193   }
4194   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4195     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4196       *Imm = 0;
4197       return true;
4198     }
4199   }
4200   return false;
4201 }
4202
4203 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4204 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4205 /// MOVSD, and MOVD, i.e. setting the lowest element.
4206 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4207   if (VT.getVectorElementType().getSizeInBits() < 32)
4208     return false;
4209   if (!VT.is128BitVector())
4210     return false;
4211
4212   unsigned NumElts = VT.getVectorNumElements();
4213
4214   if (!isUndefOrEqual(Mask[0], NumElts))
4215     return false;
4216
4217   for (unsigned i = 1; i != NumElts; ++i)
4218     if (!isUndefOrEqual(Mask[i], i))
4219       return false;
4220
4221   return true;
4222 }
4223
4224 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4225 /// as permutations between 128-bit chunks or halves. As an example: this
4226 /// shuffle bellow:
4227 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4228 /// The first half comes from the second half of V1 and the second half from the
4229 /// the second half of V2.
4230 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4231   if (!HasFp256 || !VT.is256BitVector())
4232     return false;
4233
4234   // The shuffle result is divided into half A and half B. In total the two
4235   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4236   // B must come from C, D, E or F.
4237   unsigned HalfSize = VT.getVectorNumElements()/2;
4238   bool MatchA = false, MatchB = false;
4239
4240   // Check if A comes from one of C, D, E, F.
4241   for (unsigned Half = 0; Half != 4; ++Half) {
4242     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4243       MatchA = true;
4244       break;
4245     }
4246   }
4247
4248   // Check if B comes from one of C, D, E, F.
4249   for (unsigned Half = 0; Half != 4; ++Half) {
4250     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4251       MatchB = true;
4252       break;
4253     }
4254   }
4255
4256   return MatchA && MatchB;
4257 }
4258
4259 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4260 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4261 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4262   MVT VT = SVOp->getSimpleValueType(0);
4263
4264   unsigned HalfSize = VT.getVectorNumElements()/2;
4265
4266   unsigned FstHalf = 0, SndHalf = 0;
4267   for (unsigned i = 0; i < HalfSize; ++i) {
4268     if (SVOp->getMaskElt(i) > 0) {
4269       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4270       break;
4271     }
4272   }
4273   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4274     if (SVOp->getMaskElt(i) > 0) {
4275       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4276       break;
4277     }
4278   }
4279
4280   return (FstHalf | (SndHalf << 4));
4281 }
4282
4283 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4284 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4285   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4286   if (EltSize < 32)
4287     return false;
4288
4289   unsigned NumElts = VT.getVectorNumElements();
4290   Imm8 = 0;
4291   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4292     for (unsigned i = 0; i != NumElts; ++i) {
4293       if (Mask[i] < 0)
4294         continue;
4295       Imm8 |= Mask[i] << (i*2);
4296     }
4297     return true;
4298   }
4299
4300   unsigned LaneSize = 4;
4301   SmallVector<int, 4> MaskVal(LaneSize, -1);
4302
4303   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4304     for (unsigned i = 0; i != LaneSize; ++i) {
4305       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4306         return false;
4307       if (Mask[i+l] < 0)
4308         continue;
4309       if (MaskVal[i] < 0) {
4310         MaskVal[i] = Mask[i+l] - l;
4311         Imm8 |= MaskVal[i] << (i*2);
4312         continue;
4313       }
4314       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4315         return false;
4316     }
4317   }
4318   return true;
4319 }
4320
4321 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4322 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4323 /// Note that VPERMIL mask matching is different depending whether theunderlying
4324 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4325 /// to the same elements of the low, but to the higher half of the source.
4326 /// In VPERMILPD the two lanes could be shuffled independently of each other
4327 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4328 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4329   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4330   if (VT.getSizeInBits() < 256 || EltSize < 32)
4331     return false;
4332   bool symetricMaskRequired = (EltSize == 32);
4333   unsigned NumElts = VT.getVectorNumElements();
4334
4335   unsigned NumLanes = VT.getSizeInBits()/128;
4336   unsigned LaneSize = NumElts/NumLanes;
4337   // 2 or 4 elements in one lane
4338
4339   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4340   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4341     for (unsigned i = 0; i != LaneSize; ++i) {
4342       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4343         return false;
4344       if (symetricMaskRequired) {
4345         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4346           ExpectedMaskVal[i] = Mask[i+l] - l;
4347           continue;
4348         }
4349         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4350           return false;
4351       }
4352     }
4353   }
4354   return true;
4355 }
4356
4357 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4358 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4359 /// element of vector 2 and the other elements to come from vector 1 in order.
4360 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4361                                bool V2IsSplat = false, bool V2IsUndef = false) {
4362   if (!VT.is128BitVector())
4363     return false;
4364
4365   unsigned NumOps = VT.getVectorNumElements();
4366   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4367     return false;
4368
4369   if (!isUndefOrEqual(Mask[0], 0))
4370     return false;
4371
4372   for (unsigned i = 1; i != NumOps; ++i)
4373     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4374           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4375           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4376       return false;
4377
4378   return true;
4379 }
4380
4381 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4382 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4383 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4384 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4385                            const X86Subtarget *Subtarget) {
4386   if (!Subtarget->hasSSE3())
4387     return false;
4388
4389   unsigned NumElems = VT.getVectorNumElements();
4390
4391   if ((VT.is128BitVector() && NumElems != 4) ||
4392       (VT.is256BitVector() && NumElems != 8) ||
4393       (VT.is512BitVector() && NumElems != 16))
4394     return false;
4395
4396   // "i+1" is the value the indexed mask element must have
4397   for (unsigned i = 0; i != NumElems; i += 2)
4398     if (!isUndefOrEqual(Mask[i], i+1) ||
4399         !isUndefOrEqual(Mask[i+1], i+1))
4400       return false;
4401
4402   return true;
4403 }
4404
4405 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4406 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4407 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4408 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4409                            const X86Subtarget *Subtarget) {
4410   if (!Subtarget->hasSSE3())
4411     return false;
4412
4413   unsigned NumElems = VT.getVectorNumElements();
4414
4415   if ((VT.is128BitVector() && NumElems != 4) ||
4416       (VT.is256BitVector() && NumElems != 8) ||
4417       (VT.is512BitVector() && NumElems != 16))
4418     return false;
4419
4420   // "i" is the value the indexed mask element must have
4421   for (unsigned i = 0; i != NumElems; i += 2)
4422     if (!isUndefOrEqual(Mask[i], i) ||
4423         !isUndefOrEqual(Mask[i+1], i))
4424       return false;
4425
4426   return true;
4427 }
4428
4429 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4430 /// specifies a shuffle of elements that is suitable for input to 256-bit
4431 /// version of MOVDDUP.
4432 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4433   if (!HasFp256 || !VT.is256BitVector())
4434     return false;
4435
4436   unsigned NumElts = VT.getVectorNumElements();
4437   if (NumElts != 4)
4438     return false;
4439
4440   for (unsigned i = 0; i != NumElts/2; ++i)
4441     if (!isUndefOrEqual(Mask[i], 0))
4442       return false;
4443   for (unsigned i = NumElts/2; i != NumElts; ++i)
4444     if (!isUndefOrEqual(Mask[i], NumElts/2))
4445       return false;
4446   return true;
4447 }
4448
4449 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4450 /// specifies a shuffle of elements that is suitable for input to 128-bit
4451 /// version of MOVDDUP.
4452 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4453   if (!VT.is128BitVector())
4454     return false;
4455
4456   unsigned e = VT.getVectorNumElements() / 2;
4457   for (unsigned i = 0; i != e; ++i)
4458     if (!isUndefOrEqual(Mask[i], i))
4459       return false;
4460   for (unsigned i = 0; i != e; ++i)
4461     if (!isUndefOrEqual(Mask[e+i], i))
4462       return false;
4463   return true;
4464 }
4465
4466 /// isVEXTRACTIndex - Return true if the specified
4467 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4468 /// suitable for instruction that extract 128 or 256 bit vectors
4469 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4470   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4471   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4472     return false;
4473
4474   // The index should be aligned on a vecWidth-bit boundary.
4475   uint64_t Index =
4476     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4477
4478   MVT VT = N->getSimpleValueType(0);
4479   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4480   bool Result = (Index * ElSize) % vecWidth == 0;
4481
4482   return Result;
4483 }
4484
4485 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4486 /// operand specifies a subvector insert that is suitable for input to
4487 /// insertion of 128 or 256-bit subvectors
4488 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4489   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4490   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4491     return false;
4492   // The index should be aligned on a vecWidth-bit boundary.
4493   uint64_t Index =
4494     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4495
4496   MVT VT = N->getSimpleValueType(0);
4497   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4498   bool Result = (Index * ElSize) % vecWidth == 0;
4499
4500   return Result;
4501 }
4502
4503 bool X86::isVINSERT128Index(SDNode *N) {
4504   return isVINSERTIndex(N, 128);
4505 }
4506
4507 bool X86::isVINSERT256Index(SDNode *N) {
4508   return isVINSERTIndex(N, 256);
4509 }
4510
4511 bool X86::isVEXTRACT128Index(SDNode *N) {
4512   return isVEXTRACTIndex(N, 128);
4513 }
4514
4515 bool X86::isVEXTRACT256Index(SDNode *N) {
4516   return isVEXTRACTIndex(N, 256);
4517 }
4518
4519 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4520 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4521 /// Handles 128-bit and 256-bit.
4522 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4523   MVT VT = N->getSimpleValueType(0);
4524
4525   assert((VT.getSizeInBits() >= 128) &&
4526          "Unsupported vector type for PSHUF/SHUFP");
4527
4528   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4529   // independently on 128-bit lanes.
4530   unsigned NumElts = VT.getVectorNumElements();
4531   unsigned NumLanes = VT.getSizeInBits()/128;
4532   unsigned NumLaneElts = NumElts/NumLanes;
4533
4534   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4535          "Only supports 2, 4 or 8 elements per lane");
4536
4537   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4538   unsigned Mask = 0;
4539   for (unsigned i = 0; i != NumElts; ++i) {
4540     int Elt = N->getMaskElt(i);
4541     if (Elt < 0) continue;
4542     Elt &= NumLaneElts - 1;
4543     unsigned ShAmt = (i << Shift) % 8;
4544     Mask |= Elt << ShAmt;
4545   }
4546
4547   return Mask;
4548 }
4549
4550 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4551 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4552 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4553   MVT VT = N->getSimpleValueType(0);
4554
4555   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4556          "Unsupported vector type for PSHUFHW");
4557
4558   unsigned NumElts = VT.getVectorNumElements();
4559
4560   unsigned Mask = 0;
4561   for (unsigned l = 0; l != NumElts; l += 8) {
4562     // 8 nodes per lane, but we only care about the last 4.
4563     for (unsigned i = 0; i < 4; ++i) {
4564       int Elt = N->getMaskElt(l+i+4);
4565       if (Elt < 0) continue;
4566       Elt &= 0x3; // only 2-bits.
4567       Mask |= Elt << (i * 2);
4568     }
4569   }
4570
4571   return Mask;
4572 }
4573
4574 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4575 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4576 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4577   MVT VT = N->getSimpleValueType(0);
4578
4579   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4580          "Unsupported vector type for PSHUFHW");
4581
4582   unsigned NumElts = VT.getVectorNumElements();
4583
4584   unsigned Mask = 0;
4585   for (unsigned l = 0; l != NumElts; l += 8) {
4586     // 8 nodes per lane, but we only care about the first 4.
4587     for (unsigned i = 0; i < 4; ++i) {
4588       int Elt = N->getMaskElt(l+i);
4589       if (Elt < 0) continue;
4590       Elt &= 0x3; // only 2-bits
4591       Mask |= Elt << (i * 2);
4592     }
4593   }
4594
4595   return Mask;
4596 }
4597
4598 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4599 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4600 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4601   MVT VT = SVOp->getSimpleValueType(0);
4602   unsigned EltSize = VT.is512BitVector() ? 1 :
4603     VT.getVectorElementType().getSizeInBits() >> 3;
4604
4605   unsigned NumElts = VT.getVectorNumElements();
4606   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4607   unsigned NumLaneElts = NumElts/NumLanes;
4608
4609   int Val = 0;
4610   unsigned i;
4611   for (i = 0; i != NumElts; ++i) {
4612     Val = SVOp->getMaskElt(i);
4613     if (Val >= 0)
4614       break;
4615   }
4616   if (Val >= (int)NumElts)
4617     Val -= NumElts - NumLaneElts;
4618
4619   assert(Val - i > 0 && "PALIGNR imm should be positive");
4620   return (Val - i) * EltSize;
4621 }
4622
4623 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4624   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4625   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4626     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4627
4628   uint64_t Index =
4629     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4630
4631   MVT VecVT = N->getOperand(0).getSimpleValueType();
4632   MVT ElVT = VecVT.getVectorElementType();
4633
4634   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4635   return Index / NumElemsPerChunk;
4636 }
4637
4638 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4639   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4640   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4641     llvm_unreachable("Illegal insert subvector for VINSERT");
4642
4643   uint64_t Index =
4644     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4645
4646   MVT VecVT = N->getSimpleValueType(0);
4647   MVT ElVT = VecVT.getVectorElementType();
4648
4649   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4650   return Index / NumElemsPerChunk;
4651 }
4652
4653 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4654 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4655 /// and VINSERTI128 instructions.
4656 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4657   return getExtractVEXTRACTImmediate(N, 128);
4658 }
4659
4660 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4661 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4662 /// and VINSERTI64x4 instructions.
4663 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4664   return getExtractVEXTRACTImmediate(N, 256);
4665 }
4666
4667 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4668 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4669 /// and VINSERTI128 instructions.
4670 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4671   return getInsertVINSERTImmediate(N, 128);
4672 }
4673
4674 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4675 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4676 /// and VINSERTI64x4 instructions.
4677 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4678   return getInsertVINSERTImmediate(N, 256);
4679 }
4680
4681 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4682 /// constant +0.0.
4683 bool X86::isZeroNode(SDValue Elt) {
4684   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4685     return CN->isNullValue();
4686   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4687     return CFP->getValueAPF().isPosZero();
4688   return false;
4689 }
4690
4691 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4692 /// their permute mask.
4693 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4694                                     SelectionDAG &DAG) {
4695   MVT VT = SVOp->getSimpleValueType(0);
4696   unsigned NumElems = VT.getVectorNumElements();
4697   SmallVector<int, 8> MaskVec;
4698
4699   for (unsigned i = 0; i != NumElems; ++i) {
4700     int Idx = SVOp->getMaskElt(i);
4701     if (Idx >= 0) {
4702       if (Idx < (int)NumElems)
4703         Idx += NumElems;
4704       else
4705         Idx -= NumElems;
4706     }
4707     MaskVec.push_back(Idx);
4708   }
4709   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4710                               SVOp->getOperand(0), &MaskVec[0]);
4711 }
4712
4713 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4714 /// match movhlps. The lower half elements should come from upper half of
4715 /// V1 (and in order), and the upper half elements should come from the upper
4716 /// half of V2 (and in order).
4717 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4718   if (!VT.is128BitVector())
4719     return false;
4720   if (VT.getVectorNumElements() != 4)
4721     return false;
4722   for (unsigned i = 0, e = 2; i != e; ++i)
4723     if (!isUndefOrEqual(Mask[i], i+2))
4724       return false;
4725   for (unsigned i = 2; i != 4; ++i)
4726     if (!isUndefOrEqual(Mask[i], i+4))
4727       return false;
4728   return true;
4729 }
4730
4731 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4732 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4733 /// required.
4734 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4735   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4736     return false;
4737   N = N->getOperand(0).getNode();
4738   if (!ISD::isNON_EXTLoad(N))
4739     return false;
4740   if (LD)
4741     *LD = cast<LoadSDNode>(N);
4742   return true;
4743 }
4744
4745 // Test whether the given value is a vector value which will be legalized
4746 // into a load.
4747 static bool WillBeConstantPoolLoad(SDNode *N) {
4748   if (N->getOpcode() != ISD::BUILD_VECTOR)
4749     return false;
4750
4751   // Check for any non-constant elements.
4752   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4753     switch (N->getOperand(i).getNode()->getOpcode()) {
4754     case ISD::UNDEF:
4755     case ISD::ConstantFP:
4756     case ISD::Constant:
4757       break;
4758     default:
4759       return false;
4760     }
4761
4762   // Vectors of all-zeros and all-ones are materialized with special
4763   // instructions rather than being loaded.
4764   return !ISD::isBuildVectorAllZeros(N) &&
4765          !ISD::isBuildVectorAllOnes(N);
4766 }
4767
4768 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4769 /// match movlp{s|d}. The lower half elements should come from lower half of
4770 /// V1 (and in order), and the upper half elements should come from the upper
4771 /// half of V2 (and in order). And since V1 will become the source of the
4772 /// MOVLP, it must be either a vector load or a scalar load to vector.
4773 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4774                                ArrayRef<int> Mask, MVT VT) {
4775   if (!VT.is128BitVector())
4776     return false;
4777
4778   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4779     return false;
4780   // Is V2 is a vector load, don't do this transformation. We will try to use
4781   // load folding shufps op.
4782   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4783     return false;
4784
4785   unsigned NumElems = VT.getVectorNumElements();
4786
4787   if (NumElems != 2 && NumElems != 4)
4788     return false;
4789   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4790     if (!isUndefOrEqual(Mask[i], i))
4791       return false;
4792   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4793     if (!isUndefOrEqual(Mask[i], i+NumElems))
4794       return false;
4795   return true;
4796 }
4797
4798 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4799 /// all the same.
4800 static bool isSplatVector(SDNode *N) {
4801   if (N->getOpcode() != ISD::BUILD_VECTOR)
4802     return false;
4803
4804   SDValue SplatValue = N->getOperand(0);
4805   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4806     if (N->getOperand(i) != SplatValue)
4807       return false;
4808   return true;
4809 }
4810
4811 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4812 /// to an zero vector.
4813 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4814 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4815   SDValue V1 = N->getOperand(0);
4816   SDValue V2 = N->getOperand(1);
4817   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4818   for (unsigned i = 0; i != NumElems; ++i) {
4819     int Idx = N->getMaskElt(i);
4820     if (Idx >= (int)NumElems) {
4821       unsigned Opc = V2.getOpcode();
4822       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4823         continue;
4824       if (Opc != ISD::BUILD_VECTOR ||
4825           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4826         return false;
4827     } else if (Idx >= 0) {
4828       unsigned Opc = V1.getOpcode();
4829       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4830         continue;
4831       if (Opc != ISD::BUILD_VECTOR ||
4832           !X86::isZeroNode(V1.getOperand(Idx)))
4833         return false;
4834     }
4835   }
4836   return true;
4837 }
4838
4839 /// getZeroVector - Returns a vector of specified type with all zero elements.
4840 ///
4841 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4842                              SelectionDAG &DAG, SDLoc dl) {
4843   assert(VT.isVector() && "Expected a vector type");
4844
4845   // Always build SSE zero vectors as <4 x i32> bitcasted
4846   // to their dest type. This ensures they get CSE'd.
4847   SDValue Vec;
4848   if (VT.is128BitVector()) {  // SSE
4849     if (Subtarget->hasSSE2()) {  // SSE2
4850       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4851       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4852     } else { // SSE1
4853       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4854       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4855     }
4856   } else if (VT.is256BitVector()) { // AVX
4857     if (Subtarget->hasInt256()) { // AVX2
4858       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4859       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4860       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4861     } else {
4862       // 256-bit logic and arithmetic instructions in AVX are all
4863       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4864       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4865       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4866       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4867     }
4868   } else if (VT.is512BitVector()) { // AVX-512
4869       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4870       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4871                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4872       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4873   } else if (VT.getScalarType() == MVT::i1) {
4874     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4875     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4876     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4877     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4878   } else
4879     llvm_unreachable("Unexpected vector type");
4880
4881   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4882 }
4883
4884 /// getOnesVector - Returns a vector of specified type with all bits set.
4885 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4886 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4887 /// Then bitcast to their original type, ensuring they get CSE'd.
4888 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4889                              SDLoc dl) {
4890   assert(VT.isVector() && "Expected a vector type");
4891
4892   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4893   SDValue Vec;
4894   if (VT.is256BitVector()) {
4895     if (HasInt256) { // AVX2
4896       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4897       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4898     } else { // AVX
4899       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4900       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4901     }
4902   } else if (VT.is128BitVector()) {
4903     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4904   } else
4905     llvm_unreachable("Unexpected vector type");
4906
4907   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4908 }
4909
4910 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4911 /// that point to V2 points to its first element.
4912 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4913   for (unsigned i = 0; i != NumElems; ++i) {
4914     if (Mask[i] > (int)NumElems) {
4915       Mask[i] = NumElems;
4916     }
4917   }
4918 }
4919
4920 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4921 /// operation of specified width.
4922 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4923                        SDValue V2) {
4924   unsigned NumElems = VT.getVectorNumElements();
4925   SmallVector<int, 8> Mask;
4926   Mask.push_back(NumElems);
4927   for (unsigned i = 1; i != NumElems; ++i)
4928     Mask.push_back(i);
4929   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4930 }
4931
4932 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4933 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4934                           SDValue V2) {
4935   unsigned NumElems = VT.getVectorNumElements();
4936   SmallVector<int, 8> Mask;
4937   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4938     Mask.push_back(i);
4939     Mask.push_back(i + NumElems);
4940   }
4941   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4942 }
4943
4944 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4945 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4946                           SDValue V2) {
4947   unsigned NumElems = VT.getVectorNumElements();
4948   SmallVector<int, 8> Mask;
4949   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4950     Mask.push_back(i + Half);
4951     Mask.push_back(i + NumElems + Half);
4952   }
4953   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4954 }
4955
4956 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4957 // a generic shuffle instruction because the target has no such instructions.
4958 // Generate shuffles which repeat i16 and i8 several times until they can be
4959 // represented by v4f32 and then be manipulated by target suported shuffles.
4960 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4961   MVT VT = V.getSimpleValueType();
4962   int NumElems = VT.getVectorNumElements();
4963   SDLoc dl(V);
4964
4965   while (NumElems > 4) {
4966     if (EltNo < NumElems/2) {
4967       V = getUnpackl(DAG, dl, VT, V, V);
4968     } else {
4969       V = getUnpackh(DAG, dl, VT, V, V);
4970       EltNo -= NumElems/2;
4971     }
4972     NumElems >>= 1;
4973   }
4974   return V;
4975 }
4976
4977 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4978 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4979   MVT VT = V.getSimpleValueType();
4980   SDLoc dl(V);
4981
4982   if (VT.is128BitVector()) {
4983     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4984     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4985     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4986                              &SplatMask[0]);
4987   } else if (VT.is256BitVector()) {
4988     // To use VPERMILPS to splat scalars, the second half of indicies must
4989     // refer to the higher part, which is a duplication of the lower one,
4990     // because VPERMILPS can only handle in-lane permutations.
4991     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4992                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4993
4994     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4995     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4996                              &SplatMask[0]);
4997   } else
4998     llvm_unreachable("Vector size not supported");
4999
5000   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5001 }
5002
5003 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5004 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5005   MVT SrcVT = SV->getSimpleValueType(0);
5006   SDValue V1 = SV->getOperand(0);
5007   SDLoc dl(SV);
5008
5009   int EltNo = SV->getSplatIndex();
5010   int NumElems = SrcVT.getVectorNumElements();
5011   bool Is256BitVec = SrcVT.is256BitVector();
5012
5013   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5014          "Unknown how to promote splat for type");
5015
5016   // Extract the 128-bit part containing the splat element and update
5017   // the splat element index when it refers to the higher register.
5018   if (Is256BitVec) {
5019     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5020     if (EltNo >= NumElems/2)
5021       EltNo -= NumElems/2;
5022   }
5023
5024   // All i16 and i8 vector types can't be used directly by a generic shuffle
5025   // instruction because the target has no such instruction. Generate shuffles
5026   // which repeat i16 and i8 several times until they fit in i32, and then can
5027   // be manipulated by target suported shuffles.
5028   MVT EltVT = SrcVT.getVectorElementType();
5029   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5030     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5031
5032   // Recreate the 256-bit vector and place the same 128-bit vector
5033   // into the low and high part. This is necessary because we want
5034   // to use VPERM* to shuffle the vectors
5035   if (Is256BitVec) {
5036     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5037   }
5038
5039   return getLegalSplat(DAG, V1, EltNo);
5040 }
5041
5042 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5043 /// vector of zero or undef vector.  This produces a shuffle where the low
5044 /// element of V2 is swizzled into the zero/undef vector, landing at element
5045 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5046 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5047                                            bool IsZero,
5048                                            const X86Subtarget *Subtarget,
5049                                            SelectionDAG &DAG) {
5050   MVT VT = V2.getSimpleValueType();
5051   SDValue V1 = IsZero
5052     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5053   unsigned NumElems = VT.getVectorNumElements();
5054   SmallVector<int, 16> MaskVec;
5055   for (unsigned i = 0; i != NumElems; ++i)
5056     // If this is the insertion idx, put the low elt of V2 here.
5057     MaskVec.push_back(i == Idx ? NumElems : i);
5058   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5059 }
5060
5061 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5062 /// target specific opcode. Returns true if the Mask could be calculated.
5063 /// Sets IsUnary to true if only uses one source.
5064 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5065                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5066   unsigned NumElems = VT.getVectorNumElements();
5067   SDValue ImmN;
5068
5069   IsUnary = false;
5070   switch(N->getOpcode()) {
5071   case X86ISD::SHUFP:
5072     ImmN = N->getOperand(N->getNumOperands()-1);
5073     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5074     break;
5075   case X86ISD::UNPCKH:
5076     DecodeUNPCKHMask(VT, Mask);
5077     break;
5078   case X86ISD::UNPCKL:
5079     DecodeUNPCKLMask(VT, Mask);
5080     break;
5081   case X86ISD::MOVHLPS:
5082     DecodeMOVHLPSMask(NumElems, Mask);
5083     break;
5084   case X86ISD::MOVLHPS:
5085     DecodeMOVLHPSMask(NumElems, Mask);
5086     break;
5087   case X86ISD::PALIGNR:
5088     ImmN = N->getOperand(N->getNumOperands()-1);
5089     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5090     break;
5091   case X86ISD::PSHUFD:
5092   case X86ISD::VPERMILP:
5093     ImmN = N->getOperand(N->getNumOperands()-1);
5094     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5095     IsUnary = true;
5096     break;
5097   case X86ISD::PSHUFHW:
5098     ImmN = N->getOperand(N->getNumOperands()-1);
5099     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5100     IsUnary = true;
5101     break;
5102   case X86ISD::PSHUFLW:
5103     ImmN = N->getOperand(N->getNumOperands()-1);
5104     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5105     IsUnary = true;
5106     break;
5107   case X86ISD::VPERMI:
5108     ImmN = N->getOperand(N->getNumOperands()-1);
5109     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5110     IsUnary = true;
5111     break;
5112   case X86ISD::MOVSS:
5113   case X86ISD::MOVSD: {
5114     // The index 0 always comes from the first element of the second source,
5115     // this is why MOVSS and MOVSD are used in the first place. The other
5116     // elements come from the other positions of the first source vector
5117     Mask.push_back(NumElems);
5118     for (unsigned i = 1; i != NumElems; ++i) {
5119       Mask.push_back(i);
5120     }
5121     break;
5122   }
5123   case X86ISD::VPERM2X128:
5124     ImmN = N->getOperand(N->getNumOperands()-1);
5125     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5126     if (Mask.empty()) return false;
5127     break;
5128   case X86ISD::MOVDDUP:
5129   case X86ISD::MOVLHPD:
5130   case X86ISD::MOVLPD:
5131   case X86ISD::MOVLPS:
5132   case X86ISD::MOVSHDUP:
5133   case X86ISD::MOVSLDUP:
5134     // Not yet implemented
5135     return false;
5136   default: llvm_unreachable("unknown target shuffle node");
5137   }
5138
5139   return true;
5140 }
5141
5142 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5143 /// element of the result of the vector shuffle.
5144 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5145                                    unsigned Depth) {
5146   if (Depth == 6)
5147     return SDValue();  // Limit search depth.
5148
5149   SDValue V = SDValue(N, 0);
5150   EVT VT = V.getValueType();
5151   unsigned Opcode = V.getOpcode();
5152
5153   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5154   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5155     int Elt = SV->getMaskElt(Index);
5156
5157     if (Elt < 0)
5158       return DAG.getUNDEF(VT.getVectorElementType());
5159
5160     unsigned NumElems = VT.getVectorNumElements();
5161     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5162                                          : SV->getOperand(1);
5163     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5164   }
5165
5166   // Recurse into target specific vector shuffles to find scalars.
5167   if (isTargetShuffle(Opcode)) {
5168     MVT ShufVT = V.getSimpleValueType();
5169     unsigned NumElems = ShufVT.getVectorNumElements();
5170     SmallVector<int, 16> ShuffleMask;
5171     bool IsUnary;
5172
5173     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5174       return SDValue();
5175
5176     int Elt = ShuffleMask[Index];
5177     if (Elt < 0)
5178       return DAG.getUNDEF(ShufVT.getVectorElementType());
5179
5180     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5181                                          : N->getOperand(1);
5182     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5183                                Depth+1);
5184   }
5185
5186   // Actual nodes that may contain scalar elements
5187   if (Opcode == ISD::BITCAST) {
5188     V = V.getOperand(0);
5189     EVT SrcVT = V.getValueType();
5190     unsigned NumElems = VT.getVectorNumElements();
5191
5192     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5193       return SDValue();
5194   }
5195
5196   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5197     return (Index == 0) ? V.getOperand(0)
5198                         : DAG.getUNDEF(VT.getVectorElementType());
5199
5200   if (V.getOpcode() == ISD::BUILD_VECTOR)
5201     return V.getOperand(Index);
5202
5203   return SDValue();
5204 }
5205
5206 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5207 /// shuffle operation which come from a consecutively from a zero. The
5208 /// search can start in two different directions, from left or right.
5209 /// We count undefs as zeros until PreferredNum is reached.
5210 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5211                                          unsigned NumElems, bool ZerosFromLeft,
5212                                          SelectionDAG &DAG,
5213                                          unsigned PreferredNum = -1U) {
5214   unsigned NumZeros = 0;
5215   for (unsigned i = 0; i != NumElems; ++i) {
5216     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5217     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5218     if (!Elt.getNode())
5219       break;
5220
5221     if (X86::isZeroNode(Elt))
5222       ++NumZeros;
5223     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5224       NumZeros = std::min(NumZeros + 1, PreferredNum);
5225     else
5226       break;
5227   }
5228
5229   return NumZeros;
5230 }
5231
5232 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5233 /// correspond consecutively to elements from one of the vector operands,
5234 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5235 static
5236 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5237                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5238                               unsigned NumElems, unsigned &OpNum) {
5239   bool SeenV1 = false;
5240   bool SeenV2 = false;
5241
5242   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5243     int Idx = SVOp->getMaskElt(i);
5244     // Ignore undef indicies
5245     if (Idx < 0)
5246       continue;
5247
5248     if (Idx < (int)NumElems)
5249       SeenV1 = true;
5250     else
5251       SeenV2 = true;
5252
5253     // Only accept consecutive elements from the same vector
5254     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5255       return false;
5256   }
5257
5258   OpNum = SeenV1 ? 0 : 1;
5259   return true;
5260 }
5261
5262 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5263 /// logical left shift of a vector.
5264 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5265                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5266   unsigned NumElems =
5267     SVOp->getSimpleValueType(0).getVectorNumElements();
5268   unsigned NumZeros = getNumOfConsecutiveZeros(
5269       SVOp, NumElems, false /* check zeros from right */, DAG,
5270       SVOp->getMaskElt(0));
5271   unsigned OpSrc;
5272
5273   if (!NumZeros)
5274     return false;
5275
5276   // Considering the elements in the mask that are not consecutive zeros,
5277   // check if they consecutively come from only one of the source vectors.
5278   //
5279   //               V1 = {X, A, B, C}     0
5280   //                         \  \  \    /
5281   //   vector_shuffle V1, V2 <1, 2, 3, X>
5282   //
5283   if (!isShuffleMaskConsecutive(SVOp,
5284             0,                   // Mask Start Index
5285             NumElems-NumZeros,   // Mask End Index(exclusive)
5286             NumZeros,            // Where to start looking in the src vector
5287             NumElems,            // Number of elements in vector
5288             OpSrc))              // Which source operand ?
5289     return false;
5290
5291   isLeft = false;
5292   ShAmt = NumZeros;
5293   ShVal = SVOp->getOperand(OpSrc);
5294   return true;
5295 }
5296
5297 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5298 /// logical left shift of a vector.
5299 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5300                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5301   unsigned NumElems =
5302     SVOp->getSimpleValueType(0).getVectorNumElements();
5303   unsigned NumZeros = getNumOfConsecutiveZeros(
5304       SVOp, NumElems, true /* check zeros from left */, DAG,
5305       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5306   unsigned OpSrc;
5307
5308   if (!NumZeros)
5309     return false;
5310
5311   // Considering the elements in the mask that are not consecutive zeros,
5312   // check if they consecutively come from only one of the source vectors.
5313   //
5314   //                           0    { A, B, X, X } = V2
5315   //                          / \    /  /
5316   //   vector_shuffle V1, V2 <X, X, 4, 5>
5317   //
5318   if (!isShuffleMaskConsecutive(SVOp,
5319             NumZeros,     // Mask Start Index
5320             NumElems,     // Mask End Index(exclusive)
5321             0,            // Where to start looking in the src vector
5322             NumElems,     // Number of elements in vector
5323             OpSrc))       // Which source operand ?
5324     return false;
5325
5326   isLeft = true;
5327   ShAmt = NumZeros;
5328   ShVal = SVOp->getOperand(OpSrc);
5329   return true;
5330 }
5331
5332 /// isVectorShift - Returns true if the shuffle can be implemented as a
5333 /// logical left or right shift of a vector.
5334 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5335                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5336   // Although the logic below support any bitwidth size, there are no
5337   // shift instructions which handle more than 128-bit vectors.
5338   if (!SVOp->getSimpleValueType(0).is128BitVector())
5339     return false;
5340
5341   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5342       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5343     return true;
5344
5345   return false;
5346 }
5347
5348 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5349 ///
5350 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5351                                        unsigned NumNonZero, unsigned NumZero,
5352                                        SelectionDAG &DAG,
5353                                        const X86Subtarget* Subtarget,
5354                                        const TargetLowering &TLI) {
5355   if (NumNonZero > 8)
5356     return SDValue();
5357
5358   SDLoc dl(Op);
5359   SDValue V;
5360   bool First = true;
5361   for (unsigned i = 0; i < 16; ++i) {
5362     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5363     if (ThisIsNonZero && First) {
5364       if (NumZero)
5365         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5366       else
5367         V = DAG.getUNDEF(MVT::v8i16);
5368       First = false;
5369     }
5370
5371     if ((i & 1) != 0) {
5372       SDValue ThisElt, LastElt;
5373       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5374       if (LastIsNonZero) {
5375         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5376                               MVT::i16, Op.getOperand(i-1));
5377       }
5378       if (ThisIsNonZero) {
5379         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5380         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5381                               ThisElt, DAG.getConstant(8, MVT::i8));
5382         if (LastIsNonZero)
5383           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5384       } else
5385         ThisElt = LastElt;
5386
5387       if (ThisElt.getNode())
5388         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5389                         DAG.getIntPtrConstant(i/2));
5390     }
5391   }
5392
5393   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5394 }
5395
5396 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5397 ///
5398 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5399                                      unsigned NumNonZero, unsigned NumZero,
5400                                      SelectionDAG &DAG,
5401                                      const X86Subtarget* Subtarget,
5402                                      const TargetLowering &TLI) {
5403   if (NumNonZero > 4)
5404     return SDValue();
5405
5406   SDLoc dl(Op);
5407   SDValue V;
5408   bool First = true;
5409   for (unsigned i = 0; i < 8; ++i) {
5410     bool isNonZero = (NonZeros & (1 << i)) != 0;
5411     if (isNonZero) {
5412       if (First) {
5413         if (NumZero)
5414           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5415         else
5416           V = DAG.getUNDEF(MVT::v8i16);
5417         First = false;
5418       }
5419       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5420                       MVT::v8i16, V, Op.getOperand(i),
5421                       DAG.getIntPtrConstant(i));
5422     }
5423   }
5424
5425   return V;
5426 }
5427
5428 /// getVShift - Return a vector logical shift node.
5429 ///
5430 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5431                          unsigned NumBits, SelectionDAG &DAG,
5432                          const TargetLowering &TLI, SDLoc dl) {
5433   assert(VT.is128BitVector() && "Unknown type for VShift");
5434   EVT ShVT = MVT::v2i64;
5435   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5436   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5437   return DAG.getNode(ISD::BITCAST, dl, VT,
5438                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5439                              DAG.getConstant(NumBits,
5440                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5441 }
5442
5443 static SDValue
5444 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5445
5446   // Check if the scalar load can be widened into a vector load. And if
5447   // the address is "base + cst" see if the cst can be "absorbed" into
5448   // the shuffle mask.
5449   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5450     SDValue Ptr = LD->getBasePtr();
5451     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5452       return SDValue();
5453     EVT PVT = LD->getValueType(0);
5454     if (PVT != MVT::i32 && PVT != MVT::f32)
5455       return SDValue();
5456
5457     int FI = -1;
5458     int64_t Offset = 0;
5459     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5460       FI = FINode->getIndex();
5461       Offset = 0;
5462     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5463                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5464       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5465       Offset = Ptr.getConstantOperandVal(1);
5466       Ptr = Ptr.getOperand(0);
5467     } else {
5468       return SDValue();
5469     }
5470
5471     // FIXME: 256-bit vector instructions don't require a strict alignment,
5472     // improve this code to support it better.
5473     unsigned RequiredAlign = VT.getSizeInBits()/8;
5474     SDValue Chain = LD->getChain();
5475     // Make sure the stack object alignment is at least 16 or 32.
5476     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5477     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5478       if (MFI->isFixedObjectIndex(FI)) {
5479         // Can't change the alignment. FIXME: It's possible to compute
5480         // the exact stack offset and reference FI + adjust offset instead.
5481         // If someone *really* cares about this. That's the way to implement it.
5482         return SDValue();
5483       } else {
5484         MFI->setObjectAlignment(FI, RequiredAlign);
5485       }
5486     }
5487
5488     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5489     // Ptr + (Offset & ~15).
5490     if (Offset < 0)
5491       return SDValue();
5492     if ((Offset % RequiredAlign) & 3)
5493       return SDValue();
5494     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5495     if (StartOffset)
5496       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5497                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5498
5499     int EltNo = (Offset - StartOffset) >> 2;
5500     unsigned NumElems = VT.getVectorNumElements();
5501
5502     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5503     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5504                              LD->getPointerInfo().getWithOffset(StartOffset),
5505                              false, false, false, 0);
5506
5507     SmallVector<int, 8> Mask;
5508     for (unsigned i = 0; i != NumElems; ++i)
5509       Mask.push_back(EltNo);
5510
5511     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5512   }
5513
5514   return SDValue();
5515 }
5516
5517 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5518 /// vector of type 'VT', see if the elements can be replaced by a single large
5519 /// load which has the same value as a build_vector whose operands are 'elts'.
5520 ///
5521 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5522 ///
5523 /// FIXME: we'd also like to handle the case where the last elements are zero
5524 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5525 /// There's even a handy isZeroNode for that purpose.
5526 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5527                                         SDLoc &DL, SelectionDAG &DAG,
5528                                         bool isAfterLegalize) {
5529   EVT EltVT = VT.getVectorElementType();
5530   unsigned NumElems = Elts.size();
5531
5532   LoadSDNode *LDBase = nullptr;
5533   unsigned LastLoadedElt = -1U;
5534
5535   // For each element in the initializer, see if we've found a load or an undef.
5536   // If we don't find an initial load element, or later load elements are
5537   // non-consecutive, bail out.
5538   for (unsigned i = 0; i < NumElems; ++i) {
5539     SDValue Elt = Elts[i];
5540
5541     if (!Elt.getNode() ||
5542         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5543       return SDValue();
5544     if (!LDBase) {
5545       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5546         return SDValue();
5547       LDBase = cast<LoadSDNode>(Elt.getNode());
5548       LastLoadedElt = i;
5549       continue;
5550     }
5551     if (Elt.getOpcode() == ISD::UNDEF)
5552       continue;
5553
5554     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5555     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5556       return SDValue();
5557     LastLoadedElt = i;
5558   }
5559
5560   // If we have found an entire vector of loads and undefs, then return a large
5561   // load of the entire vector width starting at the base pointer.  If we found
5562   // consecutive loads for the low half, generate a vzext_load node.
5563   if (LastLoadedElt == NumElems - 1) {
5564
5565     if (isAfterLegalize &&
5566         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5567       return SDValue();
5568
5569     SDValue NewLd = SDValue();
5570
5571     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5572       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5573                           LDBase->getPointerInfo(),
5574                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5575                           LDBase->isInvariant(), 0);
5576     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5577                         LDBase->getPointerInfo(),
5578                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5579                         LDBase->isInvariant(), LDBase->getAlignment());
5580
5581     if (LDBase->hasAnyUseOfValue(1)) {
5582       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5583                                      SDValue(LDBase, 1),
5584                                      SDValue(NewLd.getNode(), 1));
5585       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5586       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5587                              SDValue(NewLd.getNode(), 1));
5588     }
5589
5590     return NewLd;
5591   }
5592   if (NumElems == 4 && LastLoadedElt == 1 &&
5593       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5594     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5595     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5596     SDValue ResNode =
5597         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5598                                 LDBase->getPointerInfo(),
5599                                 LDBase->getAlignment(),
5600                                 false/*isVolatile*/, true/*ReadMem*/,
5601                                 false/*WriteMem*/);
5602
5603     // Make sure the newly-created LOAD is in the same position as LDBase in
5604     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5605     // update uses of LDBase's output chain to use the TokenFactor.
5606     if (LDBase->hasAnyUseOfValue(1)) {
5607       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5608                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5609       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5610       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5611                              SDValue(ResNode.getNode(), 1));
5612     }
5613
5614     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5615   }
5616   return SDValue();
5617 }
5618
5619 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5620 /// to generate a splat value for the following cases:
5621 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5622 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5623 /// a scalar load, or a constant.
5624 /// The VBROADCAST node is returned when a pattern is found,
5625 /// or SDValue() otherwise.
5626 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5627                                     SelectionDAG &DAG) {
5628   if (!Subtarget->hasFp256())
5629     return SDValue();
5630
5631   MVT VT = Op.getSimpleValueType();
5632   SDLoc dl(Op);
5633
5634   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5635          "Unsupported vector type for broadcast.");
5636
5637   SDValue Ld;
5638   bool ConstSplatVal;
5639
5640   switch (Op.getOpcode()) {
5641     default:
5642       // Unknown pattern found.
5643       return SDValue();
5644
5645     case ISD::BUILD_VECTOR: {
5646       // The BUILD_VECTOR node must be a splat.
5647       if (!isSplatVector(Op.getNode()))
5648         return SDValue();
5649
5650       Ld = Op.getOperand(0);
5651       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5652                      Ld.getOpcode() == ISD::ConstantFP);
5653
5654       // The suspected load node has several users. Make sure that all
5655       // of its users are from the BUILD_VECTOR node.
5656       // Constants may have multiple users.
5657       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5658         return SDValue();
5659       break;
5660     }
5661
5662     case ISD::VECTOR_SHUFFLE: {
5663       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5664
5665       // Shuffles must have a splat mask where the first element is
5666       // broadcasted.
5667       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5668         return SDValue();
5669
5670       SDValue Sc = Op.getOperand(0);
5671       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5672           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5673
5674         if (!Subtarget->hasInt256())
5675           return SDValue();
5676
5677         // Use the register form of the broadcast instruction available on AVX2.
5678         if (VT.getSizeInBits() >= 256)
5679           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5680         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5681       }
5682
5683       Ld = Sc.getOperand(0);
5684       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5685                        Ld.getOpcode() == ISD::ConstantFP);
5686
5687       // The scalar_to_vector node and the suspected
5688       // load node must have exactly one user.
5689       // Constants may have multiple users.
5690
5691       // AVX-512 has register version of the broadcast
5692       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5693         Ld.getValueType().getSizeInBits() >= 32;
5694       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5695           !hasRegVer))
5696         return SDValue();
5697       break;
5698     }
5699   }
5700
5701   bool IsGE256 = (VT.getSizeInBits() >= 256);
5702
5703   // Handle the broadcasting a single constant scalar from the constant pool
5704   // into a vector. On Sandybridge it is still better to load a constant vector
5705   // from the constant pool and not to broadcast it from a scalar.
5706   if (ConstSplatVal && Subtarget->hasInt256()) {
5707     EVT CVT = Ld.getValueType();
5708     assert(!CVT.isVector() && "Must not broadcast a vector type");
5709     unsigned ScalarSize = CVT.getSizeInBits();
5710
5711     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5712       const Constant *C = nullptr;
5713       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5714         C = CI->getConstantIntValue();
5715       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5716         C = CF->getConstantFPValue();
5717
5718       assert(C && "Invalid constant type");
5719
5720       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5721       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5722       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5723       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5724                        MachinePointerInfo::getConstantPool(),
5725                        false, false, false, Alignment);
5726
5727       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5728     }
5729   }
5730
5731   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5732   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5733
5734   // Handle AVX2 in-register broadcasts.
5735   if (!IsLoad && Subtarget->hasInt256() &&
5736       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5737     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5738
5739   // The scalar source must be a normal load.
5740   if (!IsLoad)
5741     return SDValue();
5742
5743   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5744     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5745
5746   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5747   // double since there is no vbroadcastsd xmm
5748   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5749     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5750       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5751   }
5752
5753   // Unsupported broadcast.
5754   return SDValue();
5755 }
5756
5757 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5758 /// underlying vector and index.
5759 ///
5760 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5761 /// index.
5762 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5763                                          SDValue ExtIdx) {
5764   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5765   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5766     return Idx;
5767
5768   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5769   // lowered this:
5770   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5771   // to:
5772   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5773   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5774   //                           undef)
5775   //                       Constant<0>)
5776   // In this case the vector is the extract_subvector expression and the index
5777   // is 2, as specified by the shuffle.
5778   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5779   SDValue ShuffleVec = SVOp->getOperand(0);
5780   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5781   assert(ShuffleVecVT.getVectorElementType() ==
5782          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5783
5784   int ShuffleIdx = SVOp->getMaskElt(Idx);
5785   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5786     ExtractedFromVec = ShuffleVec;
5787     return ShuffleIdx;
5788   }
5789   return Idx;
5790 }
5791
5792 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5793   MVT VT = Op.getSimpleValueType();
5794
5795   // Skip if insert_vec_elt is not supported.
5796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5797   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5798     return SDValue();
5799
5800   SDLoc DL(Op);
5801   unsigned NumElems = Op.getNumOperands();
5802
5803   SDValue VecIn1;
5804   SDValue VecIn2;
5805   SmallVector<unsigned, 4> InsertIndices;
5806   SmallVector<int, 8> Mask(NumElems, -1);
5807
5808   for (unsigned i = 0; i != NumElems; ++i) {
5809     unsigned Opc = Op.getOperand(i).getOpcode();
5810
5811     if (Opc == ISD::UNDEF)
5812       continue;
5813
5814     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5815       // Quit if more than 1 elements need inserting.
5816       if (InsertIndices.size() > 1)
5817         return SDValue();
5818
5819       InsertIndices.push_back(i);
5820       continue;
5821     }
5822
5823     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5824     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5825     // Quit if non-constant index.
5826     if (!isa<ConstantSDNode>(ExtIdx))
5827       return SDValue();
5828     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5829
5830     // Quit if extracted from vector of different type.
5831     if (ExtractedFromVec.getValueType() != VT)
5832       return SDValue();
5833
5834     if (!VecIn1.getNode())
5835       VecIn1 = ExtractedFromVec;
5836     else if (VecIn1 != ExtractedFromVec) {
5837       if (!VecIn2.getNode())
5838         VecIn2 = ExtractedFromVec;
5839       else if (VecIn2 != ExtractedFromVec)
5840         // Quit if more than 2 vectors to shuffle
5841         return SDValue();
5842     }
5843
5844     if (ExtractedFromVec == VecIn1)
5845       Mask[i] = Idx;
5846     else if (ExtractedFromVec == VecIn2)
5847       Mask[i] = Idx + NumElems;
5848   }
5849
5850   if (!VecIn1.getNode())
5851     return SDValue();
5852
5853   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5854   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5855   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5856     unsigned Idx = InsertIndices[i];
5857     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5858                      DAG.getIntPtrConstant(Idx));
5859   }
5860
5861   return NV;
5862 }
5863
5864 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5865 SDValue
5866 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5867
5868   MVT VT = Op.getSimpleValueType();
5869   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5870          "Unexpected type in LowerBUILD_VECTORvXi1!");
5871
5872   SDLoc dl(Op);
5873   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5874     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5875     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5876     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5877   }
5878
5879   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5880     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5881     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5882     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5883   }
5884
5885   bool AllContants = true;
5886   uint64_t Immediate = 0;
5887   int NonConstIdx = -1;
5888   bool IsSplat = true;
5889   unsigned NumNonConsts = 0;
5890   unsigned NumConsts = 0;
5891   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5892     SDValue In = Op.getOperand(idx);
5893     if (In.getOpcode() == ISD::UNDEF)
5894       continue;
5895     if (!isa<ConstantSDNode>(In)) {
5896       AllContants = false;
5897       NonConstIdx = idx;
5898       NumNonConsts++;
5899     }
5900     else {
5901       NumConsts++;
5902       if (cast<ConstantSDNode>(In)->getZExtValue())
5903       Immediate |= (1ULL << idx);
5904     }
5905     if (In != Op.getOperand(0))
5906       IsSplat = false;
5907   }
5908
5909   if (AllContants) {
5910     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5911       DAG.getConstant(Immediate, MVT::i16));
5912     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5913                        DAG.getIntPtrConstant(0));
5914   }
5915
5916   if (NumNonConsts == 1 && NonConstIdx != 0) {
5917     SDValue DstVec;
5918     if (NumConsts) {
5919       SDValue VecAsImm = DAG.getConstant(Immediate,
5920                                          MVT::getIntegerVT(VT.getSizeInBits()));
5921       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5922     }
5923     else 
5924       DstVec = DAG.getUNDEF(VT);
5925     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5926                        Op.getOperand(NonConstIdx),
5927                        DAG.getIntPtrConstant(NonConstIdx));
5928   }
5929   if (!IsSplat && (NonConstIdx != 0))
5930     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5931   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5932   SDValue Select;
5933   if (IsSplat)
5934     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5935                           DAG.getConstant(-1, SelectVT),
5936                           DAG.getConstant(0, SelectVT));
5937   else
5938     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5939                          DAG.getConstant((Immediate | 1), SelectVT),
5940                          DAG.getConstant(Immediate, SelectVT));
5941   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5942 }
5943
5944 SDValue
5945 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5946   SDLoc dl(Op);
5947
5948   MVT VT = Op.getSimpleValueType();
5949   MVT ExtVT = VT.getVectorElementType();
5950   unsigned NumElems = Op.getNumOperands();
5951
5952   // Generate vectors for predicate vectors.
5953   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5954     return LowerBUILD_VECTORvXi1(Op, DAG);
5955
5956   // Vectors containing all zeros can be matched by pxor and xorps later
5957   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5958     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5959     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5960     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5961       return Op;
5962
5963     return getZeroVector(VT, Subtarget, DAG, dl);
5964   }
5965
5966   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5967   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5968   // vpcmpeqd on 256-bit vectors.
5969   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5970     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5971       return Op;
5972
5973     if (!VT.is512BitVector())
5974       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5975   }
5976
5977   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5978   if (Broadcast.getNode())
5979     return Broadcast;
5980
5981   unsigned EVTBits = ExtVT.getSizeInBits();
5982
5983   unsigned NumZero  = 0;
5984   unsigned NumNonZero = 0;
5985   unsigned NonZeros = 0;
5986   bool IsAllConstants = true;
5987   SmallSet<SDValue, 8> Values;
5988   for (unsigned i = 0; i < NumElems; ++i) {
5989     SDValue Elt = Op.getOperand(i);
5990     if (Elt.getOpcode() == ISD::UNDEF)
5991       continue;
5992     Values.insert(Elt);
5993     if (Elt.getOpcode() != ISD::Constant &&
5994         Elt.getOpcode() != ISD::ConstantFP)
5995       IsAllConstants = false;
5996     if (X86::isZeroNode(Elt))
5997       NumZero++;
5998     else {
5999       NonZeros |= (1 << i);
6000       NumNonZero++;
6001     }
6002   }
6003
6004   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6005   if (NumNonZero == 0)
6006     return DAG.getUNDEF(VT);
6007
6008   // Special case for single non-zero, non-undef, element.
6009   if (NumNonZero == 1) {
6010     unsigned Idx = countTrailingZeros(NonZeros);
6011     SDValue Item = Op.getOperand(Idx);
6012
6013     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6014     // the value are obviously zero, truncate the value to i32 and do the
6015     // insertion that way.  Only do this if the value is non-constant or if the
6016     // value is a constant being inserted into element 0.  It is cheaper to do
6017     // a constant pool load than it is to do a movd + shuffle.
6018     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6019         (!IsAllConstants || Idx == 0)) {
6020       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6021         // Handle SSE only.
6022         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6023         EVT VecVT = MVT::v4i32;
6024         unsigned VecElts = 4;
6025
6026         // Truncate the value (which may itself be a constant) to i32, and
6027         // convert it to a vector with movd (S2V+shuffle to zero extend).
6028         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6029         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6030         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6031
6032         // Now we have our 32-bit value zero extended in the low element of
6033         // a vector.  If Idx != 0, swizzle it into place.
6034         if (Idx != 0) {
6035           SmallVector<int, 4> Mask;
6036           Mask.push_back(Idx);
6037           for (unsigned i = 1; i != VecElts; ++i)
6038             Mask.push_back(i);
6039           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6040                                       &Mask[0]);
6041         }
6042         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6043       }
6044     }
6045
6046     // If we have a constant or non-constant insertion into the low element of
6047     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6048     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6049     // depending on what the source datatype is.
6050     if (Idx == 0) {
6051       if (NumZero == 0)
6052         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6053
6054       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6055           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6056         if (VT.is256BitVector() || VT.is512BitVector()) {
6057           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6058           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6059                              Item, DAG.getIntPtrConstant(0));
6060         }
6061         assert(VT.is128BitVector() && "Expected an SSE value type!");
6062         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6063         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6064         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6065       }
6066
6067       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6068         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6069         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6070         if (VT.is256BitVector()) {
6071           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6072           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6073         } else {
6074           assert(VT.is128BitVector() && "Expected an SSE value type!");
6075           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6076         }
6077         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6078       }
6079     }
6080
6081     // Is it a vector logical left shift?
6082     if (NumElems == 2 && Idx == 1 &&
6083         X86::isZeroNode(Op.getOperand(0)) &&
6084         !X86::isZeroNode(Op.getOperand(1))) {
6085       unsigned NumBits = VT.getSizeInBits();
6086       return getVShift(true, VT,
6087                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6088                                    VT, Op.getOperand(1)),
6089                        NumBits/2, DAG, *this, dl);
6090     }
6091
6092     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6093       return SDValue();
6094
6095     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6096     // is a non-constant being inserted into an element other than the low one,
6097     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6098     // movd/movss) to move this into the low element, then shuffle it into
6099     // place.
6100     if (EVTBits == 32) {
6101       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6102
6103       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6104       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6105       SmallVector<int, 8> MaskVec;
6106       for (unsigned i = 0; i != NumElems; ++i)
6107         MaskVec.push_back(i == Idx ? 0 : 1);
6108       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6109     }
6110   }
6111
6112   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6113   if (Values.size() == 1) {
6114     if (EVTBits == 32) {
6115       // Instead of a shuffle like this:
6116       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6117       // Check if it's possible to issue this instead.
6118       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6119       unsigned Idx = countTrailingZeros(NonZeros);
6120       SDValue Item = Op.getOperand(Idx);
6121       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6122         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6123     }
6124     return SDValue();
6125   }
6126
6127   // A vector full of immediates; various special cases are already
6128   // handled, so this is best done with a single constant-pool load.
6129   if (IsAllConstants)
6130     return SDValue();
6131
6132   // For AVX-length vectors, build the individual 128-bit pieces and use
6133   // shuffles to put them in place.
6134   if (VT.is256BitVector() || VT.is512BitVector()) {
6135     SmallVector<SDValue, 64> V;
6136     for (unsigned i = 0; i != NumElems; ++i)
6137       V.push_back(Op.getOperand(i));
6138
6139     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6140
6141     // Build both the lower and upper subvector.
6142     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6143                                 makeArrayRef(&V[0], NumElems/2));
6144     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6145                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6146
6147     // Recreate the wider vector with the lower and upper part.
6148     if (VT.is256BitVector())
6149       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6150     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6151   }
6152
6153   // Let legalizer expand 2-wide build_vectors.
6154   if (EVTBits == 64) {
6155     if (NumNonZero == 1) {
6156       // One half is zero or undef.
6157       unsigned Idx = countTrailingZeros(NonZeros);
6158       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6159                                  Op.getOperand(Idx));
6160       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6161     }
6162     return SDValue();
6163   }
6164
6165   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6166   if (EVTBits == 8 && NumElems == 16) {
6167     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6168                                         Subtarget, *this);
6169     if (V.getNode()) return V;
6170   }
6171
6172   if (EVTBits == 16 && NumElems == 8) {
6173     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6174                                       Subtarget, *this);
6175     if (V.getNode()) return V;
6176   }
6177
6178   // If element VT is == 32 bits, turn it into a number of shuffles.
6179   SmallVector<SDValue, 8> V(NumElems);
6180   if (NumElems == 4 && NumZero > 0) {
6181     for (unsigned i = 0; i < 4; ++i) {
6182       bool isZero = !(NonZeros & (1 << i));
6183       if (isZero)
6184         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6185       else
6186         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6187     }
6188
6189     for (unsigned i = 0; i < 2; ++i) {
6190       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6191         default: break;
6192         case 0:
6193           V[i] = V[i*2];  // Must be a zero vector.
6194           break;
6195         case 1:
6196           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6197           break;
6198         case 2:
6199           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6200           break;
6201         case 3:
6202           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6203           break;
6204       }
6205     }
6206
6207     bool Reverse1 = (NonZeros & 0x3) == 2;
6208     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6209     int MaskVec[] = {
6210       Reverse1 ? 1 : 0,
6211       Reverse1 ? 0 : 1,
6212       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6213       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6214     };
6215     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6216   }
6217
6218   if (Values.size() > 1 && VT.is128BitVector()) {
6219     // Check for a build vector of consecutive loads.
6220     for (unsigned i = 0; i < NumElems; ++i)
6221       V[i] = Op.getOperand(i);
6222
6223     // Check for elements which are consecutive loads.
6224     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6225     if (LD.getNode())
6226       return LD;
6227
6228     // Check for a build vector from mostly shuffle plus few inserting.
6229     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6230     if (Sh.getNode())
6231       return Sh;
6232
6233     // For SSE 4.1, use insertps to put the high elements into the low element.
6234     if (getSubtarget()->hasSSE41()) {
6235       SDValue Result;
6236       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6237         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6238       else
6239         Result = DAG.getUNDEF(VT);
6240
6241       for (unsigned i = 1; i < NumElems; ++i) {
6242         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6243         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6244                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6245       }
6246       return Result;
6247     }
6248
6249     // Otherwise, expand into a number of unpckl*, start by extending each of
6250     // our (non-undef) elements to the full vector width with the element in the
6251     // bottom slot of the vector (which generates no code for SSE).
6252     for (unsigned i = 0; i < NumElems; ++i) {
6253       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6254         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6255       else
6256         V[i] = DAG.getUNDEF(VT);
6257     }
6258
6259     // Next, we iteratively mix elements, e.g. for v4f32:
6260     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6261     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6262     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6263     unsigned EltStride = NumElems >> 1;
6264     while (EltStride != 0) {
6265       for (unsigned i = 0; i < EltStride; ++i) {
6266         // If V[i+EltStride] is undef and this is the first round of mixing,
6267         // then it is safe to just drop this shuffle: V[i] is already in the
6268         // right place, the one element (since it's the first round) being
6269         // inserted as undef can be dropped.  This isn't safe for successive
6270         // rounds because they will permute elements within both vectors.
6271         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6272             EltStride == NumElems/2)
6273           continue;
6274
6275         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6276       }
6277       EltStride >>= 1;
6278     }
6279     return V[0];
6280   }
6281   return SDValue();
6282 }
6283
6284 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6285 // to create 256-bit vectors from two other 128-bit ones.
6286 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6287   SDLoc dl(Op);
6288   MVT ResVT = Op.getSimpleValueType();
6289
6290   assert((ResVT.is256BitVector() ||
6291           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6292
6293   SDValue V1 = Op.getOperand(0);
6294   SDValue V2 = Op.getOperand(1);
6295   unsigned NumElems = ResVT.getVectorNumElements();
6296   if(ResVT.is256BitVector())
6297     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6298
6299   if (Op.getNumOperands() == 4) {
6300     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6301                                 ResVT.getVectorNumElements()/2);
6302     SDValue V3 = Op.getOperand(2);
6303     SDValue V4 = Op.getOperand(3);
6304     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6305       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6306   }
6307   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6308 }
6309
6310 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6311   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6312   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6313          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6314           Op.getNumOperands() == 4)));
6315
6316   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6317   // from two other 128-bit ones.
6318
6319   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6320   return LowerAVXCONCAT_VECTORS(Op, DAG);
6321 }
6322
6323 // Try to lower a shuffle node into a simple blend instruction.
6324 static SDValue
6325 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6326                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6327   SDValue V1 = SVOp->getOperand(0);
6328   SDValue V2 = SVOp->getOperand(1);
6329   SDLoc dl(SVOp);
6330   MVT VT = SVOp->getSimpleValueType(0);
6331   MVT EltVT = VT.getVectorElementType();
6332   unsigned NumElems = VT.getVectorNumElements();
6333
6334   // There is no blend with immediate in AVX-512.
6335   if (VT.is512BitVector())
6336     return SDValue();
6337
6338   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6339     return SDValue();
6340   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6341     return SDValue();
6342
6343   // Check the mask for BLEND and build the value.
6344   unsigned MaskValue = 0;
6345   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6346   unsigned NumLanes = (NumElems-1)/8 + 1;
6347   unsigned NumElemsInLane = NumElems / NumLanes;
6348
6349   // Blend for v16i16 should be symetric for the both lanes.
6350   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6351
6352     int SndLaneEltIdx = (NumLanes == 2) ?
6353       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6354     int EltIdx = SVOp->getMaskElt(i);
6355
6356     if ((EltIdx < 0 || EltIdx == (int)i) &&
6357         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6358       continue;
6359
6360     if (((unsigned)EltIdx == (i + NumElems)) &&
6361         (SndLaneEltIdx < 0 ||
6362          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6363       MaskValue |= (1<<i);
6364     else
6365       return SDValue();
6366   }
6367
6368   // Convert i32 vectors to floating point if it is not AVX2.
6369   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6370   MVT BlendVT = VT;
6371   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6372     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6373                                NumElems);
6374     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6375     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6376   }
6377
6378   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6379                             DAG.getConstant(MaskValue, MVT::i32));
6380   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6381 }
6382
6383 /// In vector type \p VT, return true if the element at index \p InputIdx
6384 /// falls on a different 128-bit lane than \p OutputIdx.
6385 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6386                                      unsigned OutputIdx) {
6387   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6388   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6389 }
6390
6391 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6392 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6393 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6394 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6395 /// zero.
6396 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6397                          SelectionDAG &DAG) {
6398   MVT VT = V1.getSimpleValueType();
6399   assert(VT.is128BitVector() || VT.is256BitVector());
6400
6401   MVT EltVT = VT.getVectorElementType();
6402   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6403   unsigned NumElts = VT.getVectorNumElements();
6404
6405   SmallVector<SDValue, 32> PshufbMask;
6406   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6407     int InputIdx = MaskVals[OutputIdx];
6408     unsigned InputByteIdx;
6409
6410     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6411       InputByteIdx = 0x80;
6412     else {
6413       // Cross lane is not allowed.
6414       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6415         return SDValue();
6416       InputByteIdx = InputIdx * EltSizeInBytes;
6417       // Index is an byte offset within the 128-bit lane.
6418       InputByteIdx &= 0xf;
6419     }
6420
6421     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6422       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6423       if (InputByteIdx != 0x80)
6424         ++InputByteIdx;
6425     }
6426   }
6427
6428   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6429   if (ShufVT != VT)
6430     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6431   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6432                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6433 }
6434
6435 // v8i16 shuffles - Prefer shuffles in the following order:
6436 // 1. [all]   pshuflw, pshufhw, optional move
6437 // 2. [ssse3] 1 x pshufb
6438 // 3. [ssse3] 2 x pshufb + 1 x por
6439 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6440 static SDValue
6441 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6442                          SelectionDAG &DAG) {
6443   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6444   SDValue V1 = SVOp->getOperand(0);
6445   SDValue V2 = SVOp->getOperand(1);
6446   SDLoc dl(SVOp);
6447   SmallVector<int, 8> MaskVals;
6448
6449   // Determine if more than 1 of the words in each of the low and high quadwords
6450   // of the result come from the same quadword of one of the two inputs.  Undef
6451   // mask values count as coming from any quadword, for better codegen.
6452   //
6453   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6454   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6455   unsigned LoQuad[] = { 0, 0, 0, 0 };
6456   unsigned HiQuad[] = { 0, 0, 0, 0 };
6457   // Indices of quads used.
6458   std::bitset<4> InputQuads;
6459   for (unsigned i = 0; i < 8; ++i) {
6460     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6461     int EltIdx = SVOp->getMaskElt(i);
6462     MaskVals.push_back(EltIdx);
6463     if (EltIdx < 0) {
6464       ++Quad[0];
6465       ++Quad[1];
6466       ++Quad[2];
6467       ++Quad[3];
6468       continue;
6469     }
6470     ++Quad[EltIdx / 4];
6471     InputQuads.set(EltIdx / 4);
6472   }
6473
6474   int BestLoQuad = -1;
6475   unsigned MaxQuad = 1;
6476   for (unsigned i = 0; i < 4; ++i) {
6477     if (LoQuad[i] > MaxQuad) {
6478       BestLoQuad = i;
6479       MaxQuad = LoQuad[i];
6480     }
6481   }
6482
6483   int BestHiQuad = -1;
6484   MaxQuad = 1;
6485   for (unsigned i = 0; i < 4; ++i) {
6486     if (HiQuad[i] > MaxQuad) {
6487       BestHiQuad = i;
6488       MaxQuad = HiQuad[i];
6489     }
6490   }
6491
6492   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6493   // of the two input vectors, shuffle them into one input vector so only a
6494   // single pshufb instruction is necessary. If there are more than 2 input
6495   // quads, disable the next transformation since it does not help SSSE3.
6496   bool V1Used = InputQuads[0] || InputQuads[1];
6497   bool V2Used = InputQuads[2] || InputQuads[3];
6498   if (Subtarget->hasSSSE3()) {
6499     if (InputQuads.count() == 2 && V1Used && V2Used) {
6500       BestLoQuad = InputQuads[0] ? 0 : 1;
6501       BestHiQuad = InputQuads[2] ? 2 : 3;
6502     }
6503     if (InputQuads.count() > 2) {
6504       BestLoQuad = -1;
6505       BestHiQuad = -1;
6506     }
6507   }
6508
6509   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6510   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6511   // words from all 4 input quadwords.
6512   SDValue NewV;
6513   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6514     int MaskV[] = {
6515       BestLoQuad < 0 ? 0 : BestLoQuad,
6516       BestHiQuad < 0 ? 1 : BestHiQuad
6517     };
6518     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6519                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6520                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6521     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6522
6523     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6524     // source words for the shuffle, to aid later transformations.
6525     bool AllWordsInNewV = true;
6526     bool InOrder[2] = { true, true };
6527     for (unsigned i = 0; i != 8; ++i) {
6528       int idx = MaskVals[i];
6529       if (idx != (int)i)
6530         InOrder[i/4] = false;
6531       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6532         continue;
6533       AllWordsInNewV = false;
6534       break;
6535     }
6536
6537     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6538     if (AllWordsInNewV) {
6539       for (int i = 0; i != 8; ++i) {
6540         int idx = MaskVals[i];
6541         if (idx < 0)
6542           continue;
6543         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6544         if ((idx != i) && idx < 4)
6545           pshufhw = false;
6546         if ((idx != i) && idx > 3)
6547           pshuflw = false;
6548       }
6549       V1 = NewV;
6550       V2Used = false;
6551       BestLoQuad = 0;
6552       BestHiQuad = 1;
6553     }
6554
6555     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6556     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6557     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6558       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6559       unsigned TargetMask = 0;
6560       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6561                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6562       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6563       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6564                              getShufflePSHUFLWImmediate(SVOp);
6565       V1 = NewV.getOperand(0);
6566       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6567     }
6568   }
6569
6570   // Promote splats to a larger type which usually leads to more efficient code.
6571   // FIXME: Is this true if pshufb is available?
6572   if (SVOp->isSplat())
6573     return PromoteSplat(SVOp, DAG);
6574
6575   // If we have SSSE3, and all words of the result are from 1 input vector,
6576   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6577   // is present, fall back to case 4.
6578   if (Subtarget->hasSSSE3()) {
6579     SmallVector<SDValue,16> pshufbMask;
6580
6581     // If we have elements from both input vectors, set the high bit of the
6582     // shuffle mask element to zero out elements that come from V2 in the V1
6583     // mask, and elements that come from V1 in the V2 mask, so that the two
6584     // results can be OR'd together.
6585     bool TwoInputs = V1Used && V2Used;
6586     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6587     if (!TwoInputs)
6588       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6589
6590     // Calculate the shuffle mask for the second input, shuffle it, and
6591     // OR it with the first shuffled input.
6592     CommuteVectorShuffleMask(MaskVals, 8);
6593     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6594     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6595     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6596   }
6597
6598   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6599   // and update MaskVals with new element order.
6600   std::bitset<8> InOrder;
6601   if (BestLoQuad >= 0) {
6602     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6603     for (int i = 0; i != 4; ++i) {
6604       int idx = MaskVals[i];
6605       if (idx < 0) {
6606         InOrder.set(i);
6607       } else if ((idx / 4) == BestLoQuad) {
6608         MaskV[i] = idx & 3;
6609         InOrder.set(i);
6610       }
6611     }
6612     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6613                                 &MaskV[0]);
6614
6615     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6616       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6617       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6618                                   NewV.getOperand(0),
6619                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6620     }
6621   }
6622
6623   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6624   // and update MaskVals with the new element order.
6625   if (BestHiQuad >= 0) {
6626     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6627     for (unsigned i = 4; i != 8; ++i) {
6628       int idx = MaskVals[i];
6629       if (idx < 0) {
6630         InOrder.set(i);
6631       } else if ((idx / 4) == BestHiQuad) {
6632         MaskV[i] = (idx & 3) + 4;
6633         InOrder.set(i);
6634       }
6635     }
6636     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6637                                 &MaskV[0]);
6638
6639     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6640       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6641       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6642                                   NewV.getOperand(0),
6643                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6644     }
6645   }
6646
6647   // In case BestHi & BestLo were both -1, which means each quadword has a word
6648   // from each of the four input quadwords, calculate the InOrder bitvector now
6649   // before falling through to the insert/extract cleanup.
6650   if (BestLoQuad == -1 && BestHiQuad == -1) {
6651     NewV = V1;
6652     for (int i = 0; i != 8; ++i)
6653       if (MaskVals[i] < 0 || MaskVals[i] == i)
6654         InOrder.set(i);
6655   }
6656
6657   // The other elements are put in the right place using pextrw and pinsrw.
6658   for (unsigned i = 0; i != 8; ++i) {
6659     if (InOrder[i])
6660       continue;
6661     int EltIdx = MaskVals[i];
6662     if (EltIdx < 0)
6663       continue;
6664     SDValue ExtOp = (EltIdx < 8) ?
6665       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6666                   DAG.getIntPtrConstant(EltIdx)) :
6667       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6668                   DAG.getIntPtrConstant(EltIdx - 8));
6669     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6670                        DAG.getIntPtrConstant(i));
6671   }
6672   return NewV;
6673 }
6674
6675 /// \brief v16i16 shuffles
6676 ///
6677 /// FIXME: We only support generation of a single pshufb currently.  We can
6678 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6679 /// well (e.g 2 x pshufb + 1 x por).
6680 static SDValue
6681 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6682   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6683   SDValue V1 = SVOp->getOperand(0);
6684   SDValue V2 = SVOp->getOperand(1);
6685   SDLoc dl(SVOp);
6686
6687   if (V2.getOpcode() != ISD::UNDEF)
6688     return SDValue();
6689
6690   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6691   return getPSHUFB(MaskVals, V1, dl, DAG);
6692 }
6693
6694 // v16i8 shuffles - Prefer shuffles in the following order:
6695 // 1. [ssse3] 1 x pshufb
6696 // 2. [ssse3] 2 x pshufb + 1 x por
6697 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6698 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6699                                         const X86Subtarget* Subtarget,
6700                                         SelectionDAG &DAG) {
6701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6702   SDValue V1 = SVOp->getOperand(0);
6703   SDValue V2 = SVOp->getOperand(1);
6704   SDLoc dl(SVOp);
6705   ArrayRef<int> MaskVals = SVOp->getMask();
6706
6707   // Promote splats to a larger type which usually leads to more efficient code.
6708   // FIXME: Is this true if pshufb is available?
6709   if (SVOp->isSplat())
6710     return PromoteSplat(SVOp, DAG);
6711
6712   // If we have SSSE3, case 1 is generated when all result bytes come from
6713   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6714   // present, fall back to case 3.
6715
6716   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6717   if (Subtarget->hasSSSE3()) {
6718     SmallVector<SDValue,16> pshufbMask;
6719
6720     // If all result elements are from one input vector, then only translate
6721     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6722     //
6723     // Otherwise, we have elements from both input vectors, and must zero out
6724     // elements that come from V2 in the first mask, and V1 in the second mask
6725     // so that we can OR them together.
6726     for (unsigned i = 0; i != 16; ++i) {
6727       int EltIdx = MaskVals[i];
6728       if (EltIdx < 0 || EltIdx >= 16)
6729         EltIdx = 0x80;
6730       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6731     }
6732     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6733                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6734                                  MVT::v16i8, pshufbMask));
6735
6736     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6737     // the 2nd operand if it's undefined or zero.
6738     if (V2.getOpcode() == ISD::UNDEF ||
6739         ISD::isBuildVectorAllZeros(V2.getNode()))
6740       return V1;
6741
6742     // Calculate the shuffle mask for the second input, shuffle it, and
6743     // OR it with the first shuffled input.
6744     pshufbMask.clear();
6745     for (unsigned i = 0; i != 16; ++i) {
6746       int EltIdx = MaskVals[i];
6747       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6748       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6749     }
6750     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6751                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6752                                  MVT::v16i8, pshufbMask));
6753     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6754   }
6755
6756   // No SSSE3 - Calculate in place words and then fix all out of place words
6757   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6758   // the 16 different words that comprise the two doublequadword input vectors.
6759   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6760   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6761   SDValue NewV = V1;
6762   for (int i = 0; i != 8; ++i) {
6763     int Elt0 = MaskVals[i*2];
6764     int Elt1 = MaskVals[i*2+1];
6765
6766     // This word of the result is all undef, skip it.
6767     if (Elt0 < 0 && Elt1 < 0)
6768       continue;
6769
6770     // This word of the result is already in the correct place, skip it.
6771     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6772       continue;
6773
6774     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6775     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6776     SDValue InsElt;
6777
6778     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6779     // using a single extract together, load it and store it.
6780     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6781       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6782                            DAG.getIntPtrConstant(Elt1 / 2));
6783       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6784                         DAG.getIntPtrConstant(i));
6785       continue;
6786     }
6787
6788     // If Elt1 is defined, extract it from the appropriate source.  If the
6789     // source byte is not also odd, shift the extracted word left 8 bits
6790     // otherwise clear the bottom 8 bits if we need to do an or.
6791     if (Elt1 >= 0) {
6792       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6793                            DAG.getIntPtrConstant(Elt1 / 2));
6794       if ((Elt1 & 1) == 0)
6795         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6796                              DAG.getConstant(8,
6797                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6798       else if (Elt0 >= 0)
6799         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6800                              DAG.getConstant(0xFF00, MVT::i16));
6801     }
6802     // If Elt0 is defined, extract it from the appropriate source.  If the
6803     // source byte is not also even, shift the extracted word right 8 bits. If
6804     // Elt1 was also defined, OR the extracted values together before
6805     // inserting them in the result.
6806     if (Elt0 >= 0) {
6807       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6808                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6809       if ((Elt0 & 1) != 0)
6810         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6811                               DAG.getConstant(8,
6812                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6813       else if (Elt1 >= 0)
6814         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6815                              DAG.getConstant(0x00FF, MVT::i16));
6816       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6817                          : InsElt0;
6818     }
6819     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6820                        DAG.getIntPtrConstant(i));
6821   }
6822   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6823 }
6824
6825 // v32i8 shuffles - Translate to VPSHUFB if possible.
6826 static
6827 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6828                                  const X86Subtarget *Subtarget,
6829                                  SelectionDAG &DAG) {
6830   MVT VT = SVOp->getSimpleValueType(0);
6831   SDValue V1 = SVOp->getOperand(0);
6832   SDValue V2 = SVOp->getOperand(1);
6833   SDLoc dl(SVOp);
6834   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6835
6836   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6837   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6838   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6839
6840   // VPSHUFB may be generated if
6841   // (1) one of input vector is undefined or zeroinitializer.
6842   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6843   // And (2) the mask indexes don't cross the 128-bit lane.
6844   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6845       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6846     return SDValue();
6847
6848   if (V1IsAllZero && !V2IsAllZero) {
6849     CommuteVectorShuffleMask(MaskVals, 32);
6850     V1 = V2;
6851   }
6852   return getPSHUFB(MaskVals, V1, dl, DAG);
6853 }
6854
6855 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6856 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6857 /// done when every pair / quad of shuffle mask elements point to elements in
6858 /// the right sequence. e.g.
6859 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6860 static
6861 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6862                                  SelectionDAG &DAG) {
6863   MVT VT = SVOp->getSimpleValueType(0);
6864   SDLoc dl(SVOp);
6865   unsigned NumElems = VT.getVectorNumElements();
6866   MVT NewVT;
6867   unsigned Scale;
6868   switch (VT.SimpleTy) {
6869   default: llvm_unreachable("Unexpected!");
6870   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6871   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6872   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6873   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6874   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6875   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6876   }
6877
6878   SmallVector<int, 8> MaskVec;
6879   for (unsigned i = 0; i != NumElems; i += Scale) {
6880     int StartIdx = -1;
6881     for (unsigned j = 0; j != Scale; ++j) {
6882       int EltIdx = SVOp->getMaskElt(i+j);
6883       if (EltIdx < 0)
6884         continue;
6885       if (StartIdx < 0)
6886         StartIdx = (EltIdx / Scale);
6887       if (EltIdx != (int)(StartIdx*Scale + j))
6888         return SDValue();
6889     }
6890     MaskVec.push_back(StartIdx);
6891   }
6892
6893   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6894   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6895   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6896 }
6897
6898 /// getVZextMovL - Return a zero-extending vector move low node.
6899 ///
6900 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6901                             SDValue SrcOp, SelectionDAG &DAG,
6902                             const X86Subtarget *Subtarget, SDLoc dl) {
6903   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6904     LoadSDNode *LD = nullptr;
6905     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6906       LD = dyn_cast<LoadSDNode>(SrcOp);
6907     if (!LD) {
6908       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6909       // instead.
6910       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6911       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6912           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6913           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6914           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6915         // PR2108
6916         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6917         return DAG.getNode(ISD::BITCAST, dl, VT,
6918                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6919                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6920                                                    OpVT,
6921                                                    SrcOp.getOperand(0)
6922                                                           .getOperand(0))));
6923       }
6924     }
6925   }
6926
6927   return DAG.getNode(ISD::BITCAST, dl, VT,
6928                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6929                                  DAG.getNode(ISD::BITCAST, dl,
6930                                              OpVT, SrcOp)));
6931 }
6932
6933 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6934 /// which could not be matched by any known target speficic shuffle
6935 static SDValue
6936 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6937
6938   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6939   if (NewOp.getNode())
6940     return NewOp;
6941
6942   MVT VT = SVOp->getSimpleValueType(0);
6943
6944   unsigned NumElems = VT.getVectorNumElements();
6945   unsigned NumLaneElems = NumElems / 2;
6946
6947   SDLoc dl(SVOp);
6948   MVT EltVT = VT.getVectorElementType();
6949   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6950   SDValue Output[2];
6951
6952   SmallVector<int, 16> Mask;
6953   for (unsigned l = 0; l < 2; ++l) {
6954     // Build a shuffle mask for the output, discovering on the fly which
6955     // input vectors to use as shuffle operands (recorded in InputUsed).
6956     // If building a suitable shuffle vector proves too hard, then bail
6957     // out with UseBuildVector set.
6958     bool UseBuildVector = false;
6959     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6960     unsigned LaneStart = l * NumLaneElems;
6961     for (unsigned i = 0; i != NumLaneElems; ++i) {
6962       // The mask element.  This indexes into the input.
6963       int Idx = SVOp->getMaskElt(i+LaneStart);
6964       if (Idx < 0) {
6965         // the mask element does not index into any input vector.
6966         Mask.push_back(-1);
6967         continue;
6968       }
6969
6970       // The input vector this mask element indexes into.
6971       int Input = Idx / NumLaneElems;
6972
6973       // Turn the index into an offset from the start of the input vector.
6974       Idx -= Input * NumLaneElems;
6975
6976       // Find or create a shuffle vector operand to hold this input.
6977       unsigned OpNo;
6978       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6979         if (InputUsed[OpNo] == Input)
6980           // This input vector is already an operand.
6981           break;
6982         if (InputUsed[OpNo] < 0) {
6983           // Create a new operand for this input vector.
6984           InputUsed[OpNo] = Input;
6985           break;
6986         }
6987       }
6988
6989       if (OpNo >= array_lengthof(InputUsed)) {
6990         // More than two input vectors used!  Give up on trying to create a
6991         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6992         UseBuildVector = true;
6993         break;
6994       }
6995
6996       // Add the mask index for the new shuffle vector.
6997       Mask.push_back(Idx + OpNo * NumLaneElems);
6998     }
6999
7000     if (UseBuildVector) {
7001       SmallVector<SDValue, 16> SVOps;
7002       for (unsigned i = 0; i != NumLaneElems; ++i) {
7003         // The mask element.  This indexes into the input.
7004         int Idx = SVOp->getMaskElt(i+LaneStart);
7005         if (Idx < 0) {
7006           SVOps.push_back(DAG.getUNDEF(EltVT));
7007           continue;
7008         }
7009
7010         // The input vector this mask element indexes into.
7011         int Input = Idx / NumElems;
7012
7013         // Turn the index into an offset from the start of the input vector.
7014         Idx -= Input * NumElems;
7015
7016         // Extract the vector element by hand.
7017         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7018                                     SVOp->getOperand(Input),
7019                                     DAG.getIntPtrConstant(Idx)));
7020       }
7021
7022       // Construct the output using a BUILD_VECTOR.
7023       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7024     } else if (InputUsed[0] < 0) {
7025       // No input vectors were used! The result is undefined.
7026       Output[l] = DAG.getUNDEF(NVT);
7027     } else {
7028       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7029                                         (InputUsed[0] % 2) * NumLaneElems,
7030                                         DAG, dl);
7031       // If only one input was used, use an undefined vector for the other.
7032       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7033         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7034                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7035       // At least one input vector was used. Create a new shuffle vector.
7036       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7037     }
7038
7039     Mask.clear();
7040   }
7041
7042   // Concatenate the result back
7043   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7044 }
7045
7046 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7047 /// 4 elements, and match them with several different shuffle types.
7048 static SDValue
7049 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7050   SDValue V1 = SVOp->getOperand(0);
7051   SDValue V2 = SVOp->getOperand(1);
7052   SDLoc dl(SVOp);
7053   MVT VT = SVOp->getSimpleValueType(0);
7054
7055   assert(VT.is128BitVector() && "Unsupported vector size");
7056
7057   std::pair<int, int> Locs[4];
7058   int Mask1[] = { -1, -1, -1, -1 };
7059   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7060
7061   unsigned NumHi = 0;
7062   unsigned NumLo = 0;
7063   for (unsigned i = 0; i != 4; ++i) {
7064     int Idx = PermMask[i];
7065     if (Idx < 0) {
7066       Locs[i] = std::make_pair(-1, -1);
7067     } else {
7068       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7069       if (Idx < 4) {
7070         Locs[i] = std::make_pair(0, NumLo);
7071         Mask1[NumLo] = Idx;
7072         NumLo++;
7073       } else {
7074         Locs[i] = std::make_pair(1, NumHi);
7075         if (2+NumHi < 4)
7076           Mask1[2+NumHi] = Idx;
7077         NumHi++;
7078       }
7079     }
7080   }
7081
7082   if (NumLo <= 2 && NumHi <= 2) {
7083     // If no more than two elements come from either vector. This can be
7084     // implemented with two shuffles. First shuffle gather the elements.
7085     // The second shuffle, which takes the first shuffle as both of its
7086     // vector operands, put the elements into the right order.
7087     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7088
7089     int Mask2[] = { -1, -1, -1, -1 };
7090
7091     for (unsigned i = 0; i != 4; ++i)
7092       if (Locs[i].first != -1) {
7093         unsigned Idx = (i < 2) ? 0 : 4;
7094         Idx += Locs[i].first * 2 + Locs[i].second;
7095         Mask2[i] = Idx;
7096       }
7097
7098     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7099   }
7100
7101   if (NumLo == 3 || NumHi == 3) {
7102     // Otherwise, we must have three elements from one vector, call it X, and
7103     // one element from the other, call it Y.  First, use a shufps to build an
7104     // intermediate vector with the one element from Y and the element from X
7105     // that will be in the same half in the final destination (the indexes don't
7106     // matter). Then, use a shufps to build the final vector, taking the half
7107     // containing the element from Y from the intermediate, and the other half
7108     // from X.
7109     if (NumHi == 3) {
7110       // Normalize it so the 3 elements come from V1.
7111       CommuteVectorShuffleMask(PermMask, 4);
7112       std::swap(V1, V2);
7113     }
7114
7115     // Find the element from V2.
7116     unsigned HiIndex;
7117     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7118       int Val = PermMask[HiIndex];
7119       if (Val < 0)
7120         continue;
7121       if (Val >= 4)
7122         break;
7123     }
7124
7125     Mask1[0] = PermMask[HiIndex];
7126     Mask1[1] = -1;
7127     Mask1[2] = PermMask[HiIndex^1];
7128     Mask1[3] = -1;
7129     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7130
7131     if (HiIndex >= 2) {
7132       Mask1[0] = PermMask[0];
7133       Mask1[1] = PermMask[1];
7134       Mask1[2] = HiIndex & 1 ? 6 : 4;
7135       Mask1[3] = HiIndex & 1 ? 4 : 6;
7136       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7137     }
7138
7139     Mask1[0] = HiIndex & 1 ? 2 : 0;
7140     Mask1[1] = HiIndex & 1 ? 0 : 2;
7141     Mask1[2] = PermMask[2];
7142     Mask1[3] = PermMask[3];
7143     if (Mask1[2] >= 0)
7144       Mask1[2] += 4;
7145     if (Mask1[3] >= 0)
7146       Mask1[3] += 4;
7147     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7148   }
7149
7150   // Break it into (shuffle shuffle_hi, shuffle_lo).
7151   int LoMask[] = { -1, -1, -1, -1 };
7152   int HiMask[] = { -1, -1, -1, -1 };
7153
7154   int *MaskPtr = LoMask;
7155   unsigned MaskIdx = 0;
7156   unsigned LoIdx = 0;
7157   unsigned HiIdx = 2;
7158   for (unsigned i = 0; i != 4; ++i) {
7159     if (i == 2) {
7160       MaskPtr = HiMask;
7161       MaskIdx = 1;
7162       LoIdx = 0;
7163       HiIdx = 2;
7164     }
7165     int Idx = PermMask[i];
7166     if (Idx < 0) {
7167       Locs[i] = std::make_pair(-1, -1);
7168     } else if (Idx < 4) {
7169       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7170       MaskPtr[LoIdx] = Idx;
7171       LoIdx++;
7172     } else {
7173       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7174       MaskPtr[HiIdx] = Idx;
7175       HiIdx++;
7176     }
7177   }
7178
7179   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7180   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7181   int MaskOps[] = { -1, -1, -1, -1 };
7182   for (unsigned i = 0; i != 4; ++i)
7183     if (Locs[i].first != -1)
7184       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7185   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7186 }
7187
7188 static bool MayFoldVectorLoad(SDValue V) {
7189   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7190     V = V.getOperand(0);
7191
7192   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7193     V = V.getOperand(0);
7194   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7195       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7196     // BUILD_VECTOR (load), undef
7197     V = V.getOperand(0);
7198
7199   return MayFoldLoad(V);
7200 }
7201
7202 static
7203 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7204   MVT VT = Op.getSimpleValueType();
7205
7206   // Canonizalize to v2f64.
7207   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7208   return DAG.getNode(ISD::BITCAST, dl, VT,
7209                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7210                                           V1, DAG));
7211 }
7212
7213 static
7214 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7215                         bool HasSSE2) {
7216   SDValue V1 = Op.getOperand(0);
7217   SDValue V2 = Op.getOperand(1);
7218   MVT VT = Op.getSimpleValueType();
7219
7220   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7221
7222   if (HasSSE2 && VT == MVT::v2f64)
7223     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7224
7225   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7226   return DAG.getNode(ISD::BITCAST, dl, VT,
7227                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7228                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7229                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7230 }
7231
7232 static
7233 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7234   SDValue V1 = Op.getOperand(0);
7235   SDValue V2 = Op.getOperand(1);
7236   MVT VT = Op.getSimpleValueType();
7237
7238   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7239          "unsupported shuffle type");
7240
7241   if (V2.getOpcode() == ISD::UNDEF)
7242     V2 = V1;
7243
7244   // v4i32 or v4f32
7245   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7246 }
7247
7248 static
7249 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7250   SDValue V1 = Op.getOperand(0);
7251   SDValue V2 = Op.getOperand(1);
7252   MVT VT = Op.getSimpleValueType();
7253   unsigned NumElems = VT.getVectorNumElements();
7254
7255   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7256   // operand of these instructions is only memory, so check if there's a
7257   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7258   // same masks.
7259   bool CanFoldLoad = false;
7260
7261   // Trivial case, when V2 comes from a load.
7262   if (MayFoldVectorLoad(V2))
7263     CanFoldLoad = true;
7264
7265   // When V1 is a load, it can be folded later into a store in isel, example:
7266   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7267   //    turns into:
7268   //  (MOVLPSmr addr:$src1, VR128:$src2)
7269   // So, recognize this potential and also use MOVLPS or MOVLPD
7270   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7271     CanFoldLoad = true;
7272
7273   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7274   if (CanFoldLoad) {
7275     if (HasSSE2 && NumElems == 2)
7276       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7277
7278     if (NumElems == 4)
7279       // If we don't care about the second element, proceed to use movss.
7280       if (SVOp->getMaskElt(1) != -1)
7281         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7282   }
7283
7284   // movl and movlp will both match v2i64, but v2i64 is never matched by
7285   // movl earlier because we make it strict to avoid messing with the movlp load
7286   // folding logic (see the code above getMOVLP call). Match it here then,
7287   // this is horrible, but will stay like this until we move all shuffle
7288   // matching to x86 specific nodes. Note that for the 1st condition all
7289   // types are matched with movsd.
7290   if (HasSSE2) {
7291     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7292     // as to remove this logic from here, as much as possible
7293     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7294       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7295     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7296   }
7297
7298   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7299
7300   // Invert the operand order and use SHUFPS to match it.
7301   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7302                               getShuffleSHUFImmediate(SVOp), DAG);
7303 }
7304
7305 // It is only safe to call this function if isINSERTPSMask is true for
7306 // this shufflevector mask.
7307 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7308                            SelectionDAG &DAG) {
7309   // Generate an insertps instruction when inserting an f32 from memory onto a
7310   // v4f32 or when copying a member from one v4f32 to another.
7311   // We also use it for transferring i32 from one register to another,
7312   // since it simply copies the same bits.
7313   // If we're transfering an i32 from memory to a specific element in a
7314   // register, we output a generic DAG that will match the PINSRD
7315   // instruction.
7316   // TODO: Optimize for AVX cases too (VINSERTPS)
7317   MVT VT = SVOp->getSimpleValueType(0);
7318   MVT EVT = VT.getVectorElementType();
7319   SDValue V1 = SVOp->getOperand(0);
7320   SDValue V2 = SVOp->getOperand(1);
7321   auto Mask = SVOp->getMask();
7322   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7323          "unsupported vector type for insertps/pinsrd");
7324
7325   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7326                              [](const int &i) { return i < 4; });
7327
7328   SDValue From;
7329   SDValue To;
7330   unsigned DestIndex;
7331   if (FromV1 == 1) {
7332     From = V1;
7333     To = V2;
7334     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7335                              [](const int &i) { return i < 4; }) -
7336                 Mask.begin();
7337   } else {
7338     From = V2;
7339     To = V1;
7340     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7341                              [](const int &i) { return i >= 4; }) -
7342                 Mask.begin();
7343   }
7344
7345   if (MayFoldLoad(From)) {
7346     // Trivial case, when From comes from a load and is only used by the
7347     // shuffle. Make it use insertps from the vector that we need from that
7348     // load.
7349     SDValue Addr = From.getOperand(1);
7350     SDValue NewAddr =
7351         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7352                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7353                                     Addr.getSimpleValueType()));
7354
7355     LoadSDNode *Load = cast<LoadSDNode>(From);
7356     SDValue NewLoad =
7357         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7358                     DAG.getMachineFunction().getMachineMemOperand(
7359                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7360
7361     if (EVT == MVT::f32) {
7362       // Create this as a scalar to vector to match the instruction pattern.
7363       SDValue LoadScalarToVector =
7364           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7365       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7366       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7367                          InsertpsMask);
7368     } else { // EVT == MVT::i32
7369       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7370       // instruction, to match the PINSRD instruction, which loads an i32 to a
7371       // certain vector element.
7372       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7373                          DAG.getConstant(DestIndex, MVT::i32));
7374     }
7375   }
7376
7377   // Vector-element-to-vector
7378   unsigned SrcIndex = Mask[DestIndex] % 4;
7379   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7380   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7381 }
7382
7383 // Reduce a vector shuffle to zext.
7384 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7385                                     SelectionDAG &DAG) {
7386   // PMOVZX is only available from SSE41.
7387   if (!Subtarget->hasSSE41())
7388     return SDValue();
7389
7390   MVT VT = Op.getSimpleValueType();
7391
7392   // Only AVX2 support 256-bit vector integer extending.
7393   if (!Subtarget->hasInt256() && VT.is256BitVector())
7394     return SDValue();
7395
7396   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7397   SDLoc DL(Op);
7398   SDValue V1 = Op.getOperand(0);
7399   SDValue V2 = Op.getOperand(1);
7400   unsigned NumElems = VT.getVectorNumElements();
7401
7402   // Extending is an unary operation and the element type of the source vector
7403   // won't be equal to or larger than i64.
7404   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7405       VT.getVectorElementType() == MVT::i64)
7406     return SDValue();
7407
7408   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7409   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7410   while ((1U << Shift) < NumElems) {
7411     if (SVOp->getMaskElt(1U << Shift) == 1)
7412       break;
7413     Shift += 1;
7414     // The maximal ratio is 8, i.e. from i8 to i64.
7415     if (Shift > 3)
7416       return SDValue();
7417   }
7418
7419   // Check the shuffle mask.
7420   unsigned Mask = (1U << Shift) - 1;
7421   for (unsigned i = 0; i != NumElems; ++i) {
7422     int EltIdx = SVOp->getMaskElt(i);
7423     if ((i & Mask) != 0 && EltIdx != -1)
7424       return SDValue();
7425     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7426       return SDValue();
7427   }
7428
7429   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7430   MVT NeVT = MVT::getIntegerVT(NBits);
7431   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7432
7433   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7434     return SDValue();
7435
7436   // Simplify the operand as it's prepared to be fed into shuffle.
7437   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7438   if (V1.getOpcode() == ISD::BITCAST &&
7439       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7440       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7441       V1.getOperand(0).getOperand(0)
7442         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7443     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7444     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7445     ConstantSDNode *CIdx =
7446       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7447     // If it's foldable, i.e. normal load with single use, we will let code
7448     // selection to fold it. Otherwise, we will short the conversion sequence.
7449     if (CIdx && CIdx->getZExtValue() == 0 &&
7450         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7451       MVT FullVT = V.getSimpleValueType();
7452       MVT V1VT = V1.getSimpleValueType();
7453       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7454         // The "ext_vec_elt" node is wider than the result node.
7455         // In this case we should extract subvector from V.
7456         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7457         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7458         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7459                                         FullVT.getVectorNumElements()/Ratio);
7460         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7461                         DAG.getIntPtrConstant(0));
7462       }
7463       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7464     }
7465   }
7466
7467   return DAG.getNode(ISD::BITCAST, DL, VT,
7468                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7469 }
7470
7471 static SDValue
7472 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7473                        SelectionDAG &DAG) {
7474   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7475   MVT VT = Op.getSimpleValueType();
7476   SDLoc dl(Op);
7477   SDValue V1 = Op.getOperand(0);
7478   SDValue V2 = Op.getOperand(1);
7479
7480   if (isZeroShuffle(SVOp))
7481     return getZeroVector(VT, Subtarget, DAG, dl);
7482
7483   // Handle splat operations
7484   if (SVOp->isSplat()) {
7485     // Use vbroadcast whenever the splat comes from a foldable load
7486     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7487     if (Broadcast.getNode())
7488       return Broadcast;
7489   }
7490
7491   // Check integer expanding shuffles.
7492   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7493   if (NewOp.getNode())
7494     return NewOp;
7495
7496   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7497   // do it!
7498   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7499       VT == MVT::v16i16 || VT == MVT::v32i8) {
7500     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7501     if (NewOp.getNode())
7502       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7503   } else if ((VT == MVT::v4i32 ||
7504              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7505     // FIXME: Figure out a cleaner way to do this.
7506     // Try to make use of movq to zero out the top part.
7507     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7508       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7509       if (NewOp.getNode()) {
7510         MVT NewVT = NewOp.getSimpleValueType();
7511         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7512                                NewVT, true, false))
7513           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7514                               DAG, Subtarget, dl);
7515       }
7516     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7517       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7518       if (NewOp.getNode()) {
7519         MVT NewVT = NewOp.getSimpleValueType();
7520         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7521           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7522                               DAG, Subtarget, dl);
7523       }
7524     }
7525   }
7526   return SDValue();
7527 }
7528
7529 SDValue
7530 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7531   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7532   SDValue V1 = Op.getOperand(0);
7533   SDValue V2 = Op.getOperand(1);
7534   MVT VT = Op.getSimpleValueType();
7535   SDLoc dl(Op);
7536   unsigned NumElems = VT.getVectorNumElements();
7537   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7538   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7539   bool V1IsSplat = false;
7540   bool V2IsSplat = false;
7541   bool HasSSE2 = Subtarget->hasSSE2();
7542   bool HasFp256    = Subtarget->hasFp256();
7543   bool HasInt256   = Subtarget->hasInt256();
7544   MachineFunction &MF = DAG.getMachineFunction();
7545   bool OptForSize = MF.getFunction()->getAttributes().
7546     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7547
7548   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7549
7550   if (V1IsUndef && V2IsUndef)
7551     return DAG.getUNDEF(VT);
7552
7553   // When we create a shuffle node we put the UNDEF node to second operand,
7554   // but in some cases the first operand may be transformed to UNDEF.
7555   // In this case we should just commute the node.
7556   if (V1IsUndef)
7557     return CommuteVectorShuffle(SVOp, DAG);
7558
7559   // Vector shuffle lowering takes 3 steps:
7560   //
7561   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7562   //    narrowing and commutation of operands should be handled.
7563   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7564   //    shuffle nodes.
7565   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7566   //    so the shuffle can be broken into other shuffles and the legalizer can
7567   //    try the lowering again.
7568   //
7569   // The general idea is that no vector_shuffle operation should be left to
7570   // be matched during isel, all of them must be converted to a target specific
7571   // node here.
7572
7573   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7574   // narrowing and commutation of operands should be handled. The actual code
7575   // doesn't include all of those, work in progress...
7576   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7577   if (NewOp.getNode())
7578     return NewOp;
7579
7580   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7581
7582   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7583   // unpckh_undef). Only use pshufd if speed is more important than size.
7584   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7585     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7586   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7587     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7588
7589   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7590       V2IsUndef && MayFoldVectorLoad(V1))
7591     return getMOVDDup(Op, dl, V1, DAG);
7592
7593   if (isMOVHLPS_v_undef_Mask(M, VT))
7594     return getMOVHighToLow(Op, dl, DAG);
7595
7596   // Use to match splats
7597   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7598       (VT == MVT::v2f64 || VT == MVT::v2i64))
7599     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7600
7601   if (isPSHUFDMask(M, VT)) {
7602     // The actual implementation will match the mask in the if above and then
7603     // during isel it can match several different instructions, not only pshufd
7604     // as its name says, sad but true, emulate the behavior for now...
7605     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7606       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7607
7608     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7609
7610     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7611       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7612
7613     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7614       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7615                                   DAG);
7616
7617     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7618                                 TargetMask, DAG);
7619   }
7620
7621   if (isPALIGNRMask(M, VT, Subtarget))
7622     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7623                                 getShufflePALIGNRImmediate(SVOp),
7624                                 DAG);
7625
7626   // Check if this can be converted into a logical shift.
7627   bool isLeft = false;
7628   unsigned ShAmt = 0;
7629   SDValue ShVal;
7630   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7631   if (isShift && ShVal.hasOneUse()) {
7632     // If the shifted value has multiple uses, it may be cheaper to use
7633     // v_set0 + movlhps or movhlps, etc.
7634     MVT EltVT = VT.getVectorElementType();
7635     ShAmt *= EltVT.getSizeInBits();
7636     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7637   }
7638
7639   if (isMOVLMask(M, VT)) {
7640     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7641       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7642     if (!isMOVLPMask(M, VT)) {
7643       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7644         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7645
7646       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7647         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7648     }
7649   }
7650
7651   // FIXME: fold these into legal mask.
7652   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7653     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7654
7655   if (isMOVHLPSMask(M, VT))
7656     return getMOVHighToLow(Op, dl, DAG);
7657
7658   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7659     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7660
7661   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7662     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7663
7664   if (isMOVLPMask(M, VT))
7665     return getMOVLP(Op, dl, DAG, HasSSE2);
7666
7667   if (ShouldXformToMOVHLPS(M, VT) ||
7668       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7669     return CommuteVectorShuffle(SVOp, DAG);
7670
7671   if (isShift) {
7672     // No better options. Use a vshldq / vsrldq.
7673     MVT EltVT = VT.getVectorElementType();
7674     ShAmt *= EltVT.getSizeInBits();
7675     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7676   }
7677
7678   bool Commuted = false;
7679   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7680   // 1,1,1,1 -> v8i16 though.
7681   V1IsSplat = isSplatVector(V1.getNode());
7682   V2IsSplat = isSplatVector(V2.getNode());
7683
7684   // Canonicalize the splat or undef, if present, to be on the RHS.
7685   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7686     CommuteVectorShuffleMask(M, NumElems);
7687     std::swap(V1, V2);
7688     std::swap(V1IsSplat, V2IsSplat);
7689     Commuted = true;
7690   }
7691
7692   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7693     // Shuffling low element of v1 into undef, just return v1.
7694     if (V2IsUndef)
7695       return V1;
7696     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7697     // the instruction selector will not match, so get a canonical MOVL with
7698     // swapped operands to undo the commute.
7699     return getMOVL(DAG, dl, VT, V2, V1);
7700   }
7701
7702   if (isUNPCKLMask(M, VT, HasInt256))
7703     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7704
7705   if (isUNPCKHMask(M, VT, HasInt256))
7706     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7707
7708   if (V2IsSplat) {
7709     // Normalize mask so all entries that point to V2 points to its first
7710     // element then try to match unpck{h|l} again. If match, return a
7711     // new vector_shuffle with the corrected mask.p
7712     SmallVector<int, 8> NewMask(M.begin(), M.end());
7713     NormalizeMask(NewMask, NumElems);
7714     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7715       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7716     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7717       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7718   }
7719
7720   if (Commuted) {
7721     // Commute is back and try unpck* again.
7722     // FIXME: this seems wrong.
7723     CommuteVectorShuffleMask(M, NumElems);
7724     std::swap(V1, V2);
7725     std::swap(V1IsSplat, V2IsSplat);
7726
7727     if (isUNPCKLMask(M, VT, HasInt256))
7728       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7729
7730     if (isUNPCKHMask(M, VT, HasInt256))
7731       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7732   }
7733
7734   // Normalize the node to match x86 shuffle ops if needed
7735   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7736     return CommuteVectorShuffle(SVOp, DAG);
7737
7738   // The checks below are all present in isShuffleMaskLegal, but they are
7739   // inlined here right now to enable us to directly emit target specific
7740   // nodes, and remove one by one until they don't return Op anymore.
7741
7742   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7743       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7744     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7745       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7746   }
7747
7748   if (isPSHUFHWMask(M, VT, HasInt256))
7749     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7750                                 getShufflePSHUFHWImmediate(SVOp),
7751                                 DAG);
7752
7753   if (isPSHUFLWMask(M, VT, HasInt256))
7754     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7755                                 getShufflePSHUFLWImmediate(SVOp),
7756                                 DAG);
7757
7758   if (isSHUFPMask(M, VT))
7759     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7760                                 getShuffleSHUFImmediate(SVOp), DAG);
7761
7762   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7763     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7764   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7765     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7766
7767   //===--------------------------------------------------------------------===//
7768   // Generate target specific nodes for 128 or 256-bit shuffles only
7769   // supported in the AVX instruction set.
7770   //
7771
7772   // Handle VMOVDDUPY permutations
7773   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7774     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7775
7776   // Handle VPERMILPS/D* permutations
7777   if (isVPERMILPMask(M, VT)) {
7778     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7779       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7780                                   getShuffleSHUFImmediate(SVOp), DAG);
7781     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7782                                 getShuffleSHUFImmediate(SVOp), DAG);
7783   }
7784
7785   unsigned Idx;
7786   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7787     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7788                               Idx*(NumElems/2), DAG, dl);
7789
7790   // Handle VPERM2F128/VPERM2I128 permutations
7791   if (isVPERM2X128Mask(M, VT, HasFp256))
7792     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7793                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7794
7795   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7796   if (BlendOp.getNode())
7797     return BlendOp;
7798
7799   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7800     return getINSERTPS(SVOp, dl, DAG);
7801
7802   unsigned Imm8;
7803   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7804     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7805
7806   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7807       VT.is512BitVector()) {
7808     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7809     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7810     SmallVector<SDValue, 16> permclMask;
7811     for (unsigned i = 0; i != NumElems; ++i) {
7812       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7813     }
7814
7815     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7816     if (V2IsUndef)
7817       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7818       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7819                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7820     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7821                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7822   }
7823
7824   //===--------------------------------------------------------------------===//
7825   // Since no target specific shuffle was selected for this generic one,
7826   // lower it into other known shuffles. FIXME: this isn't true yet, but
7827   // this is the plan.
7828   //
7829
7830   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7831   if (VT == MVT::v8i16) {
7832     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7833     if (NewOp.getNode())
7834       return NewOp;
7835   }
7836
7837   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7838     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7839     if (NewOp.getNode())
7840       return NewOp;
7841   }
7842
7843   if (VT == MVT::v16i8) {
7844     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7845     if (NewOp.getNode())
7846       return NewOp;
7847   }
7848
7849   if (VT == MVT::v32i8) {
7850     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7851     if (NewOp.getNode())
7852       return NewOp;
7853   }
7854
7855   // Handle all 128-bit wide vectors with 4 elements, and match them with
7856   // several different shuffle types.
7857   if (NumElems == 4 && VT.is128BitVector())
7858     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7859
7860   // Handle general 256-bit shuffles
7861   if (VT.is256BitVector())
7862     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7863
7864   return SDValue();
7865 }
7866
7867 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7868   MVT VT = Op.getSimpleValueType();
7869   SDLoc dl(Op);
7870
7871   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7872     return SDValue();
7873
7874   if (VT.getSizeInBits() == 8) {
7875     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7876                                   Op.getOperand(0), Op.getOperand(1));
7877     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7878                                   DAG.getValueType(VT));
7879     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7880   }
7881
7882   if (VT.getSizeInBits() == 16) {
7883     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7884     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7885     if (Idx == 0)
7886       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7887                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7888                                      DAG.getNode(ISD::BITCAST, dl,
7889                                                  MVT::v4i32,
7890                                                  Op.getOperand(0)),
7891                                      Op.getOperand(1)));
7892     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7893                                   Op.getOperand(0), Op.getOperand(1));
7894     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7895                                   DAG.getValueType(VT));
7896     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7897   }
7898
7899   if (VT == MVT::f32) {
7900     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7901     // the result back to FR32 register. It's only worth matching if the
7902     // result has a single use which is a store or a bitcast to i32.  And in
7903     // the case of a store, it's not worth it if the index is a constant 0,
7904     // because a MOVSSmr can be used instead, which is smaller and faster.
7905     if (!Op.hasOneUse())
7906       return SDValue();
7907     SDNode *User = *Op.getNode()->use_begin();
7908     if ((User->getOpcode() != ISD::STORE ||
7909          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7910           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7911         (User->getOpcode() != ISD::BITCAST ||
7912          User->getValueType(0) != MVT::i32))
7913       return SDValue();
7914     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7915                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7916                                               Op.getOperand(0)),
7917                                               Op.getOperand(1));
7918     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7919   }
7920
7921   if (VT == MVT::i32 || VT == MVT::i64) {
7922     // ExtractPS/pextrq works with constant index.
7923     if (isa<ConstantSDNode>(Op.getOperand(1)))
7924       return Op;
7925   }
7926   return SDValue();
7927 }
7928
7929 /// Extract one bit from mask vector, like v16i1 or v8i1.
7930 /// AVX-512 feature.
7931 SDValue
7932 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7933   SDValue Vec = Op.getOperand(0);
7934   SDLoc dl(Vec);
7935   MVT VecVT = Vec.getSimpleValueType();
7936   SDValue Idx = Op.getOperand(1);
7937   MVT EltVT = Op.getSimpleValueType();
7938
7939   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7940
7941   // variable index can't be handled in mask registers,
7942   // extend vector to VR512
7943   if (!isa<ConstantSDNode>(Idx)) {
7944     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7945     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7946     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7947                               ExtVT.getVectorElementType(), Ext, Idx);
7948     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7949   }
7950
7951   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7952   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7953   unsigned MaxSift = rc->getSize()*8 - 1;
7954   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7955                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7956   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7957                     DAG.getConstant(MaxSift, MVT::i8));
7958   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7959                        DAG.getIntPtrConstant(0));
7960 }
7961
7962 SDValue
7963 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7964                                            SelectionDAG &DAG) const {
7965   SDLoc dl(Op);
7966   SDValue Vec = Op.getOperand(0);
7967   MVT VecVT = Vec.getSimpleValueType();
7968   SDValue Idx = Op.getOperand(1);
7969
7970   if (Op.getSimpleValueType() == MVT::i1)
7971     return ExtractBitFromMaskVector(Op, DAG);
7972
7973   if (!isa<ConstantSDNode>(Idx)) {
7974     if (VecVT.is512BitVector() ||
7975         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7976          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7977
7978       MVT MaskEltVT =
7979         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7980       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7981                                     MaskEltVT.getSizeInBits());
7982
7983       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7984       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7985                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7986                                 Idx, DAG.getConstant(0, getPointerTy()));
7987       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7988       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7989                         Perm, DAG.getConstant(0, getPointerTy()));
7990     }
7991     return SDValue();
7992   }
7993
7994   // If this is a 256-bit vector result, first extract the 128-bit vector and
7995   // then extract the element from the 128-bit vector.
7996   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7997
7998     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7999     // Get the 128-bit vector.
8000     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8001     MVT EltVT = VecVT.getVectorElementType();
8002
8003     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8004
8005     //if (IdxVal >= NumElems/2)
8006     //  IdxVal -= NumElems/2;
8007     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8008     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8009                        DAG.getConstant(IdxVal, MVT::i32));
8010   }
8011
8012   assert(VecVT.is128BitVector() && "Unexpected vector length");
8013
8014   if (Subtarget->hasSSE41()) {
8015     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8016     if (Res.getNode())
8017       return Res;
8018   }
8019
8020   MVT VT = Op.getSimpleValueType();
8021   // TODO: handle v16i8.
8022   if (VT.getSizeInBits() == 16) {
8023     SDValue Vec = Op.getOperand(0);
8024     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8025     if (Idx == 0)
8026       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8027                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8028                                      DAG.getNode(ISD::BITCAST, dl,
8029                                                  MVT::v4i32, Vec),
8030                                      Op.getOperand(1)));
8031     // Transform it so it match pextrw which produces a 32-bit result.
8032     MVT EltVT = MVT::i32;
8033     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8034                                   Op.getOperand(0), Op.getOperand(1));
8035     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8036                                   DAG.getValueType(VT));
8037     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8038   }
8039
8040   if (VT.getSizeInBits() == 32) {
8041     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8042     if (Idx == 0)
8043       return Op;
8044
8045     // SHUFPS the element to the lowest double word, then movss.
8046     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8047     MVT VVT = Op.getOperand(0).getSimpleValueType();
8048     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8049                                        DAG.getUNDEF(VVT), Mask);
8050     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8051                        DAG.getIntPtrConstant(0));
8052   }
8053
8054   if (VT.getSizeInBits() == 64) {
8055     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8056     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8057     //        to match extract_elt for f64.
8058     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8059     if (Idx == 0)
8060       return Op;
8061
8062     // UNPCKHPD the element to the lowest double word, then movsd.
8063     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8064     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8065     int Mask[2] = { 1, -1 };
8066     MVT VVT = Op.getOperand(0).getSimpleValueType();
8067     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8068                                        DAG.getUNDEF(VVT), Mask);
8069     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8070                        DAG.getIntPtrConstant(0));
8071   }
8072
8073   return SDValue();
8074 }
8075
8076 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8077   MVT VT = Op.getSimpleValueType();
8078   MVT EltVT = VT.getVectorElementType();
8079   SDLoc dl(Op);
8080
8081   SDValue N0 = Op.getOperand(0);
8082   SDValue N1 = Op.getOperand(1);
8083   SDValue N2 = Op.getOperand(2);
8084
8085   if (!VT.is128BitVector())
8086     return SDValue();
8087
8088   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8089       isa<ConstantSDNode>(N2)) {
8090     unsigned Opc;
8091     if (VT == MVT::v8i16)
8092       Opc = X86ISD::PINSRW;
8093     else if (VT == MVT::v16i8)
8094       Opc = X86ISD::PINSRB;
8095     else
8096       Opc = X86ISD::PINSRB;
8097
8098     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8099     // argument.
8100     if (N1.getValueType() != MVT::i32)
8101       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8102     if (N2.getValueType() != MVT::i32)
8103       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8104     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8105   }
8106
8107   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8108     // Bits [7:6] of the constant are the source select.  This will always be
8109     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8110     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8111     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8112     // Bits [5:4] of the constant are the destination select.  This is the
8113     //  value of the incoming immediate.
8114     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8115     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8116     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8117     // Create this as a scalar to vector..
8118     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8119     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8120   }
8121
8122   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8123     // PINSR* works with constant index.
8124     return Op;
8125   }
8126   return SDValue();
8127 }
8128
8129 /// Insert one bit to mask vector, like v16i1 or v8i1.
8130 /// AVX-512 feature.
8131 SDValue 
8132 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8133   SDLoc dl(Op);
8134   SDValue Vec = Op.getOperand(0);
8135   SDValue Elt = Op.getOperand(1);
8136   SDValue Idx = Op.getOperand(2);
8137   MVT VecVT = Vec.getSimpleValueType();
8138
8139   if (!isa<ConstantSDNode>(Idx)) {
8140     // Non constant index. Extend source and destination,
8141     // insert element and then truncate the result.
8142     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8143     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8144     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8145       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8146       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8147     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8148   }
8149
8150   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8151   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8152   if (Vec.getOpcode() == ISD::UNDEF)
8153     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8154                        DAG.getConstant(IdxVal, MVT::i8));
8155   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8156   unsigned MaxSift = rc->getSize()*8 - 1;
8157   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8158                     DAG.getConstant(MaxSift, MVT::i8));
8159   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8160                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8161   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8162 }
8163 SDValue
8164 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8165   MVT VT = Op.getSimpleValueType();
8166   MVT EltVT = VT.getVectorElementType();
8167   
8168   if (EltVT == MVT::i1)
8169     return InsertBitToMaskVector(Op, DAG);
8170
8171   SDLoc dl(Op);
8172   SDValue N0 = Op.getOperand(0);
8173   SDValue N1 = Op.getOperand(1);
8174   SDValue N2 = Op.getOperand(2);
8175
8176   // If this is a 256-bit vector result, first extract the 128-bit vector,
8177   // insert the element into the extracted half and then place it back.
8178   if (VT.is256BitVector() || VT.is512BitVector()) {
8179     if (!isa<ConstantSDNode>(N2))
8180       return SDValue();
8181
8182     // Get the desired 128-bit vector half.
8183     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8184     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8185
8186     // Insert the element into the desired half.
8187     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8188     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8189
8190     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8191                     DAG.getConstant(IdxIn128, MVT::i32));
8192
8193     // Insert the changed part back to the 256-bit vector
8194     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8195   }
8196
8197   if (Subtarget->hasSSE41())
8198     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8199
8200   if (EltVT == MVT::i8)
8201     return SDValue();
8202
8203   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8204     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8205     // as its second argument.
8206     if (N1.getValueType() != MVT::i32)
8207       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8208     if (N2.getValueType() != MVT::i32)
8209       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8210     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8211   }
8212   return SDValue();
8213 }
8214
8215 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8216   SDLoc dl(Op);
8217   MVT OpVT = Op.getSimpleValueType();
8218
8219   // If this is a 256-bit vector result, first insert into a 128-bit
8220   // vector and then insert into the 256-bit vector.
8221   if (!OpVT.is128BitVector()) {
8222     // Insert into a 128-bit vector.
8223     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8224     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8225                                  OpVT.getVectorNumElements() / SizeFactor);
8226
8227     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8228
8229     // Insert the 128-bit vector.
8230     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8231   }
8232
8233   if (OpVT == MVT::v1i64 &&
8234       Op.getOperand(0).getValueType() == MVT::i64)
8235     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8236
8237   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8238   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8239   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8240                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8241 }
8242
8243 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8244 // a simple subregister reference or explicit instructions to grab
8245 // upper bits of a vector.
8246 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8247                                       SelectionDAG &DAG) {
8248   SDLoc dl(Op);
8249   SDValue In =  Op.getOperand(0);
8250   SDValue Idx = Op.getOperand(1);
8251   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8252   MVT ResVT   = Op.getSimpleValueType();
8253   MVT InVT    = In.getSimpleValueType();
8254
8255   if (Subtarget->hasFp256()) {
8256     if (ResVT.is128BitVector() &&
8257         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8258         isa<ConstantSDNode>(Idx)) {
8259       return Extract128BitVector(In, IdxVal, DAG, dl);
8260     }
8261     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8262         isa<ConstantSDNode>(Idx)) {
8263       return Extract256BitVector(In, IdxVal, DAG, dl);
8264     }
8265   }
8266   return SDValue();
8267 }
8268
8269 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8270 // simple superregister reference or explicit instructions to insert
8271 // the upper bits of a vector.
8272 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8273                                      SelectionDAG &DAG) {
8274   if (Subtarget->hasFp256()) {
8275     SDLoc dl(Op.getNode());
8276     SDValue Vec = Op.getNode()->getOperand(0);
8277     SDValue SubVec = Op.getNode()->getOperand(1);
8278     SDValue Idx = Op.getNode()->getOperand(2);
8279
8280     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8281          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8282         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8283         isa<ConstantSDNode>(Idx)) {
8284       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8285       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8286     }
8287
8288     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8289         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8290         isa<ConstantSDNode>(Idx)) {
8291       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8292       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8293     }
8294   }
8295   return SDValue();
8296 }
8297
8298 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8299 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8300 // one of the above mentioned nodes. It has to be wrapped because otherwise
8301 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8302 // be used to form addressing mode. These wrapped nodes will be selected
8303 // into MOV32ri.
8304 SDValue
8305 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8306   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8307
8308   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8309   // global base reg.
8310   unsigned char OpFlag = 0;
8311   unsigned WrapperKind = X86ISD::Wrapper;
8312   CodeModel::Model M = getTargetMachine().getCodeModel();
8313
8314   if (Subtarget->isPICStyleRIPRel() &&
8315       (M == CodeModel::Small || M == CodeModel::Kernel))
8316     WrapperKind = X86ISD::WrapperRIP;
8317   else if (Subtarget->isPICStyleGOT())
8318     OpFlag = X86II::MO_GOTOFF;
8319   else if (Subtarget->isPICStyleStubPIC())
8320     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8321
8322   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8323                                              CP->getAlignment(),
8324                                              CP->getOffset(), OpFlag);
8325   SDLoc DL(CP);
8326   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8327   // With PIC, the address is actually $g + Offset.
8328   if (OpFlag) {
8329     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8330                          DAG.getNode(X86ISD::GlobalBaseReg,
8331                                      SDLoc(), getPointerTy()),
8332                          Result);
8333   }
8334
8335   return Result;
8336 }
8337
8338 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8339   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8340
8341   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8342   // global base reg.
8343   unsigned char OpFlag = 0;
8344   unsigned WrapperKind = X86ISD::Wrapper;
8345   CodeModel::Model M = getTargetMachine().getCodeModel();
8346
8347   if (Subtarget->isPICStyleRIPRel() &&
8348       (M == CodeModel::Small || M == CodeModel::Kernel))
8349     WrapperKind = X86ISD::WrapperRIP;
8350   else if (Subtarget->isPICStyleGOT())
8351     OpFlag = X86II::MO_GOTOFF;
8352   else if (Subtarget->isPICStyleStubPIC())
8353     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8354
8355   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8356                                           OpFlag);
8357   SDLoc DL(JT);
8358   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8359
8360   // With PIC, the address is actually $g + Offset.
8361   if (OpFlag)
8362     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8363                          DAG.getNode(X86ISD::GlobalBaseReg,
8364                                      SDLoc(), getPointerTy()),
8365                          Result);
8366
8367   return Result;
8368 }
8369
8370 SDValue
8371 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8372   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8373
8374   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8375   // global base reg.
8376   unsigned char OpFlag = 0;
8377   unsigned WrapperKind = X86ISD::Wrapper;
8378   CodeModel::Model M = getTargetMachine().getCodeModel();
8379
8380   if (Subtarget->isPICStyleRIPRel() &&
8381       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8382     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8383       OpFlag = X86II::MO_GOTPCREL;
8384     WrapperKind = X86ISD::WrapperRIP;
8385   } else if (Subtarget->isPICStyleGOT()) {
8386     OpFlag = X86II::MO_GOT;
8387   } else if (Subtarget->isPICStyleStubPIC()) {
8388     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8389   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8390     OpFlag = X86II::MO_DARWIN_NONLAZY;
8391   }
8392
8393   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8394
8395   SDLoc DL(Op);
8396   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8397
8398   // With PIC, the address is actually $g + Offset.
8399   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8400       !Subtarget->is64Bit()) {
8401     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8402                          DAG.getNode(X86ISD::GlobalBaseReg,
8403                                      SDLoc(), getPointerTy()),
8404                          Result);
8405   }
8406
8407   // For symbols that require a load from a stub to get the address, emit the
8408   // load.
8409   if (isGlobalStubReference(OpFlag))
8410     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8411                          MachinePointerInfo::getGOT(), false, false, false, 0);
8412
8413   return Result;
8414 }
8415
8416 SDValue
8417 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8418   // Create the TargetBlockAddressAddress node.
8419   unsigned char OpFlags =
8420     Subtarget->ClassifyBlockAddressReference();
8421   CodeModel::Model M = getTargetMachine().getCodeModel();
8422   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8423   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8424   SDLoc dl(Op);
8425   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8426                                              OpFlags);
8427
8428   if (Subtarget->isPICStyleRIPRel() &&
8429       (M == CodeModel::Small || M == CodeModel::Kernel))
8430     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8431   else
8432     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8433
8434   // With PIC, the address is actually $g + Offset.
8435   if (isGlobalRelativeToPICBase(OpFlags)) {
8436     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8437                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8438                          Result);
8439   }
8440
8441   return Result;
8442 }
8443
8444 SDValue
8445 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8446                                       int64_t Offset, SelectionDAG &DAG) const {
8447   // Create the TargetGlobalAddress node, folding in the constant
8448   // offset if it is legal.
8449   unsigned char OpFlags =
8450     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8451   CodeModel::Model M = getTargetMachine().getCodeModel();
8452   SDValue Result;
8453   if (OpFlags == X86II::MO_NO_FLAG &&
8454       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8455     // A direct static reference to a global.
8456     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8457     Offset = 0;
8458   } else {
8459     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8460   }
8461
8462   if (Subtarget->isPICStyleRIPRel() &&
8463       (M == CodeModel::Small || M == CodeModel::Kernel))
8464     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8465   else
8466     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8467
8468   // With PIC, the address is actually $g + Offset.
8469   if (isGlobalRelativeToPICBase(OpFlags)) {
8470     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8471                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8472                          Result);
8473   }
8474
8475   // For globals that require a load from a stub to get the address, emit the
8476   // load.
8477   if (isGlobalStubReference(OpFlags))
8478     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8479                          MachinePointerInfo::getGOT(), false, false, false, 0);
8480
8481   // If there was a non-zero offset that we didn't fold, create an explicit
8482   // addition for it.
8483   if (Offset != 0)
8484     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8485                          DAG.getConstant(Offset, getPointerTy()));
8486
8487   return Result;
8488 }
8489
8490 SDValue
8491 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8492   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8493   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8494   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8495 }
8496
8497 static SDValue
8498 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8499            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8500            unsigned char OperandFlags, bool LocalDynamic = false) {
8501   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8502   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8503   SDLoc dl(GA);
8504   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8505                                            GA->getValueType(0),
8506                                            GA->getOffset(),
8507                                            OperandFlags);
8508
8509   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8510                                            : X86ISD::TLSADDR;
8511
8512   if (InFlag) {
8513     SDValue Ops[] = { Chain,  TGA, *InFlag };
8514     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8515   } else {
8516     SDValue Ops[]  = { Chain, TGA };
8517     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8518   }
8519
8520   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8521   MFI->setAdjustsStack(true);
8522
8523   SDValue Flag = Chain.getValue(1);
8524   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8525 }
8526
8527 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8528 static SDValue
8529 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8530                                 const EVT PtrVT) {
8531   SDValue InFlag;
8532   SDLoc dl(GA);  // ? function entry point might be better
8533   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8534                                    DAG.getNode(X86ISD::GlobalBaseReg,
8535                                                SDLoc(), PtrVT), InFlag);
8536   InFlag = Chain.getValue(1);
8537
8538   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8539 }
8540
8541 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8542 static SDValue
8543 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8544                                 const EVT PtrVT) {
8545   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8546                     X86::RAX, X86II::MO_TLSGD);
8547 }
8548
8549 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8550                                            SelectionDAG &DAG,
8551                                            const EVT PtrVT,
8552                                            bool is64Bit) {
8553   SDLoc dl(GA);
8554
8555   // Get the start address of the TLS block for this module.
8556   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8557       .getInfo<X86MachineFunctionInfo>();
8558   MFI->incNumLocalDynamicTLSAccesses();
8559
8560   SDValue Base;
8561   if (is64Bit) {
8562     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8563                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8564   } else {
8565     SDValue InFlag;
8566     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8567         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8568     InFlag = Chain.getValue(1);
8569     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8570                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8571   }
8572
8573   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8574   // of Base.
8575
8576   // Build x@dtpoff.
8577   unsigned char OperandFlags = X86II::MO_DTPOFF;
8578   unsigned WrapperKind = X86ISD::Wrapper;
8579   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8580                                            GA->getValueType(0),
8581                                            GA->getOffset(), OperandFlags);
8582   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8583
8584   // Add x@dtpoff with the base.
8585   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8586 }
8587
8588 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8589 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8590                                    const EVT PtrVT, TLSModel::Model model,
8591                                    bool is64Bit, bool isPIC) {
8592   SDLoc dl(GA);
8593
8594   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8595   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8596                                                          is64Bit ? 257 : 256));
8597
8598   SDValue ThreadPointer =
8599       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8600                   MachinePointerInfo(Ptr), false, false, false, 0);
8601
8602   unsigned char OperandFlags = 0;
8603   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8604   // initialexec.
8605   unsigned WrapperKind = X86ISD::Wrapper;
8606   if (model == TLSModel::LocalExec) {
8607     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8608   } else if (model == TLSModel::InitialExec) {
8609     if (is64Bit) {
8610       OperandFlags = X86II::MO_GOTTPOFF;
8611       WrapperKind = X86ISD::WrapperRIP;
8612     } else {
8613       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8614     }
8615   } else {
8616     llvm_unreachable("Unexpected model");
8617   }
8618
8619   // emit "addl x@ntpoff,%eax" (local exec)
8620   // or "addl x@indntpoff,%eax" (initial exec)
8621   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8622   SDValue TGA =
8623       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8624                                  GA->getOffset(), OperandFlags);
8625   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8626
8627   if (model == TLSModel::InitialExec) {
8628     if (isPIC && !is64Bit) {
8629       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8630                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8631                            Offset);
8632     }
8633
8634     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8635                          MachinePointerInfo::getGOT(), false, false, false, 0);
8636   }
8637
8638   // The address of the thread local variable is the add of the thread
8639   // pointer with the offset of the variable.
8640   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8641 }
8642
8643 SDValue
8644 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8645
8646   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8647   const GlobalValue *GV = GA->getGlobal();
8648
8649   if (Subtarget->isTargetELF()) {
8650     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8651
8652     switch (model) {
8653       case TLSModel::GeneralDynamic:
8654         if (Subtarget->is64Bit())
8655           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8656         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8657       case TLSModel::LocalDynamic:
8658         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8659                                            Subtarget->is64Bit());
8660       case TLSModel::InitialExec:
8661       case TLSModel::LocalExec:
8662         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8663                                    Subtarget->is64Bit(),
8664                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8665     }
8666     llvm_unreachable("Unknown TLS model.");
8667   }
8668
8669   if (Subtarget->isTargetDarwin()) {
8670     // Darwin only has one model of TLS.  Lower to that.
8671     unsigned char OpFlag = 0;
8672     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8673                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8674
8675     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8676     // global base reg.
8677     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8678                   !Subtarget->is64Bit();
8679     if (PIC32)
8680       OpFlag = X86II::MO_TLVP_PIC_BASE;
8681     else
8682       OpFlag = X86II::MO_TLVP;
8683     SDLoc DL(Op);
8684     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8685                                                 GA->getValueType(0),
8686                                                 GA->getOffset(), OpFlag);
8687     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8688
8689     // With PIC32, the address is actually $g + Offset.
8690     if (PIC32)
8691       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8692                            DAG.getNode(X86ISD::GlobalBaseReg,
8693                                        SDLoc(), getPointerTy()),
8694                            Offset);
8695
8696     // Lowering the machine isd will make sure everything is in the right
8697     // location.
8698     SDValue Chain = DAG.getEntryNode();
8699     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8700     SDValue Args[] = { Chain, Offset };
8701     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8702
8703     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8704     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8705     MFI->setAdjustsStack(true);
8706
8707     // And our return value (tls address) is in the standard call return value
8708     // location.
8709     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8710     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8711                               Chain.getValue(1));
8712   }
8713
8714   if (Subtarget->isTargetKnownWindowsMSVC() ||
8715       Subtarget->isTargetWindowsGNU()) {
8716     // Just use the implicit TLS architecture
8717     // Need to generate someting similar to:
8718     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8719     //                                  ; from TEB
8720     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8721     //   mov     rcx, qword [rdx+rcx*8]
8722     //   mov     eax, .tls$:tlsvar
8723     //   [rax+rcx] contains the address
8724     // Windows 64bit: gs:0x58
8725     // Windows 32bit: fs:__tls_array
8726
8727     // If GV is an alias then use the aliasee for determining
8728     // thread-localness.
8729     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8730       GV = GA->getAliasedGlobal();
8731     SDLoc dl(GA);
8732     SDValue Chain = DAG.getEntryNode();
8733
8734     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8735     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8736     // use its literal value of 0x2C.
8737     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8738                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8739                                                              256)
8740                                         : Type::getInt32PtrTy(*DAG.getContext(),
8741                                                               257));
8742
8743     SDValue TlsArray =
8744         Subtarget->is64Bit()
8745             ? DAG.getIntPtrConstant(0x58)
8746             : (Subtarget->isTargetWindowsGNU()
8747                    ? DAG.getIntPtrConstant(0x2C)
8748                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8749
8750     SDValue ThreadPointer =
8751         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8752                     MachinePointerInfo(Ptr), false, false, false, 0);
8753
8754     // Load the _tls_index variable
8755     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8756     if (Subtarget->is64Bit())
8757       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8758                            IDX, MachinePointerInfo(), MVT::i32,
8759                            false, false, 0);
8760     else
8761       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8762                         false, false, false, 0);
8763
8764     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8765                                     getPointerTy());
8766     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8767
8768     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8769     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8770                       false, false, false, 0);
8771
8772     // Get the offset of start of .tls section
8773     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8774                                              GA->getValueType(0),
8775                                              GA->getOffset(), X86II::MO_SECREL);
8776     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8777
8778     // The address of the thread local variable is the add of the thread
8779     // pointer with the offset of the variable.
8780     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8781   }
8782
8783   llvm_unreachable("TLS not implemented for this target.");
8784 }
8785
8786 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8787 /// and take a 2 x i32 value to shift plus a shift amount.
8788 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8789   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8790   MVT VT = Op.getSimpleValueType();
8791   unsigned VTBits = VT.getSizeInBits();
8792   SDLoc dl(Op);
8793   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8794   SDValue ShOpLo = Op.getOperand(0);
8795   SDValue ShOpHi = Op.getOperand(1);
8796   SDValue ShAmt  = Op.getOperand(2);
8797   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8798   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8799   // during isel.
8800   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8801                                   DAG.getConstant(VTBits - 1, MVT::i8));
8802   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8803                                      DAG.getConstant(VTBits - 1, MVT::i8))
8804                        : DAG.getConstant(0, VT);
8805
8806   SDValue Tmp2, Tmp3;
8807   if (Op.getOpcode() == ISD::SHL_PARTS) {
8808     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8809     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8810   } else {
8811     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8812     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8813   }
8814
8815   // If the shift amount is larger or equal than the width of a part we can't
8816   // rely on the results of shld/shrd. Insert a test and select the appropriate
8817   // values for large shift amounts.
8818   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8819                                 DAG.getConstant(VTBits, MVT::i8));
8820   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8821                              AndNode, DAG.getConstant(0, MVT::i8));
8822
8823   SDValue Hi, Lo;
8824   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8825   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8826   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8827
8828   if (Op.getOpcode() == ISD::SHL_PARTS) {
8829     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8830     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8831   } else {
8832     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8833     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8834   }
8835
8836   SDValue Ops[2] = { Lo, Hi };
8837   return DAG.getMergeValues(Ops, dl);
8838 }
8839
8840 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8841                                            SelectionDAG &DAG) const {
8842   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8843
8844   if (SrcVT.isVector())
8845     return SDValue();
8846
8847   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8848          "Unknown SINT_TO_FP to lower!");
8849
8850   // These are really Legal; return the operand so the caller accepts it as
8851   // Legal.
8852   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8853     return Op;
8854   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8855       Subtarget->is64Bit()) {
8856     return Op;
8857   }
8858
8859   SDLoc dl(Op);
8860   unsigned Size = SrcVT.getSizeInBits()/8;
8861   MachineFunction &MF = DAG.getMachineFunction();
8862   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8863   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8864   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8865                                StackSlot,
8866                                MachinePointerInfo::getFixedStack(SSFI),
8867                                false, false, 0);
8868   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8869 }
8870
8871 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8872                                      SDValue StackSlot,
8873                                      SelectionDAG &DAG) const {
8874   // Build the FILD
8875   SDLoc DL(Op);
8876   SDVTList Tys;
8877   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8878   if (useSSE)
8879     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8880   else
8881     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8882
8883   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8884
8885   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8886   MachineMemOperand *MMO;
8887   if (FI) {
8888     int SSFI = FI->getIndex();
8889     MMO =
8890       DAG.getMachineFunction()
8891       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8892                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8893   } else {
8894     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8895     StackSlot = StackSlot.getOperand(1);
8896   }
8897   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8898   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8899                                            X86ISD::FILD, DL,
8900                                            Tys, Ops, SrcVT, MMO);
8901
8902   if (useSSE) {
8903     Chain = Result.getValue(1);
8904     SDValue InFlag = Result.getValue(2);
8905
8906     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8907     // shouldn't be necessary except that RFP cannot be live across
8908     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8909     MachineFunction &MF = DAG.getMachineFunction();
8910     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8911     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8912     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8913     Tys = DAG.getVTList(MVT::Other);
8914     SDValue Ops[] = {
8915       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8916     };
8917     MachineMemOperand *MMO =
8918       DAG.getMachineFunction()
8919       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8920                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8921
8922     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8923                                     Ops, Op.getValueType(), MMO);
8924     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8925                          MachinePointerInfo::getFixedStack(SSFI),
8926                          false, false, false, 0);
8927   }
8928
8929   return Result;
8930 }
8931
8932 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8933 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8934                                                SelectionDAG &DAG) const {
8935   // This algorithm is not obvious. Here it is what we're trying to output:
8936   /*
8937      movq       %rax,  %xmm0
8938      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8939      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8940      #ifdef __SSE3__
8941        haddpd   %xmm0, %xmm0
8942      #else
8943        pshufd   $0x4e, %xmm0, %xmm1
8944        addpd    %xmm1, %xmm0
8945      #endif
8946   */
8947
8948   SDLoc dl(Op);
8949   LLVMContext *Context = DAG.getContext();
8950
8951   // Build some magic constants.
8952   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8953   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8954   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8955
8956   SmallVector<Constant*,2> CV1;
8957   CV1.push_back(
8958     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8959                                       APInt(64, 0x4330000000000000ULL))));
8960   CV1.push_back(
8961     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8962                                       APInt(64, 0x4530000000000000ULL))));
8963   Constant *C1 = ConstantVector::get(CV1);
8964   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8965
8966   // Load the 64-bit value into an XMM register.
8967   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8968                             Op.getOperand(0));
8969   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8970                               MachinePointerInfo::getConstantPool(),
8971                               false, false, false, 16);
8972   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8973                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8974                               CLod0);
8975
8976   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8977                               MachinePointerInfo::getConstantPool(),
8978                               false, false, false, 16);
8979   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8980   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8981   SDValue Result;
8982
8983   if (Subtarget->hasSSE3()) {
8984     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8985     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8986   } else {
8987     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8988     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8989                                            S2F, 0x4E, DAG);
8990     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8991                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8992                          Sub);
8993   }
8994
8995   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8996                      DAG.getIntPtrConstant(0));
8997 }
8998
8999 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9000 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9001                                                SelectionDAG &DAG) const {
9002   SDLoc dl(Op);
9003   // FP constant to bias correct the final result.
9004   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9005                                    MVT::f64);
9006
9007   // Load the 32-bit value into an XMM register.
9008   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9009                              Op.getOperand(0));
9010
9011   // Zero out the upper parts of the register.
9012   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9013
9014   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9015                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9016                      DAG.getIntPtrConstant(0));
9017
9018   // Or the load with the bias.
9019   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9020                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9021                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9022                                                    MVT::v2f64, Load)),
9023                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9024                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9025                                                    MVT::v2f64, Bias)));
9026   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9027                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9028                    DAG.getIntPtrConstant(0));
9029
9030   // Subtract the bias.
9031   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9032
9033   // Handle final rounding.
9034   EVT DestVT = Op.getValueType();
9035
9036   if (DestVT.bitsLT(MVT::f64))
9037     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9038                        DAG.getIntPtrConstant(0));
9039   if (DestVT.bitsGT(MVT::f64))
9040     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9041
9042   // Handle final rounding.
9043   return Sub;
9044 }
9045
9046 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9047                                                SelectionDAG &DAG) const {
9048   SDValue N0 = Op.getOperand(0);
9049   MVT SVT = N0.getSimpleValueType();
9050   SDLoc dl(Op);
9051
9052   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9053           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9054          "Custom UINT_TO_FP is not supported!");
9055
9056   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9057   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9058                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9059 }
9060
9061 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9062                                            SelectionDAG &DAG) const {
9063   SDValue N0 = Op.getOperand(0);
9064   SDLoc dl(Op);
9065
9066   if (Op.getValueType().isVector())
9067     return lowerUINT_TO_FP_vec(Op, DAG);
9068
9069   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9070   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9071   // the optimization here.
9072   if (DAG.SignBitIsZero(N0))
9073     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9074
9075   MVT SrcVT = N0.getSimpleValueType();
9076   MVT DstVT = Op.getSimpleValueType();
9077   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9078     return LowerUINT_TO_FP_i64(Op, DAG);
9079   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9080     return LowerUINT_TO_FP_i32(Op, DAG);
9081   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9082     return SDValue();
9083
9084   // Make a 64-bit buffer, and use it to build an FILD.
9085   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9086   if (SrcVT == MVT::i32) {
9087     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9088     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9089                                      getPointerTy(), StackSlot, WordOff);
9090     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9091                                   StackSlot, MachinePointerInfo(),
9092                                   false, false, 0);
9093     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9094                                   OffsetSlot, MachinePointerInfo(),
9095                                   false, false, 0);
9096     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9097     return Fild;
9098   }
9099
9100   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9101   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9102                                StackSlot, MachinePointerInfo(),
9103                                false, false, 0);
9104   // For i64 source, we need to add the appropriate power of 2 if the input
9105   // was negative.  This is the same as the optimization in
9106   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9107   // we must be careful to do the computation in x87 extended precision, not
9108   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9109   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9110   MachineMemOperand *MMO =
9111     DAG.getMachineFunction()
9112     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9113                           MachineMemOperand::MOLoad, 8, 8);
9114
9115   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9116   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9117   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9118                                          MVT::i64, MMO);
9119
9120   APInt FF(32, 0x5F800000ULL);
9121
9122   // Check whether the sign bit is set.
9123   SDValue SignSet = DAG.getSetCC(dl,
9124                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9125                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9126                                  ISD::SETLT);
9127
9128   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9129   SDValue FudgePtr = DAG.getConstantPool(
9130                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9131                                          getPointerTy());
9132
9133   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9134   SDValue Zero = DAG.getIntPtrConstant(0);
9135   SDValue Four = DAG.getIntPtrConstant(4);
9136   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9137                                Zero, Four);
9138   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9139
9140   // Load the value out, extending it from f32 to f80.
9141   // FIXME: Avoid the extend by constructing the right constant pool?
9142   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9143                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9144                                  MVT::f32, false, false, 4);
9145   // Extend everything to 80 bits to force it to be done on x87.
9146   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9147   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9148 }
9149
9150 std::pair<SDValue,SDValue>
9151 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9152                                     bool IsSigned, bool IsReplace) const {
9153   SDLoc DL(Op);
9154
9155   EVT DstTy = Op.getValueType();
9156
9157   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9158     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9159     DstTy = MVT::i64;
9160   }
9161
9162   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9163          DstTy.getSimpleVT() >= MVT::i16 &&
9164          "Unknown FP_TO_INT to lower!");
9165
9166   // These are really Legal.
9167   if (DstTy == MVT::i32 &&
9168       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9169     return std::make_pair(SDValue(), SDValue());
9170   if (Subtarget->is64Bit() &&
9171       DstTy == MVT::i64 &&
9172       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9173     return std::make_pair(SDValue(), SDValue());
9174
9175   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9176   // stack slot, or into the FTOL runtime function.
9177   MachineFunction &MF = DAG.getMachineFunction();
9178   unsigned MemSize = DstTy.getSizeInBits()/8;
9179   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9180   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9181
9182   unsigned Opc;
9183   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9184     Opc = X86ISD::WIN_FTOL;
9185   else
9186     switch (DstTy.getSimpleVT().SimpleTy) {
9187     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9188     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9189     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9190     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9191     }
9192
9193   SDValue Chain = DAG.getEntryNode();
9194   SDValue Value = Op.getOperand(0);
9195   EVT TheVT = Op.getOperand(0).getValueType();
9196   // FIXME This causes a redundant load/store if the SSE-class value is already
9197   // in memory, such as if it is on the callstack.
9198   if (isScalarFPTypeInSSEReg(TheVT)) {
9199     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9200     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9201                          MachinePointerInfo::getFixedStack(SSFI),
9202                          false, false, 0);
9203     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9204     SDValue Ops[] = {
9205       Chain, StackSlot, DAG.getValueType(TheVT)
9206     };
9207
9208     MachineMemOperand *MMO =
9209       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9210                               MachineMemOperand::MOLoad, MemSize, MemSize);
9211     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9212     Chain = Value.getValue(1);
9213     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9214     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9215   }
9216
9217   MachineMemOperand *MMO =
9218     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9219                             MachineMemOperand::MOStore, MemSize, MemSize);
9220
9221   if (Opc != X86ISD::WIN_FTOL) {
9222     // Build the FP_TO_INT*_IN_MEM
9223     SDValue Ops[] = { Chain, Value, StackSlot };
9224     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9225                                            Ops, DstTy, MMO);
9226     return std::make_pair(FIST, StackSlot);
9227   } else {
9228     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9229       DAG.getVTList(MVT::Other, MVT::Glue),
9230       Chain, Value);
9231     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9232       MVT::i32, ftol.getValue(1));
9233     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9234       MVT::i32, eax.getValue(2));
9235     SDValue Ops[] = { eax, edx };
9236     SDValue pair = IsReplace
9237       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9238       : DAG.getMergeValues(Ops, DL);
9239     return std::make_pair(pair, SDValue());
9240   }
9241 }
9242
9243 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9244                               const X86Subtarget *Subtarget) {
9245   MVT VT = Op->getSimpleValueType(0);
9246   SDValue In = Op->getOperand(0);
9247   MVT InVT = In.getSimpleValueType();
9248   SDLoc dl(Op);
9249
9250   // Optimize vectors in AVX mode:
9251   //
9252   //   v8i16 -> v8i32
9253   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9254   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9255   //   Concat upper and lower parts.
9256   //
9257   //   v4i32 -> v4i64
9258   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9259   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9260   //   Concat upper and lower parts.
9261   //
9262
9263   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9264       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9265       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9266     return SDValue();
9267
9268   if (Subtarget->hasInt256())
9269     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9270
9271   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9272   SDValue Undef = DAG.getUNDEF(InVT);
9273   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9274   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9275   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9276
9277   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9278                              VT.getVectorNumElements()/2);
9279
9280   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9281   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9282
9283   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9284 }
9285
9286 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9287                                         SelectionDAG &DAG) {
9288   MVT VT = Op->getSimpleValueType(0);
9289   SDValue In = Op->getOperand(0);
9290   MVT InVT = In.getSimpleValueType();
9291   SDLoc DL(Op);
9292   unsigned int NumElts = VT.getVectorNumElements();
9293   if (NumElts != 8 && NumElts != 16)
9294     return SDValue();
9295
9296   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9297     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9298
9299   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9301   // Now we have only mask extension
9302   assert(InVT.getVectorElementType() == MVT::i1);
9303   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9304   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9305   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9306   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9307   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9308                            MachinePointerInfo::getConstantPool(),
9309                            false, false, false, Alignment);
9310
9311   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9312   if (VT.is512BitVector())
9313     return Brcst;
9314   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9315 }
9316
9317 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9318                                SelectionDAG &DAG) {
9319   if (Subtarget->hasFp256()) {
9320     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9321     if (Res.getNode())
9322       return Res;
9323   }
9324
9325   return SDValue();
9326 }
9327
9328 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9329                                 SelectionDAG &DAG) {
9330   SDLoc DL(Op);
9331   MVT VT = Op.getSimpleValueType();
9332   SDValue In = Op.getOperand(0);
9333   MVT SVT = In.getSimpleValueType();
9334
9335   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9336     return LowerZERO_EXTEND_AVX512(Op, DAG);
9337
9338   if (Subtarget->hasFp256()) {
9339     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9340     if (Res.getNode())
9341       return Res;
9342   }
9343
9344   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9345          VT.getVectorNumElements() != SVT.getVectorNumElements());
9346   return SDValue();
9347 }
9348
9349 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9350   SDLoc DL(Op);
9351   MVT VT = Op.getSimpleValueType();
9352   SDValue In = Op.getOperand(0);
9353   MVT InVT = In.getSimpleValueType();
9354
9355   if (VT == MVT::i1) {
9356     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9357            "Invalid scalar TRUNCATE operation");
9358     if (InVT == MVT::i32)
9359       return SDValue();
9360     if (InVT.getSizeInBits() == 64)
9361       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9362     else if (InVT.getSizeInBits() < 32)
9363       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9364     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9365   }
9366   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9367          "Invalid TRUNCATE operation");
9368
9369   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9370     if (VT.getVectorElementType().getSizeInBits() >=8)
9371       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9372
9373     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9374     unsigned NumElts = InVT.getVectorNumElements();
9375     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9376     if (InVT.getSizeInBits() < 512) {
9377       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9378       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9379       InVT = ExtVT;
9380     }
9381     
9382     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9383     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9384     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9385     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9386     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9387                            MachinePointerInfo::getConstantPool(),
9388                            false, false, false, Alignment);
9389     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9390     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9391     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9392   }
9393
9394   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9395     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9396     if (Subtarget->hasInt256()) {
9397       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9398       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9399       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9400                                 ShufMask);
9401       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9402                          DAG.getIntPtrConstant(0));
9403     }
9404
9405     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9406                                DAG.getIntPtrConstant(0));
9407     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9408                                DAG.getIntPtrConstant(2));
9409     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9410     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9411     static const int ShufMask[] = {0, 2, 4, 6};
9412     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9413   }
9414
9415   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9416     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9417     if (Subtarget->hasInt256()) {
9418       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9419
9420       SmallVector<SDValue,32> pshufbMask;
9421       for (unsigned i = 0; i < 2; ++i) {
9422         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9423         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9424         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9425         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9426         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9427         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9428         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9429         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9430         for (unsigned j = 0; j < 8; ++j)
9431           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9432       }
9433       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9434       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9435       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9436
9437       static const int ShufMask[] = {0,  2,  -1,  -1};
9438       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9439                                 &ShufMask[0]);
9440       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9441                        DAG.getIntPtrConstant(0));
9442       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9443     }
9444
9445     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9446                                DAG.getIntPtrConstant(0));
9447
9448     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9449                                DAG.getIntPtrConstant(4));
9450
9451     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9452     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9453
9454     // The PSHUFB mask:
9455     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9456                                    -1, -1, -1, -1, -1, -1, -1, -1};
9457
9458     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9459     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9460     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9461
9462     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9463     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9464
9465     // The MOVLHPS Mask:
9466     static const int ShufMask2[] = {0, 1, 4, 5};
9467     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9468     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9469   }
9470
9471   // Handle truncation of V256 to V128 using shuffles.
9472   if (!VT.is128BitVector() || !InVT.is256BitVector())
9473     return SDValue();
9474
9475   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9476
9477   unsigned NumElems = VT.getVectorNumElements();
9478   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9479
9480   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9481   // Prepare truncation shuffle mask
9482   for (unsigned i = 0; i != NumElems; ++i)
9483     MaskVec[i] = i * 2;
9484   SDValue V = DAG.getVectorShuffle(NVT, DL,
9485                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9486                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9487   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9488                      DAG.getIntPtrConstant(0));
9489 }
9490
9491 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9492                                            SelectionDAG &DAG) const {
9493   assert(!Op.getSimpleValueType().isVector());
9494
9495   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9496     /*IsSigned=*/ true, /*IsReplace=*/ false);
9497   SDValue FIST = Vals.first, StackSlot = Vals.second;
9498   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9499   if (!FIST.getNode()) return Op;
9500
9501   if (StackSlot.getNode())
9502     // Load the result.
9503     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9504                        FIST, StackSlot, MachinePointerInfo(),
9505                        false, false, false, 0);
9506
9507   // The node is the result.
9508   return FIST;
9509 }
9510
9511 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9512                                            SelectionDAG &DAG) const {
9513   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9514     /*IsSigned=*/ false, /*IsReplace=*/ false);
9515   SDValue FIST = Vals.first, StackSlot = Vals.second;
9516   assert(FIST.getNode() && "Unexpected failure");
9517
9518   if (StackSlot.getNode())
9519     // Load the result.
9520     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9521                        FIST, StackSlot, MachinePointerInfo(),
9522                        false, false, false, 0);
9523
9524   // The node is the result.
9525   return FIST;
9526 }
9527
9528 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9529   SDLoc DL(Op);
9530   MVT VT = Op.getSimpleValueType();
9531   SDValue In = Op.getOperand(0);
9532   MVT SVT = In.getSimpleValueType();
9533
9534   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9535
9536   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9537                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9538                                  In, DAG.getUNDEF(SVT)));
9539 }
9540
9541 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9542   LLVMContext *Context = DAG.getContext();
9543   SDLoc dl(Op);
9544   MVT VT = Op.getSimpleValueType();
9545   MVT EltVT = VT;
9546   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9547   if (VT.isVector()) {
9548     EltVT = VT.getVectorElementType();
9549     NumElts = VT.getVectorNumElements();
9550   }
9551   Constant *C;
9552   if (EltVT == MVT::f64)
9553     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9554                                           APInt(64, ~(1ULL << 63))));
9555   else
9556     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9557                                           APInt(32, ~(1U << 31))));
9558   C = ConstantVector::getSplat(NumElts, C);
9559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9560   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9561   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9562   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9563                              MachinePointerInfo::getConstantPool(),
9564                              false, false, false, Alignment);
9565   if (VT.isVector()) {
9566     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9567     return DAG.getNode(ISD::BITCAST, dl, VT,
9568                        DAG.getNode(ISD::AND, dl, ANDVT,
9569                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9570                                                Op.getOperand(0)),
9571                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9572   }
9573   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9574 }
9575
9576 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9577   LLVMContext *Context = DAG.getContext();
9578   SDLoc dl(Op);
9579   MVT VT = Op.getSimpleValueType();
9580   MVT EltVT = VT;
9581   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9582   if (VT.isVector()) {
9583     EltVT = VT.getVectorElementType();
9584     NumElts = VT.getVectorNumElements();
9585   }
9586   Constant *C;
9587   if (EltVT == MVT::f64)
9588     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9589                                           APInt(64, 1ULL << 63)));
9590   else
9591     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9592                                           APInt(32, 1U << 31)));
9593   C = ConstantVector::getSplat(NumElts, C);
9594   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9595   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9596   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9597   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9598                              MachinePointerInfo::getConstantPool(),
9599                              false, false, false, Alignment);
9600   if (VT.isVector()) {
9601     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9602     return DAG.getNode(ISD::BITCAST, dl, VT,
9603                        DAG.getNode(ISD::XOR, dl, XORVT,
9604                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9605                                                Op.getOperand(0)),
9606                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9607   }
9608
9609   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9610 }
9611
9612 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9613   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9614   LLVMContext *Context = DAG.getContext();
9615   SDValue Op0 = Op.getOperand(0);
9616   SDValue Op1 = Op.getOperand(1);
9617   SDLoc dl(Op);
9618   MVT VT = Op.getSimpleValueType();
9619   MVT SrcVT = Op1.getSimpleValueType();
9620
9621   // If second operand is smaller, extend it first.
9622   if (SrcVT.bitsLT(VT)) {
9623     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9624     SrcVT = VT;
9625   }
9626   // And if it is bigger, shrink it first.
9627   if (SrcVT.bitsGT(VT)) {
9628     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9629     SrcVT = VT;
9630   }
9631
9632   // At this point the operands and the result should have the same
9633   // type, and that won't be f80 since that is not custom lowered.
9634
9635   // First get the sign bit of second operand.
9636   SmallVector<Constant*,4> CV;
9637   if (SrcVT == MVT::f64) {
9638     const fltSemantics &Sem = APFloat::IEEEdouble;
9639     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9640     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9641   } else {
9642     const fltSemantics &Sem = APFloat::IEEEsingle;
9643     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9644     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9645     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9646     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9647   }
9648   Constant *C = ConstantVector::get(CV);
9649   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9650   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9651                               MachinePointerInfo::getConstantPool(),
9652                               false, false, false, 16);
9653   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9654
9655   // Shift sign bit right or left if the two operands have different types.
9656   if (SrcVT.bitsGT(VT)) {
9657     // Op0 is MVT::f32, Op1 is MVT::f64.
9658     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9659     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9660                           DAG.getConstant(32, MVT::i32));
9661     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9662     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9663                           DAG.getIntPtrConstant(0));
9664   }
9665
9666   // Clear first operand sign bit.
9667   CV.clear();
9668   if (VT == MVT::f64) {
9669     const fltSemantics &Sem = APFloat::IEEEdouble;
9670     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9671                                                    APInt(64, ~(1ULL << 63)))));
9672     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9673   } else {
9674     const fltSemantics &Sem = APFloat::IEEEsingle;
9675     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9676                                                    APInt(32, ~(1U << 31)))));
9677     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9678     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9679     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9680   }
9681   C = ConstantVector::get(CV);
9682   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9683   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9684                               MachinePointerInfo::getConstantPool(),
9685                               false, false, false, 16);
9686   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9687
9688   // Or the value with the sign bit.
9689   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9690 }
9691
9692 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9693   SDValue N0 = Op.getOperand(0);
9694   SDLoc dl(Op);
9695   MVT VT = Op.getSimpleValueType();
9696
9697   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9698   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9699                                   DAG.getConstant(1, VT));
9700   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9701 }
9702
9703 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9704 //
9705 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9706                                       SelectionDAG &DAG) {
9707   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9708
9709   if (!Subtarget->hasSSE41())
9710     return SDValue();
9711
9712   if (!Op->hasOneUse())
9713     return SDValue();
9714
9715   SDNode *N = Op.getNode();
9716   SDLoc DL(N);
9717
9718   SmallVector<SDValue, 8> Opnds;
9719   DenseMap<SDValue, unsigned> VecInMap;
9720   SmallVector<SDValue, 8> VecIns;
9721   EVT VT = MVT::Other;
9722
9723   // Recognize a special case where a vector is casted into wide integer to
9724   // test all 0s.
9725   Opnds.push_back(N->getOperand(0));
9726   Opnds.push_back(N->getOperand(1));
9727
9728   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9729     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9730     // BFS traverse all OR'd operands.
9731     if (I->getOpcode() == ISD::OR) {
9732       Opnds.push_back(I->getOperand(0));
9733       Opnds.push_back(I->getOperand(1));
9734       // Re-evaluate the number of nodes to be traversed.
9735       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9736       continue;
9737     }
9738
9739     // Quit if a non-EXTRACT_VECTOR_ELT
9740     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9741       return SDValue();
9742
9743     // Quit if without a constant index.
9744     SDValue Idx = I->getOperand(1);
9745     if (!isa<ConstantSDNode>(Idx))
9746       return SDValue();
9747
9748     SDValue ExtractedFromVec = I->getOperand(0);
9749     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9750     if (M == VecInMap.end()) {
9751       VT = ExtractedFromVec.getValueType();
9752       // Quit if not 128/256-bit vector.
9753       if (!VT.is128BitVector() && !VT.is256BitVector())
9754         return SDValue();
9755       // Quit if not the same type.
9756       if (VecInMap.begin() != VecInMap.end() &&
9757           VT != VecInMap.begin()->first.getValueType())
9758         return SDValue();
9759       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9760       VecIns.push_back(ExtractedFromVec);
9761     }
9762     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9763   }
9764
9765   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9766          "Not extracted from 128-/256-bit vector.");
9767
9768   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9769
9770   for (DenseMap<SDValue, unsigned>::const_iterator
9771         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9772     // Quit if not all elements are used.
9773     if (I->second != FullMask)
9774       return SDValue();
9775   }
9776
9777   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9778
9779   // Cast all vectors into TestVT for PTEST.
9780   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9781     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9782
9783   // If more than one full vectors are evaluated, OR them first before PTEST.
9784   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9785     // Each iteration will OR 2 nodes and append the result until there is only
9786     // 1 node left, i.e. the final OR'd value of all vectors.
9787     SDValue LHS = VecIns[Slot];
9788     SDValue RHS = VecIns[Slot + 1];
9789     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9790   }
9791
9792   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9793                      VecIns.back(), VecIns.back());
9794 }
9795
9796 /// \brief return true if \c Op has a use that doesn't just read flags.
9797 static bool hasNonFlagsUse(SDValue Op) {
9798   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9799        ++UI) {
9800     SDNode *User = *UI;
9801     unsigned UOpNo = UI.getOperandNo();
9802     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9803       // Look pass truncate.
9804       UOpNo = User->use_begin().getOperandNo();
9805       User = *User->use_begin();
9806     }
9807
9808     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9809         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9810       return true;
9811   }
9812   return false;
9813 }
9814
9815 /// Emit nodes that will be selected as "test Op0,Op0", or something
9816 /// equivalent.
9817 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9818                                     SelectionDAG &DAG) const {
9819   if (Op.getValueType() == MVT::i1)
9820     // KORTEST instruction should be selected
9821     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9822                        DAG.getConstant(0, Op.getValueType()));
9823
9824   // CF and OF aren't always set the way we want. Determine which
9825   // of these we need.
9826   bool NeedCF = false;
9827   bool NeedOF = false;
9828   switch (X86CC) {
9829   default: break;
9830   case X86::COND_A: case X86::COND_AE:
9831   case X86::COND_B: case X86::COND_BE:
9832     NeedCF = true;
9833     break;
9834   case X86::COND_G: case X86::COND_GE:
9835   case X86::COND_L: case X86::COND_LE:
9836   case X86::COND_O: case X86::COND_NO:
9837     NeedOF = true;
9838     break;
9839   }
9840   // See if we can use the EFLAGS value from the operand instead of
9841   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9842   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9843   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9844     // Emit a CMP with 0, which is the TEST pattern.
9845     //if (Op.getValueType() == MVT::i1)
9846     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9847     //                     DAG.getConstant(0, MVT::i1));
9848     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9849                        DAG.getConstant(0, Op.getValueType()));
9850   }
9851   unsigned Opcode = 0;
9852   unsigned NumOperands = 0;
9853
9854   // Truncate operations may prevent the merge of the SETCC instruction
9855   // and the arithmetic instruction before it. Attempt to truncate the operands
9856   // of the arithmetic instruction and use a reduced bit-width instruction.
9857   bool NeedTruncation = false;
9858   SDValue ArithOp = Op;
9859   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9860     SDValue Arith = Op->getOperand(0);
9861     // Both the trunc and the arithmetic op need to have one user each.
9862     if (Arith->hasOneUse())
9863       switch (Arith.getOpcode()) {
9864         default: break;
9865         case ISD::ADD:
9866         case ISD::SUB:
9867         case ISD::AND:
9868         case ISD::OR:
9869         case ISD::XOR: {
9870           NeedTruncation = true;
9871           ArithOp = Arith;
9872         }
9873       }
9874   }
9875
9876   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9877   // which may be the result of a CAST.  We use the variable 'Op', which is the
9878   // non-casted variable when we check for possible users.
9879   switch (ArithOp.getOpcode()) {
9880   case ISD::ADD:
9881     // Due to an isel shortcoming, be conservative if this add is likely to be
9882     // selected as part of a load-modify-store instruction. When the root node
9883     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9884     // uses of other nodes in the match, such as the ADD in this case. This
9885     // leads to the ADD being left around and reselected, with the result being
9886     // two adds in the output.  Alas, even if none our users are stores, that
9887     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9888     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9889     // climbing the DAG back to the root, and it doesn't seem to be worth the
9890     // effort.
9891     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9892          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9893       if (UI->getOpcode() != ISD::CopyToReg &&
9894           UI->getOpcode() != ISD::SETCC &&
9895           UI->getOpcode() != ISD::STORE)
9896         goto default_case;
9897
9898     if (ConstantSDNode *C =
9899         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9900       // An add of one will be selected as an INC.
9901       if (C->getAPIntValue() == 1) {
9902         Opcode = X86ISD::INC;
9903         NumOperands = 1;
9904         break;
9905       }
9906
9907       // An add of negative one (subtract of one) will be selected as a DEC.
9908       if (C->getAPIntValue().isAllOnesValue()) {
9909         Opcode = X86ISD::DEC;
9910         NumOperands = 1;
9911         break;
9912       }
9913     }
9914
9915     // Otherwise use a regular EFLAGS-setting add.
9916     Opcode = X86ISD::ADD;
9917     NumOperands = 2;
9918     break;
9919   case ISD::SHL:
9920   case ISD::SRL:
9921     // If we have a constant logical shift that's only used in a comparison
9922     // against zero turn it into an equivalent AND. This allows turning it into
9923     // a TEST instruction later.
9924     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9925         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9926       EVT VT = Op.getValueType();
9927       unsigned BitWidth = VT.getSizeInBits();
9928       unsigned ShAmt = Op->getConstantOperandVal(1);
9929       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9930         break;
9931       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9932                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9933                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9934       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9935         break;
9936       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9937                                 DAG.getConstant(Mask, VT));
9938       DAG.ReplaceAllUsesWith(Op, New);
9939       Op = New;
9940     }
9941     break;
9942
9943   case ISD::AND:
9944     // If the primary and result isn't used, don't bother using X86ISD::AND,
9945     // because a TEST instruction will be better.
9946     if (!hasNonFlagsUse(Op))
9947       break;
9948     // FALL THROUGH
9949   case ISD::SUB:
9950   case ISD::OR:
9951   case ISD::XOR:
9952     // Due to the ISEL shortcoming noted above, be conservative if this op is
9953     // likely to be selected as part of a load-modify-store instruction.
9954     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9955            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9956       if (UI->getOpcode() == ISD::STORE)
9957         goto default_case;
9958
9959     // Otherwise use a regular EFLAGS-setting instruction.
9960     switch (ArithOp.getOpcode()) {
9961     default: llvm_unreachable("unexpected operator!");
9962     case ISD::SUB: Opcode = X86ISD::SUB; break;
9963     case ISD::XOR: Opcode = X86ISD::XOR; break;
9964     case ISD::AND: Opcode = X86ISD::AND; break;
9965     case ISD::OR: {
9966       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9967         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9968         if (EFLAGS.getNode())
9969           return EFLAGS;
9970       }
9971       Opcode = X86ISD::OR;
9972       break;
9973     }
9974     }
9975
9976     NumOperands = 2;
9977     break;
9978   case X86ISD::ADD:
9979   case X86ISD::SUB:
9980   case X86ISD::INC:
9981   case X86ISD::DEC:
9982   case X86ISD::OR:
9983   case X86ISD::XOR:
9984   case X86ISD::AND:
9985     return SDValue(Op.getNode(), 1);
9986   default:
9987   default_case:
9988     break;
9989   }
9990
9991   // If we found that truncation is beneficial, perform the truncation and
9992   // update 'Op'.
9993   if (NeedTruncation) {
9994     EVT VT = Op.getValueType();
9995     SDValue WideVal = Op->getOperand(0);
9996     EVT WideVT = WideVal.getValueType();
9997     unsigned ConvertedOp = 0;
9998     // Use a target machine opcode to prevent further DAGCombine
9999     // optimizations that may separate the arithmetic operations
10000     // from the setcc node.
10001     switch (WideVal.getOpcode()) {
10002       default: break;
10003       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10004       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10005       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10006       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10007       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10008     }
10009
10010     if (ConvertedOp) {
10011       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10012       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10013         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10014         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10015         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10016       }
10017     }
10018   }
10019
10020   if (Opcode == 0)
10021     // Emit a CMP with 0, which is the TEST pattern.
10022     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10023                        DAG.getConstant(0, Op.getValueType()));
10024
10025   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10026   SmallVector<SDValue, 4> Ops;
10027   for (unsigned i = 0; i != NumOperands; ++i)
10028     Ops.push_back(Op.getOperand(i));
10029
10030   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10031   DAG.ReplaceAllUsesWith(Op, New);
10032   return SDValue(New.getNode(), 1);
10033 }
10034
10035 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10036 /// equivalent.
10037 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10038                                    SDLoc dl, SelectionDAG &DAG) const {
10039   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10040     if (C->getAPIntValue() == 0)
10041       return EmitTest(Op0, X86CC, dl, DAG);
10042
10043      if (Op0.getValueType() == MVT::i1)
10044        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10045   }
10046  
10047   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10048        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10049     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10050     // This avoids subregister aliasing issues. Keep the smaller reference 
10051     // if we're optimizing for size, however, as that'll allow better folding 
10052     // of memory operations.
10053     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10054         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10055              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10056         !Subtarget->isAtom()) {
10057       unsigned ExtendOp =
10058           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10059       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10060       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10061     }
10062     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10063     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10064     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10065                               Op0, Op1);
10066     return SDValue(Sub.getNode(), 1);
10067   }
10068   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10069 }
10070
10071 /// Convert a comparison if required by the subtarget.
10072 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10073                                                  SelectionDAG &DAG) const {
10074   // If the subtarget does not support the FUCOMI instruction, floating-point
10075   // comparisons have to be converted.
10076   if (Subtarget->hasCMov() ||
10077       Cmp.getOpcode() != X86ISD::CMP ||
10078       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10079       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10080     return Cmp;
10081
10082   // The instruction selector will select an FUCOM instruction instead of
10083   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10084   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10085   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10086   SDLoc dl(Cmp);
10087   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10088   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10089   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10090                             DAG.getConstant(8, MVT::i8));
10091   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10092   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10093 }
10094
10095 static bool isAllOnes(SDValue V) {
10096   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10097   return C && C->isAllOnesValue();
10098 }
10099
10100 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10101 /// if it's possible.
10102 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10103                                      SDLoc dl, SelectionDAG &DAG) const {
10104   SDValue Op0 = And.getOperand(0);
10105   SDValue Op1 = And.getOperand(1);
10106   if (Op0.getOpcode() == ISD::TRUNCATE)
10107     Op0 = Op0.getOperand(0);
10108   if (Op1.getOpcode() == ISD::TRUNCATE)
10109     Op1 = Op1.getOperand(0);
10110
10111   SDValue LHS, RHS;
10112   if (Op1.getOpcode() == ISD::SHL)
10113     std::swap(Op0, Op1);
10114   if (Op0.getOpcode() == ISD::SHL) {
10115     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10116       if (And00C->getZExtValue() == 1) {
10117         // If we looked past a truncate, check that it's only truncating away
10118         // known zeros.
10119         unsigned BitWidth = Op0.getValueSizeInBits();
10120         unsigned AndBitWidth = And.getValueSizeInBits();
10121         if (BitWidth > AndBitWidth) {
10122           APInt Zeros, Ones;
10123           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10124           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10125             return SDValue();
10126         }
10127         LHS = Op1;
10128         RHS = Op0.getOperand(1);
10129       }
10130   } else if (Op1.getOpcode() == ISD::Constant) {
10131     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10132     uint64_t AndRHSVal = AndRHS->getZExtValue();
10133     SDValue AndLHS = Op0;
10134
10135     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10136       LHS = AndLHS.getOperand(0);
10137       RHS = AndLHS.getOperand(1);
10138     }
10139
10140     // Use BT if the immediate can't be encoded in a TEST instruction.
10141     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10142       LHS = AndLHS;
10143       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10144     }
10145   }
10146
10147   if (LHS.getNode()) {
10148     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10149     // instruction.  Since the shift amount is in-range-or-undefined, we know
10150     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10151     // the encoding for the i16 version is larger than the i32 version.
10152     // Also promote i16 to i32 for performance / code size reason.
10153     if (LHS.getValueType() == MVT::i8 ||
10154         LHS.getValueType() == MVT::i16)
10155       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10156
10157     // If the operand types disagree, extend the shift amount to match.  Since
10158     // BT ignores high bits (like shifts) we can use anyextend.
10159     if (LHS.getValueType() != RHS.getValueType())
10160       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10161
10162     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10163     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10164     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10165                        DAG.getConstant(Cond, MVT::i8), BT);
10166   }
10167
10168   return SDValue();
10169 }
10170
10171 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10172 /// mask CMPs.
10173 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10174                               SDValue &Op1) {
10175   unsigned SSECC;
10176   bool Swap = false;
10177
10178   // SSE Condition code mapping:
10179   //  0 - EQ
10180   //  1 - LT
10181   //  2 - LE
10182   //  3 - UNORD
10183   //  4 - NEQ
10184   //  5 - NLT
10185   //  6 - NLE
10186   //  7 - ORD
10187   switch (SetCCOpcode) {
10188   default: llvm_unreachable("Unexpected SETCC condition");
10189   case ISD::SETOEQ:
10190   case ISD::SETEQ:  SSECC = 0; break;
10191   case ISD::SETOGT:
10192   case ISD::SETGT:  Swap = true; // Fallthrough
10193   case ISD::SETLT:
10194   case ISD::SETOLT: SSECC = 1; break;
10195   case ISD::SETOGE:
10196   case ISD::SETGE:  Swap = true; // Fallthrough
10197   case ISD::SETLE:
10198   case ISD::SETOLE: SSECC = 2; break;
10199   case ISD::SETUO:  SSECC = 3; break;
10200   case ISD::SETUNE:
10201   case ISD::SETNE:  SSECC = 4; break;
10202   case ISD::SETULE: Swap = true; // Fallthrough
10203   case ISD::SETUGE: SSECC = 5; break;
10204   case ISD::SETULT: Swap = true; // Fallthrough
10205   case ISD::SETUGT: SSECC = 6; break;
10206   case ISD::SETO:   SSECC = 7; break;
10207   case ISD::SETUEQ:
10208   case ISD::SETONE: SSECC = 8; break;
10209   }
10210   if (Swap)
10211     std::swap(Op0, Op1);
10212
10213   return SSECC;
10214 }
10215
10216 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10217 // ones, and then concatenate the result back.
10218 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10219   MVT VT = Op.getSimpleValueType();
10220
10221   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10222          "Unsupported value type for operation");
10223
10224   unsigned NumElems = VT.getVectorNumElements();
10225   SDLoc dl(Op);
10226   SDValue CC = Op.getOperand(2);
10227
10228   // Extract the LHS vectors
10229   SDValue LHS = Op.getOperand(0);
10230   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10231   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10232
10233   // Extract the RHS vectors
10234   SDValue RHS = Op.getOperand(1);
10235   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10236   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10237
10238   // Issue the operation on the smaller types and concatenate the result back
10239   MVT EltVT = VT.getVectorElementType();
10240   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10241   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10242                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10243                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10244 }
10245
10246 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10247                                      const X86Subtarget *Subtarget) {
10248   SDValue Op0 = Op.getOperand(0);
10249   SDValue Op1 = Op.getOperand(1);
10250   SDValue CC = Op.getOperand(2);
10251   MVT VT = Op.getSimpleValueType();
10252   SDLoc dl(Op);
10253
10254   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10255          Op.getValueType().getScalarType() == MVT::i1 &&
10256          "Cannot set masked compare for this operation");
10257
10258   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10259   unsigned  Opc = 0;
10260   bool Unsigned = false;
10261   bool Swap = false;
10262   unsigned SSECC;
10263   switch (SetCCOpcode) {
10264   default: llvm_unreachable("Unexpected SETCC condition");
10265   case ISD::SETNE:  SSECC = 4; break;
10266   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10267   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10268   case ISD::SETLT:  Swap = true; //fall-through
10269   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10270   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10271   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10272   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10273   case ISD::SETULE: Unsigned = true; //fall-through
10274   case ISD::SETLE:  SSECC = 2; break;
10275   }
10276
10277   if (Swap)
10278     std::swap(Op0, Op1);
10279   if (Opc)
10280     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10281   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10282   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10283                      DAG.getConstant(SSECC, MVT::i8));
10284 }
10285
10286 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10287 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10288 /// return an empty value.
10289 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10290 {
10291   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10292   if (!BV)
10293     return SDValue();
10294
10295   MVT VT = Op1.getSimpleValueType();
10296   MVT EVT = VT.getVectorElementType();
10297   unsigned n = VT.getVectorNumElements();
10298   SmallVector<SDValue, 8> ULTOp1;
10299
10300   for (unsigned i = 0; i < n; ++i) {
10301     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10302     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10303       return SDValue();
10304
10305     // Avoid underflow.
10306     APInt Val = Elt->getAPIntValue();
10307     if (Val == 0)
10308       return SDValue();
10309
10310     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10311   }
10312
10313   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10314 }
10315
10316 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10317                            SelectionDAG &DAG) {
10318   SDValue Op0 = Op.getOperand(0);
10319   SDValue Op1 = Op.getOperand(1);
10320   SDValue CC = Op.getOperand(2);
10321   MVT VT = Op.getSimpleValueType();
10322   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10323   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10324   SDLoc dl(Op);
10325
10326   if (isFP) {
10327 #ifndef NDEBUG
10328     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10329     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10330 #endif
10331
10332     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10333     unsigned Opc = X86ISD::CMPP;
10334     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10335       assert(VT.getVectorNumElements() <= 16);
10336       Opc = X86ISD::CMPM;
10337     }
10338     // In the two special cases we can't handle, emit two comparisons.
10339     if (SSECC == 8) {
10340       unsigned CC0, CC1;
10341       unsigned CombineOpc;
10342       if (SetCCOpcode == ISD::SETUEQ) {
10343         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10344       } else {
10345         assert(SetCCOpcode == ISD::SETONE);
10346         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10347       }
10348
10349       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10350                                  DAG.getConstant(CC0, MVT::i8));
10351       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10352                                  DAG.getConstant(CC1, MVT::i8));
10353       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10354     }
10355     // Handle all other FP comparisons here.
10356     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10357                        DAG.getConstant(SSECC, MVT::i8));
10358   }
10359
10360   // Break 256-bit integer vector compare into smaller ones.
10361   if (VT.is256BitVector() && !Subtarget->hasInt256())
10362     return Lower256IntVSETCC(Op, DAG);
10363
10364   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10365   EVT OpVT = Op1.getValueType();
10366   if (Subtarget->hasAVX512()) {
10367     if (Op1.getValueType().is512BitVector() ||
10368         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10369       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10370
10371     // In AVX-512 architecture setcc returns mask with i1 elements,
10372     // But there is no compare instruction for i8 and i16 elements.
10373     // We are not talking about 512-bit operands in this case, these
10374     // types are illegal.
10375     if (MaskResult &&
10376         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10377          OpVT.getVectorElementType().getSizeInBits() >= 8))
10378       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10379                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10380   }
10381
10382   // We are handling one of the integer comparisons here.  Since SSE only has
10383   // GT and EQ comparisons for integer, swapping operands and multiple
10384   // operations may be required for some comparisons.
10385   unsigned Opc;
10386   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10387   bool Subus = false;
10388
10389   switch (SetCCOpcode) {
10390   default: llvm_unreachable("Unexpected SETCC condition");
10391   case ISD::SETNE:  Invert = true;
10392   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10393   case ISD::SETLT:  Swap = true;
10394   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10395   case ISD::SETGE:  Swap = true;
10396   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10397                     Invert = true; break;
10398   case ISD::SETULT: Swap = true;
10399   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10400                     FlipSigns = true; break;
10401   case ISD::SETUGE: Swap = true;
10402   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10403                     FlipSigns = true; Invert = true; break;
10404   }
10405
10406   // Special case: Use min/max operations for SETULE/SETUGE
10407   MVT VET = VT.getVectorElementType();
10408   bool hasMinMax =
10409        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10410     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10411
10412   if (hasMinMax) {
10413     switch (SetCCOpcode) {
10414     default: break;
10415     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10416     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10417     }
10418
10419     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10420   }
10421
10422   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10423   if (!MinMax && hasSubus) {
10424     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10425     // Op0 u<= Op1:
10426     //   t = psubus Op0, Op1
10427     //   pcmpeq t, <0..0>
10428     switch (SetCCOpcode) {
10429     default: break;
10430     case ISD::SETULT: {
10431       // If the comparison is against a constant we can turn this into a
10432       // setule.  With psubus, setule does not require a swap.  This is
10433       // beneficial because the constant in the register is no longer
10434       // destructed as the destination so it can be hoisted out of a loop.
10435       // Only do this pre-AVX since vpcmp* is no longer destructive.
10436       if (Subtarget->hasAVX())
10437         break;
10438       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10439       if (ULEOp1.getNode()) {
10440         Op1 = ULEOp1;
10441         Subus = true; Invert = false; Swap = false;
10442       }
10443       break;
10444     }
10445     // Psubus is better than flip-sign because it requires no inversion.
10446     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10447     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10448     }
10449
10450     if (Subus) {
10451       Opc = X86ISD::SUBUS;
10452       FlipSigns = false;
10453     }
10454   }
10455
10456   if (Swap)
10457     std::swap(Op0, Op1);
10458
10459   // Check that the operation in question is available (most are plain SSE2,
10460   // but PCMPGTQ and PCMPEQQ have different requirements).
10461   if (VT == MVT::v2i64) {
10462     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10463       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10464
10465       // First cast everything to the right type.
10466       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10467       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10468
10469       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10470       // bits of the inputs before performing those operations. The lower
10471       // compare is always unsigned.
10472       SDValue SB;
10473       if (FlipSigns) {
10474         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10475       } else {
10476         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10477         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10478         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10479                          Sign, Zero, Sign, Zero);
10480       }
10481       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10482       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10483
10484       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10485       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10486       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10487
10488       // Create masks for only the low parts/high parts of the 64 bit integers.
10489       static const int MaskHi[] = { 1, 1, 3, 3 };
10490       static const int MaskLo[] = { 0, 0, 2, 2 };
10491       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10492       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10493       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10494
10495       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10496       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10497
10498       if (Invert)
10499         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10500
10501       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10502     }
10503
10504     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10505       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10506       // pcmpeqd + pshufd + pand.
10507       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10508
10509       // First cast everything to the right type.
10510       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10511       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10512
10513       // Do the compare.
10514       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10515
10516       // Make sure the lower and upper halves are both all-ones.
10517       static const int Mask[] = { 1, 0, 3, 2 };
10518       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10519       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10520
10521       if (Invert)
10522         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10523
10524       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10525     }
10526   }
10527
10528   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10529   // bits of the inputs before performing those operations.
10530   if (FlipSigns) {
10531     EVT EltVT = VT.getVectorElementType();
10532     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10533     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10534     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10535   }
10536
10537   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10538
10539   // If the logical-not of the result is required, perform that now.
10540   if (Invert)
10541     Result = DAG.getNOT(dl, Result, VT);
10542
10543   if (MinMax)
10544     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10545
10546   if (Subus)
10547     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10548                          getZeroVector(VT, Subtarget, DAG, dl));
10549
10550   return Result;
10551 }
10552
10553 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10554
10555   MVT VT = Op.getSimpleValueType();
10556
10557   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10558
10559   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10560          && "SetCC type must be 8-bit or 1-bit integer");
10561   SDValue Op0 = Op.getOperand(0);
10562   SDValue Op1 = Op.getOperand(1);
10563   SDLoc dl(Op);
10564   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10565
10566   // Optimize to BT if possible.
10567   // Lower (X & (1 << N)) == 0 to BT(X, N).
10568   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10569   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10570   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10571       Op1.getOpcode() == ISD::Constant &&
10572       cast<ConstantSDNode>(Op1)->isNullValue() &&
10573       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10574     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10575     if (NewSetCC.getNode())
10576       return NewSetCC;
10577   }
10578
10579   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10580   // these.
10581   if (Op1.getOpcode() == ISD::Constant &&
10582       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10583        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10584       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10585
10586     // If the input is a setcc, then reuse the input setcc or use a new one with
10587     // the inverted condition.
10588     if (Op0.getOpcode() == X86ISD::SETCC) {
10589       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10590       bool Invert = (CC == ISD::SETNE) ^
10591         cast<ConstantSDNode>(Op1)->isNullValue();
10592       if (!Invert)
10593         return Op0;
10594
10595       CCode = X86::GetOppositeBranchCondition(CCode);
10596       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10597                                   DAG.getConstant(CCode, MVT::i8),
10598                                   Op0.getOperand(1));
10599       if (VT == MVT::i1)
10600         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10601       return SetCC;
10602     }
10603   }
10604   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10605       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10606       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10607
10608     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10609     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10610   }
10611
10612   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10613   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10614   if (X86CC == X86::COND_INVALID)
10615     return SDValue();
10616
10617   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10618   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10619   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10620                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10621   if (VT == MVT::i1)
10622     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10623   return SetCC;
10624 }
10625
10626 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10627 static bool isX86LogicalCmp(SDValue Op) {
10628   unsigned Opc = Op.getNode()->getOpcode();
10629   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10630       Opc == X86ISD::SAHF)
10631     return true;
10632   if (Op.getResNo() == 1 &&
10633       (Opc == X86ISD::ADD ||
10634        Opc == X86ISD::SUB ||
10635        Opc == X86ISD::ADC ||
10636        Opc == X86ISD::SBB ||
10637        Opc == X86ISD::SMUL ||
10638        Opc == X86ISD::UMUL ||
10639        Opc == X86ISD::INC ||
10640        Opc == X86ISD::DEC ||
10641        Opc == X86ISD::OR ||
10642        Opc == X86ISD::XOR ||
10643        Opc == X86ISD::AND))
10644     return true;
10645
10646   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10647     return true;
10648
10649   return false;
10650 }
10651
10652 static bool isZero(SDValue V) {
10653   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10654   return C && C->isNullValue();
10655 }
10656
10657 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10658   if (V.getOpcode() != ISD::TRUNCATE)
10659     return false;
10660
10661   SDValue VOp0 = V.getOperand(0);
10662   unsigned InBits = VOp0.getValueSizeInBits();
10663   unsigned Bits = V.getValueSizeInBits();
10664   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10665 }
10666
10667 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10668   bool addTest = true;
10669   SDValue Cond  = Op.getOperand(0);
10670   SDValue Op1 = Op.getOperand(1);
10671   SDValue Op2 = Op.getOperand(2);
10672   SDLoc DL(Op);
10673   EVT VT = Op1.getValueType();
10674   SDValue CC;
10675
10676   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10677   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10678   // sequence later on.
10679   if (Cond.getOpcode() == ISD::SETCC &&
10680       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10681        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10682       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10683     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10684     int SSECC = translateX86FSETCC(
10685         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10686
10687     if (SSECC != 8) {
10688       if (Subtarget->hasAVX512()) {
10689         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10690                                   DAG.getConstant(SSECC, MVT::i8));
10691         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10692       }
10693       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10694                                 DAG.getConstant(SSECC, MVT::i8));
10695       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10696       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10697       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10698     }
10699   }
10700
10701   if (Cond.getOpcode() == ISD::SETCC) {
10702     SDValue NewCond = LowerSETCC(Cond, DAG);
10703     if (NewCond.getNode())
10704       Cond = NewCond;
10705   }
10706
10707   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10708   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10709   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10710   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10711   if (Cond.getOpcode() == X86ISD::SETCC &&
10712       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10713       isZero(Cond.getOperand(1).getOperand(1))) {
10714     SDValue Cmp = Cond.getOperand(1);
10715
10716     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10717
10718     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10719         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10720       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10721
10722       SDValue CmpOp0 = Cmp.getOperand(0);
10723       // Apply further optimizations for special cases
10724       // (select (x != 0), -1, 0) -> neg & sbb
10725       // (select (x == 0), 0, -1) -> neg & sbb
10726       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10727         if (YC->isNullValue() &&
10728             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10729           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10730           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10731                                     DAG.getConstant(0, CmpOp0.getValueType()),
10732                                     CmpOp0);
10733           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10734                                     DAG.getConstant(X86::COND_B, MVT::i8),
10735                                     SDValue(Neg.getNode(), 1));
10736           return Res;
10737         }
10738
10739       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10740                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10741       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10742
10743       SDValue Res =   // Res = 0 or -1.
10744         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10745                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10746
10747       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10748         Res = DAG.getNOT(DL, Res, Res.getValueType());
10749
10750       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10751       if (!N2C || !N2C->isNullValue())
10752         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10753       return Res;
10754     }
10755   }
10756
10757   // Look past (and (setcc_carry (cmp ...)), 1).
10758   if (Cond.getOpcode() == ISD::AND &&
10759       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10760     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10761     if (C && C->getAPIntValue() == 1)
10762       Cond = Cond.getOperand(0);
10763   }
10764
10765   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10766   // setting operand in place of the X86ISD::SETCC.
10767   unsigned CondOpcode = Cond.getOpcode();
10768   if (CondOpcode == X86ISD::SETCC ||
10769       CondOpcode == X86ISD::SETCC_CARRY) {
10770     CC = Cond.getOperand(0);
10771
10772     SDValue Cmp = Cond.getOperand(1);
10773     unsigned Opc = Cmp.getOpcode();
10774     MVT VT = Op.getSimpleValueType();
10775
10776     bool IllegalFPCMov = false;
10777     if (VT.isFloatingPoint() && !VT.isVector() &&
10778         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10779       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10780
10781     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10782         Opc == X86ISD::BT) { // FIXME
10783       Cond = Cmp;
10784       addTest = false;
10785     }
10786   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10787              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10788              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10789               Cond.getOperand(0).getValueType() != MVT::i8)) {
10790     SDValue LHS = Cond.getOperand(0);
10791     SDValue RHS = Cond.getOperand(1);
10792     unsigned X86Opcode;
10793     unsigned X86Cond;
10794     SDVTList VTs;
10795     switch (CondOpcode) {
10796     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10797     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10798     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10799     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10800     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10801     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10802     default: llvm_unreachable("unexpected overflowing operator");
10803     }
10804     if (CondOpcode == ISD::UMULO)
10805       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10806                           MVT::i32);
10807     else
10808       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10809
10810     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10811
10812     if (CondOpcode == ISD::UMULO)
10813       Cond = X86Op.getValue(2);
10814     else
10815       Cond = X86Op.getValue(1);
10816
10817     CC = DAG.getConstant(X86Cond, MVT::i8);
10818     addTest = false;
10819   }
10820
10821   if (addTest) {
10822     // Look pass the truncate if the high bits are known zero.
10823     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10824         Cond = Cond.getOperand(0);
10825
10826     // We know the result of AND is compared against zero. Try to match
10827     // it to BT.
10828     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10829       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10830       if (NewSetCC.getNode()) {
10831         CC = NewSetCC.getOperand(0);
10832         Cond = NewSetCC.getOperand(1);
10833         addTest = false;
10834       }
10835     }
10836   }
10837
10838   if (addTest) {
10839     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10840     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10841   }
10842
10843   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10844   // a <  b ?  0 : -1 -> RES = setcc_carry
10845   // a >= b ? -1 :  0 -> RES = setcc_carry
10846   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10847   if (Cond.getOpcode() == X86ISD::SUB) {
10848     Cond = ConvertCmpIfNecessary(Cond, DAG);
10849     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10850
10851     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10852         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10853       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10854                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10855       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10856         return DAG.getNOT(DL, Res, Res.getValueType());
10857       return Res;
10858     }
10859   }
10860
10861   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10862   // widen the cmov and push the truncate through. This avoids introducing a new
10863   // branch during isel and doesn't add any extensions.
10864   if (Op.getValueType() == MVT::i8 &&
10865       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10866     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10867     if (T1.getValueType() == T2.getValueType() &&
10868         // Blacklist CopyFromReg to avoid partial register stalls.
10869         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10870       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10871       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10872       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10873     }
10874   }
10875
10876   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10877   // condition is true.
10878   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10879   SDValue Ops[] = { Op2, Op1, CC, Cond };
10880   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10881 }
10882
10883 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10884   MVT VT = Op->getSimpleValueType(0);
10885   SDValue In = Op->getOperand(0);
10886   MVT InVT = In.getSimpleValueType();
10887   SDLoc dl(Op);
10888
10889   unsigned int NumElts = VT.getVectorNumElements();
10890   if (NumElts != 8 && NumElts != 16)
10891     return SDValue();
10892
10893   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10894     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10895
10896   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10897   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10898
10899   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10900   Constant *C = ConstantInt::get(*DAG.getContext(),
10901     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10902
10903   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10904   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10905   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10906                           MachinePointerInfo::getConstantPool(),
10907                           false, false, false, Alignment);
10908   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10909   if (VT.is512BitVector())
10910     return Brcst;
10911   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10912 }
10913
10914 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10915                                 SelectionDAG &DAG) {
10916   MVT VT = Op->getSimpleValueType(0);
10917   SDValue In = Op->getOperand(0);
10918   MVT InVT = In.getSimpleValueType();
10919   SDLoc dl(Op);
10920
10921   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10922     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10923
10924   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10925       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10926       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10927     return SDValue();
10928
10929   if (Subtarget->hasInt256())
10930     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10931
10932   // Optimize vectors in AVX mode
10933   // Sign extend  v8i16 to v8i32 and
10934   //              v4i32 to v4i64
10935   //
10936   // Divide input vector into two parts
10937   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10938   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10939   // concat the vectors to original VT
10940
10941   unsigned NumElems = InVT.getVectorNumElements();
10942   SDValue Undef = DAG.getUNDEF(InVT);
10943
10944   SmallVector<int,8> ShufMask1(NumElems, -1);
10945   for (unsigned i = 0; i != NumElems/2; ++i)
10946     ShufMask1[i] = i;
10947
10948   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10949
10950   SmallVector<int,8> ShufMask2(NumElems, -1);
10951   for (unsigned i = 0; i != NumElems/2; ++i)
10952     ShufMask2[i] = i + NumElems/2;
10953
10954   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10955
10956   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10957                                 VT.getVectorNumElements()/2);
10958
10959   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10960   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10961
10962   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10963 }
10964
10965 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10966 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10967 // from the AND / OR.
10968 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10969   Opc = Op.getOpcode();
10970   if (Opc != ISD::OR && Opc != ISD::AND)
10971     return false;
10972   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10973           Op.getOperand(0).hasOneUse() &&
10974           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10975           Op.getOperand(1).hasOneUse());
10976 }
10977
10978 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10979 // 1 and that the SETCC node has a single use.
10980 static bool isXor1OfSetCC(SDValue Op) {
10981   if (Op.getOpcode() != ISD::XOR)
10982     return false;
10983   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10984   if (N1C && N1C->getAPIntValue() == 1) {
10985     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10986       Op.getOperand(0).hasOneUse();
10987   }
10988   return false;
10989 }
10990
10991 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10992   bool addTest = true;
10993   SDValue Chain = Op.getOperand(0);
10994   SDValue Cond  = Op.getOperand(1);
10995   SDValue Dest  = Op.getOperand(2);
10996   SDLoc dl(Op);
10997   SDValue CC;
10998   bool Inverted = false;
10999
11000   if (Cond.getOpcode() == ISD::SETCC) {
11001     // Check for setcc([su]{add,sub,mul}o == 0).
11002     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11003         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11004         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11005         Cond.getOperand(0).getResNo() == 1 &&
11006         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11007          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11008          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11009          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11010          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11011          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11012       Inverted = true;
11013       Cond = Cond.getOperand(0);
11014     } else {
11015       SDValue NewCond = LowerSETCC(Cond, DAG);
11016       if (NewCond.getNode())
11017         Cond = NewCond;
11018     }
11019   }
11020 #if 0
11021   // FIXME: LowerXALUO doesn't handle these!!
11022   else if (Cond.getOpcode() == X86ISD::ADD  ||
11023            Cond.getOpcode() == X86ISD::SUB  ||
11024            Cond.getOpcode() == X86ISD::SMUL ||
11025            Cond.getOpcode() == X86ISD::UMUL)
11026     Cond = LowerXALUO(Cond, DAG);
11027 #endif
11028
11029   // Look pass (and (setcc_carry (cmp ...)), 1).
11030   if (Cond.getOpcode() == ISD::AND &&
11031       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11032     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11033     if (C && C->getAPIntValue() == 1)
11034       Cond = Cond.getOperand(0);
11035   }
11036
11037   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11038   // setting operand in place of the X86ISD::SETCC.
11039   unsigned CondOpcode = Cond.getOpcode();
11040   if (CondOpcode == X86ISD::SETCC ||
11041       CondOpcode == X86ISD::SETCC_CARRY) {
11042     CC = Cond.getOperand(0);
11043
11044     SDValue Cmp = Cond.getOperand(1);
11045     unsigned Opc = Cmp.getOpcode();
11046     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11047     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11048       Cond = Cmp;
11049       addTest = false;
11050     } else {
11051       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11052       default: break;
11053       case X86::COND_O:
11054       case X86::COND_B:
11055         // These can only come from an arithmetic instruction with overflow,
11056         // e.g. SADDO, UADDO.
11057         Cond = Cond.getNode()->getOperand(1);
11058         addTest = false;
11059         break;
11060       }
11061     }
11062   }
11063   CondOpcode = Cond.getOpcode();
11064   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11065       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11066       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11067        Cond.getOperand(0).getValueType() != MVT::i8)) {
11068     SDValue LHS = Cond.getOperand(0);
11069     SDValue RHS = Cond.getOperand(1);
11070     unsigned X86Opcode;
11071     unsigned X86Cond;
11072     SDVTList VTs;
11073     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11074     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11075     // X86ISD::INC).
11076     switch (CondOpcode) {
11077     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11078     case ISD::SADDO:
11079       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11080         if (C->isOne()) {
11081           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11082           break;
11083         }
11084       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11085     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11086     case ISD::SSUBO:
11087       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11088         if (C->isOne()) {
11089           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11090           break;
11091         }
11092       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11093     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11094     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11095     default: llvm_unreachable("unexpected overflowing operator");
11096     }
11097     if (Inverted)
11098       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11099     if (CondOpcode == ISD::UMULO)
11100       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11101                           MVT::i32);
11102     else
11103       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11104
11105     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11106
11107     if (CondOpcode == ISD::UMULO)
11108       Cond = X86Op.getValue(2);
11109     else
11110       Cond = X86Op.getValue(1);
11111
11112     CC = DAG.getConstant(X86Cond, MVT::i8);
11113     addTest = false;
11114   } else {
11115     unsigned CondOpc;
11116     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11117       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11118       if (CondOpc == ISD::OR) {
11119         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11120         // two branches instead of an explicit OR instruction with a
11121         // separate test.
11122         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11123             isX86LogicalCmp(Cmp)) {
11124           CC = Cond.getOperand(0).getOperand(0);
11125           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11126                               Chain, Dest, CC, Cmp);
11127           CC = Cond.getOperand(1).getOperand(0);
11128           Cond = Cmp;
11129           addTest = false;
11130         }
11131       } else { // ISD::AND
11132         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11133         // two branches instead of an explicit AND instruction with a
11134         // separate test. However, we only do this if this block doesn't
11135         // have a fall-through edge, because this requires an explicit
11136         // jmp when the condition is false.
11137         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11138             isX86LogicalCmp(Cmp) &&
11139             Op.getNode()->hasOneUse()) {
11140           X86::CondCode CCode =
11141             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11142           CCode = X86::GetOppositeBranchCondition(CCode);
11143           CC = DAG.getConstant(CCode, MVT::i8);
11144           SDNode *User = *Op.getNode()->use_begin();
11145           // Look for an unconditional branch following this conditional branch.
11146           // We need this because we need to reverse the successors in order
11147           // to implement FCMP_OEQ.
11148           if (User->getOpcode() == ISD::BR) {
11149             SDValue FalseBB = User->getOperand(1);
11150             SDNode *NewBR =
11151               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11152             assert(NewBR == User);
11153             (void)NewBR;
11154             Dest = FalseBB;
11155
11156             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11157                                 Chain, Dest, CC, Cmp);
11158             X86::CondCode CCode =
11159               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11160             CCode = X86::GetOppositeBranchCondition(CCode);
11161             CC = DAG.getConstant(CCode, MVT::i8);
11162             Cond = Cmp;
11163             addTest = false;
11164           }
11165         }
11166       }
11167     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11168       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11169       // It should be transformed during dag combiner except when the condition
11170       // is set by a arithmetics with overflow node.
11171       X86::CondCode CCode =
11172         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11173       CCode = X86::GetOppositeBranchCondition(CCode);
11174       CC = DAG.getConstant(CCode, MVT::i8);
11175       Cond = Cond.getOperand(0).getOperand(1);
11176       addTest = false;
11177     } else if (Cond.getOpcode() == ISD::SETCC &&
11178                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11179       // For FCMP_OEQ, we can emit
11180       // two branches instead of an explicit AND instruction with a
11181       // separate test. However, we only do this if this block doesn't
11182       // have a fall-through edge, because this requires an explicit
11183       // jmp when the condition is false.
11184       if (Op.getNode()->hasOneUse()) {
11185         SDNode *User = *Op.getNode()->use_begin();
11186         // Look for an unconditional branch following this conditional branch.
11187         // We need this because we need to reverse the successors in order
11188         // to implement FCMP_OEQ.
11189         if (User->getOpcode() == ISD::BR) {
11190           SDValue FalseBB = User->getOperand(1);
11191           SDNode *NewBR =
11192             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11193           assert(NewBR == User);
11194           (void)NewBR;
11195           Dest = FalseBB;
11196
11197           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11198                                     Cond.getOperand(0), Cond.getOperand(1));
11199           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11200           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11201           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11202                               Chain, Dest, CC, Cmp);
11203           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11204           Cond = Cmp;
11205           addTest = false;
11206         }
11207       }
11208     } else if (Cond.getOpcode() == ISD::SETCC &&
11209                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11210       // For FCMP_UNE, we can emit
11211       // two branches instead of an explicit AND instruction with a
11212       // separate test. However, we only do this if this block doesn't
11213       // have a fall-through edge, because this requires an explicit
11214       // jmp when the condition is false.
11215       if (Op.getNode()->hasOneUse()) {
11216         SDNode *User = *Op.getNode()->use_begin();
11217         // Look for an unconditional branch following this conditional branch.
11218         // We need this because we need to reverse the successors in order
11219         // to implement FCMP_UNE.
11220         if (User->getOpcode() == ISD::BR) {
11221           SDValue FalseBB = User->getOperand(1);
11222           SDNode *NewBR =
11223             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11224           assert(NewBR == User);
11225           (void)NewBR;
11226
11227           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11228                                     Cond.getOperand(0), Cond.getOperand(1));
11229           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11230           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11231           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11232                               Chain, Dest, CC, Cmp);
11233           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11234           Cond = Cmp;
11235           addTest = false;
11236           Dest = FalseBB;
11237         }
11238       }
11239     }
11240   }
11241
11242   if (addTest) {
11243     // Look pass the truncate if the high bits are known zero.
11244     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11245         Cond = Cond.getOperand(0);
11246
11247     // We know the result of AND is compared against zero. Try to match
11248     // it to BT.
11249     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11250       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11251       if (NewSetCC.getNode()) {
11252         CC = NewSetCC.getOperand(0);
11253         Cond = NewSetCC.getOperand(1);
11254         addTest = false;
11255       }
11256     }
11257   }
11258
11259   if (addTest) {
11260     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11261     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11262   }
11263   Cond = ConvertCmpIfNecessary(Cond, DAG);
11264   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11265                      Chain, Dest, CC, Cond);
11266 }
11267
11268 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11269 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11270 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11271 // that the guard pages used by the OS virtual memory manager are allocated in
11272 // correct sequence.
11273 SDValue
11274 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11275                                            SelectionDAG &DAG) const {
11276   MachineFunction &MF = DAG.getMachineFunction();
11277   bool SplitStack = MF.shouldSplitStack();
11278   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11279                SplitStack;
11280   SDLoc dl(Op);
11281
11282   if (!Lower) {
11283     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11284     SDNode* Node = Op.getNode();
11285
11286     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11287     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11288         " not tell us which reg is the stack pointer!");
11289     EVT VT = Node->getValueType(0);
11290     SDValue Tmp1 = SDValue(Node, 0);
11291     SDValue Tmp2 = SDValue(Node, 1);
11292     SDValue Tmp3 = Node->getOperand(2);
11293     SDValue Chain = Tmp1.getOperand(0);
11294
11295     // Chain the dynamic stack allocation so that it doesn't modify the stack
11296     // pointer when other instructions are using the stack.
11297     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11298         SDLoc(Node));
11299
11300     SDValue Size = Tmp2.getOperand(1);
11301     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11302     Chain = SP.getValue(1);
11303     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11304     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11305     unsigned StackAlign = TFI.getStackAlignment();
11306     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11307     if (Align > StackAlign)
11308       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11309           DAG.getConstant(-(uint64_t)Align, VT));
11310     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11311
11312     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11313         DAG.getIntPtrConstant(0, true), SDValue(),
11314         SDLoc(Node));
11315
11316     SDValue Ops[2] = { Tmp1, Tmp2 };
11317     return DAG.getMergeValues(Ops, dl);
11318   }
11319
11320   // Get the inputs.
11321   SDValue Chain = Op.getOperand(0);
11322   SDValue Size  = Op.getOperand(1);
11323   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11324   EVT VT = Op.getNode()->getValueType(0);
11325
11326   bool Is64Bit = Subtarget->is64Bit();
11327   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11328
11329   if (SplitStack) {
11330     MachineRegisterInfo &MRI = MF.getRegInfo();
11331
11332     if (Is64Bit) {
11333       // The 64 bit implementation of segmented stacks needs to clobber both r10
11334       // r11. This makes it impossible to use it along with nested parameters.
11335       const Function *F = MF.getFunction();
11336
11337       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11338            I != E; ++I)
11339         if (I->hasNestAttr())
11340           report_fatal_error("Cannot use segmented stacks with functions that "
11341                              "have nested arguments.");
11342     }
11343
11344     const TargetRegisterClass *AddrRegClass =
11345       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11346     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11347     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11348     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11349                                 DAG.getRegister(Vreg, SPTy));
11350     SDValue Ops1[2] = { Value, Chain };
11351     return DAG.getMergeValues(Ops1, dl);
11352   } else {
11353     SDValue Flag;
11354     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11355
11356     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11357     Flag = Chain.getValue(1);
11358     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11359
11360     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11361
11362     const X86RegisterInfo *RegInfo =
11363       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11364     unsigned SPReg = RegInfo->getStackRegister();
11365     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11366     Chain = SP.getValue(1);
11367
11368     if (Align) {
11369       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11370                        DAG.getConstant(-(uint64_t)Align, VT));
11371       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11372     }
11373
11374     SDValue Ops1[2] = { SP, Chain };
11375     return DAG.getMergeValues(Ops1, dl);
11376   }
11377 }
11378
11379 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11380   MachineFunction &MF = DAG.getMachineFunction();
11381   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11382
11383   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11384   SDLoc DL(Op);
11385
11386   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11387     // vastart just stores the address of the VarArgsFrameIndex slot into the
11388     // memory location argument.
11389     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11390                                    getPointerTy());
11391     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11392                         MachinePointerInfo(SV), false, false, 0);
11393   }
11394
11395   // __va_list_tag:
11396   //   gp_offset         (0 - 6 * 8)
11397   //   fp_offset         (48 - 48 + 8 * 16)
11398   //   overflow_arg_area (point to parameters coming in memory).
11399   //   reg_save_area
11400   SmallVector<SDValue, 8> MemOps;
11401   SDValue FIN = Op.getOperand(1);
11402   // Store gp_offset
11403   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11404                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11405                                                MVT::i32),
11406                                FIN, MachinePointerInfo(SV), false, false, 0);
11407   MemOps.push_back(Store);
11408
11409   // Store fp_offset
11410   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11411                     FIN, DAG.getIntPtrConstant(4));
11412   Store = DAG.getStore(Op.getOperand(0), DL,
11413                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11414                                        MVT::i32),
11415                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11416   MemOps.push_back(Store);
11417
11418   // Store ptr to overflow_arg_area
11419   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11420                     FIN, DAG.getIntPtrConstant(4));
11421   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11422                                     getPointerTy());
11423   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11424                        MachinePointerInfo(SV, 8),
11425                        false, false, 0);
11426   MemOps.push_back(Store);
11427
11428   // Store ptr to reg_save_area.
11429   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11430                     FIN, DAG.getIntPtrConstant(8));
11431   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11432                                     getPointerTy());
11433   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11434                        MachinePointerInfo(SV, 16), false, false, 0);
11435   MemOps.push_back(Store);
11436   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11437 }
11438
11439 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11440   assert(Subtarget->is64Bit() &&
11441          "LowerVAARG only handles 64-bit va_arg!");
11442   assert((Subtarget->isTargetLinux() ||
11443           Subtarget->isTargetDarwin()) &&
11444           "Unhandled target in LowerVAARG");
11445   assert(Op.getNode()->getNumOperands() == 4);
11446   SDValue Chain = Op.getOperand(0);
11447   SDValue SrcPtr = Op.getOperand(1);
11448   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11449   unsigned Align = Op.getConstantOperandVal(3);
11450   SDLoc dl(Op);
11451
11452   EVT ArgVT = Op.getNode()->getValueType(0);
11453   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11454   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11455   uint8_t ArgMode;
11456
11457   // Decide which area this value should be read from.
11458   // TODO: Implement the AMD64 ABI in its entirety. This simple
11459   // selection mechanism works only for the basic types.
11460   if (ArgVT == MVT::f80) {
11461     llvm_unreachable("va_arg for f80 not yet implemented");
11462   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11463     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11464   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11465     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11466   } else {
11467     llvm_unreachable("Unhandled argument type in LowerVAARG");
11468   }
11469
11470   if (ArgMode == 2) {
11471     // Sanity Check: Make sure using fp_offset makes sense.
11472     assert(!getTargetMachine().Options.UseSoftFloat &&
11473            !(DAG.getMachineFunction()
11474                 .getFunction()->getAttributes()
11475                 .hasAttribute(AttributeSet::FunctionIndex,
11476                               Attribute::NoImplicitFloat)) &&
11477            Subtarget->hasSSE1());
11478   }
11479
11480   // Insert VAARG_64 node into the DAG
11481   // VAARG_64 returns two values: Variable Argument Address, Chain
11482   SmallVector<SDValue, 11> InstOps;
11483   InstOps.push_back(Chain);
11484   InstOps.push_back(SrcPtr);
11485   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11486   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11487   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11488   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11489   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11490                                           VTs, InstOps, MVT::i64,
11491                                           MachinePointerInfo(SV),
11492                                           /*Align=*/0,
11493                                           /*Volatile=*/false,
11494                                           /*ReadMem=*/true,
11495                                           /*WriteMem=*/true);
11496   Chain = VAARG.getValue(1);
11497
11498   // Load the next argument and return it
11499   return DAG.getLoad(ArgVT, dl,
11500                      Chain,
11501                      VAARG,
11502                      MachinePointerInfo(),
11503                      false, false, false, 0);
11504 }
11505
11506 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11507                            SelectionDAG &DAG) {
11508   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11509   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11510   SDValue Chain = Op.getOperand(0);
11511   SDValue DstPtr = Op.getOperand(1);
11512   SDValue SrcPtr = Op.getOperand(2);
11513   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11514   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11515   SDLoc DL(Op);
11516
11517   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11518                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11519                        false,
11520                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11521 }
11522
11523 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11524 // amount is a constant. Takes immediate version of shift as input.
11525 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11526                                           SDValue SrcOp, uint64_t ShiftAmt,
11527                                           SelectionDAG &DAG) {
11528   MVT ElementType = VT.getVectorElementType();
11529
11530   // Check for ShiftAmt >= element width
11531   if (ShiftAmt >= ElementType.getSizeInBits()) {
11532     if (Opc == X86ISD::VSRAI)
11533       ShiftAmt = ElementType.getSizeInBits() - 1;
11534     else
11535       return DAG.getConstant(0, VT);
11536   }
11537
11538   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11539          && "Unknown target vector shift-by-constant node");
11540
11541   // Fold this packed vector shift into a build vector if SrcOp is a
11542   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11543   if (VT == SrcOp.getSimpleValueType() &&
11544       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11545     SmallVector<SDValue, 8> Elts;
11546     unsigned NumElts = SrcOp->getNumOperands();
11547     ConstantSDNode *ND;
11548
11549     switch(Opc) {
11550     default: llvm_unreachable(nullptr);
11551     case X86ISD::VSHLI:
11552       for (unsigned i=0; i!=NumElts; ++i) {
11553         SDValue CurrentOp = SrcOp->getOperand(i);
11554         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11555           Elts.push_back(CurrentOp);
11556           continue;
11557         }
11558         ND = cast<ConstantSDNode>(CurrentOp);
11559         const APInt &C = ND->getAPIntValue();
11560         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11561       }
11562       break;
11563     case X86ISD::VSRLI:
11564       for (unsigned i=0; i!=NumElts; ++i) {
11565         SDValue CurrentOp = SrcOp->getOperand(i);
11566         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11567           Elts.push_back(CurrentOp);
11568           continue;
11569         }
11570         ND = cast<ConstantSDNode>(CurrentOp);
11571         const APInt &C = ND->getAPIntValue();
11572         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11573       }
11574       break;
11575     case X86ISD::VSRAI:
11576       for (unsigned i=0; i!=NumElts; ++i) {
11577         SDValue CurrentOp = SrcOp->getOperand(i);
11578         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11579           Elts.push_back(CurrentOp);
11580           continue;
11581         }
11582         ND = cast<ConstantSDNode>(CurrentOp);
11583         const APInt &C = ND->getAPIntValue();
11584         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11585       }
11586       break;
11587     }
11588
11589     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11590   }
11591
11592   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11593 }
11594
11595 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11596 // may or may not be a constant. Takes immediate version of shift as input.
11597 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11598                                    SDValue SrcOp, SDValue ShAmt,
11599                                    SelectionDAG &DAG) {
11600   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11601
11602   // Catch shift-by-constant.
11603   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11604     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11605                                       CShAmt->getZExtValue(), DAG);
11606
11607   // Change opcode to non-immediate version
11608   switch (Opc) {
11609     default: llvm_unreachable("Unknown target vector shift node");
11610     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11611     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11612     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11613   }
11614
11615   // Need to build a vector containing shift amount
11616   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11617   SDValue ShOps[4];
11618   ShOps[0] = ShAmt;
11619   ShOps[1] = DAG.getConstant(0, MVT::i32);
11620   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11621   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11622
11623   // The return type has to be a 128-bit type with the same element
11624   // type as the input type.
11625   MVT EltVT = VT.getVectorElementType();
11626   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11627
11628   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11629   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11630 }
11631
11632 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11633   SDLoc dl(Op);
11634   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11635   switch (IntNo) {
11636   default: return SDValue();    // Don't custom lower most intrinsics.
11637   // Comparison intrinsics.
11638   case Intrinsic::x86_sse_comieq_ss:
11639   case Intrinsic::x86_sse_comilt_ss:
11640   case Intrinsic::x86_sse_comile_ss:
11641   case Intrinsic::x86_sse_comigt_ss:
11642   case Intrinsic::x86_sse_comige_ss:
11643   case Intrinsic::x86_sse_comineq_ss:
11644   case Intrinsic::x86_sse_ucomieq_ss:
11645   case Intrinsic::x86_sse_ucomilt_ss:
11646   case Intrinsic::x86_sse_ucomile_ss:
11647   case Intrinsic::x86_sse_ucomigt_ss:
11648   case Intrinsic::x86_sse_ucomige_ss:
11649   case Intrinsic::x86_sse_ucomineq_ss:
11650   case Intrinsic::x86_sse2_comieq_sd:
11651   case Intrinsic::x86_sse2_comilt_sd:
11652   case Intrinsic::x86_sse2_comile_sd:
11653   case Intrinsic::x86_sse2_comigt_sd:
11654   case Intrinsic::x86_sse2_comige_sd:
11655   case Intrinsic::x86_sse2_comineq_sd:
11656   case Intrinsic::x86_sse2_ucomieq_sd:
11657   case Intrinsic::x86_sse2_ucomilt_sd:
11658   case Intrinsic::x86_sse2_ucomile_sd:
11659   case Intrinsic::x86_sse2_ucomigt_sd:
11660   case Intrinsic::x86_sse2_ucomige_sd:
11661   case Intrinsic::x86_sse2_ucomineq_sd: {
11662     unsigned Opc;
11663     ISD::CondCode CC;
11664     switch (IntNo) {
11665     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11666     case Intrinsic::x86_sse_comieq_ss:
11667     case Intrinsic::x86_sse2_comieq_sd:
11668       Opc = X86ISD::COMI;
11669       CC = ISD::SETEQ;
11670       break;
11671     case Intrinsic::x86_sse_comilt_ss:
11672     case Intrinsic::x86_sse2_comilt_sd:
11673       Opc = X86ISD::COMI;
11674       CC = ISD::SETLT;
11675       break;
11676     case Intrinsic::x86_sse_comile_ss:
11677     case Intrinsic::x86_sse2_comile_sd:
11678       Opc = X86ISD::COMI;
11679       CC = ISD::SETLE;
11680       break;
11681     case Intrinsic::x86_sse_comigt_ss:
11682     case Intrinsic::x86_sse2_comigt_sd:
11683       Opc = X86ISD::COMI;
11684       CC = ISD::SETGT;
11685       break;
11686     case Intrinsic::x86_sse_comige_ss:
11687     case Intrinsic::x86_sse2_comige_sd:
11688       Opc = X86ISD::COMI;
11689       CC = ISD::SETGE;
11690       break;
11691     case Intrinsic::x86_sse_comineq_ss:
11692     case Intrinsic::x86_sse2_comineq_sd:
11693       Opc = X86ISD::COMI;
11694       CC = ISD::SETNE;
11695       break;
11696     case Intrinsic::x86_sse_ucomieq_ss:
11697     case Intrinsic::x86_sse2_ucomieq_sd:
11698       Opc = X86ISD::UCOMI;
11699       CC = ISD::SETEQ;
11700       break;
11701     case Intrinsic::x86_sse_ucomilt_ss:
11702     case Intrinsic::x86_sse2_ucomilt_sd:
11703       Opc = X86ISD::UCOMI;
11704       CC = ISD::SETLT;
11705       break;
11706     case Intrinsic::x86_sse_ucomile_ss:
11707     case Intrinsic::x86_sse2_ucomile_sd:
11708       Opc = X86ISD::UCOMI;
11709       CC = ISD::SETLE;
11710       break;
11711     case Intrinsic::x86_sse_ucomigt_ss:
11712     case Intrinsic::x86_sse2_ucomigt_sd:
11713       Opc = X86ISD::UCOMI;
11714       CC = ISD::SETGT;
11715       break;
11716     case Intrinsic::x86_sse_ucomige_ss:
11717     case Intrinsic::x86_sse2_ucomige_sd:
11718       Opc = X86ISD::UCOMI;
11719       CC = ISD::SETGE;
11720       break;
11721     case Intrinsic::x86_sse_ucomineq_ss:
11722     case Intrinsic::x86_sse2_ucomineq_sd:
11723       Opc = X86ISD::UCOMI;
11724       CC = ISD::SETNE;
11725       break;
11726     }
11727
11728     SDValue LHS = Op.getOperand(1);
11729     SDValue RHS = Op.getOperand(2);
11730     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11731     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11732     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11733     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11734                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11735     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11736   }
11737
11738   // Arithmetic intrinsics.
11739   case Intrinsic::x86_sse2_pmulu_dq:
11740   case Intrinsic::x86_avx2_pmulu_dq:
11741     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11742                        Op.getOperand(1), Op.getOperand(2));
11743
11744   case Intrinsic::x86_sse41_pmuldq:
11745   case Intrinsic::x86_avx2_pmul_dq:
11746     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11747                        Op.getOperand(1), Op.getOperand(2));
11748
11749   case Intrinsic::x86_sse2_pmulhu_w:
11750   case Intrinsic::x86_avx2_pmulhu_w:
11751     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11752                        Op.getOperand(1), Op.getOperand(2));
11753
11754   case Intrinsic::x86_sse2_pmulh_w:
11755   case Intrinsic::x86_avx2_pmulh_w:
11756     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11757                        Op.getOperand(1), Op.getOperand(2));
11758
11759   // SSE2/AVX2 sub with unsigned saturation intrinsics
11760   case Intrinsic::x86_sse2_psubus_b:
11761   case Intrinsic::x86_sse2_psubus_w:
11762   case Intrinsic::x86_avx2_psubus_b:
11763   case Intrinsic::x86_avx2_psubus_w:
11764     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11765                        Op.getOperand(1), Op.getOperand(2));
11766
11767   // SSE3/AVX horizontal add/sub intrinsics
11768   case Intrinsic::x86_sse3_hadd_ps:
11769   case Intrinsic::x86_sse3_hadd_pd:
11770   case Intrinsic::x86_avx_hadd_ps_256:
11771   case Intrinsic::x86_avx_hadd_pd_256:
11772   case Intrinsic::x86_sse3_hsub_ps:
11773   case Intrinsic::x86_sse3_hsub_pd:
11774   case Intrinsic::x86_avx_hsub_ps_256:
11775   case Intrinsic::x86_avx_hsub_pd_256:
11776   case Intrinsic::x86_ssse3_phadd_w_128:
11777   case Intrinsic::x86_ssse3_phadd_d_128:
11778   case Intrinsic::x86_avx2_phadd_w:
11779   case Intrinsic::x86_avx2_phadd_d:
11780   case Intrinsic::x86_ssse3_phsub_w_128:
11781   case Intrinsic::x86_ssse3_phsub_d_128:
11782   case Intrinsic::x86_avx2_phsub_w:
11783   case Intrinsic::x86_avx2_phsub_d: {
11784     unsigned Opcode;
11785     switch (IntNo) {
11786     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11787     case Intrinsic::x86_sse3_hadd_ps:
11788     case Intrinsic::x86_sse3_hadd_pd:
11789     case Intrinsic::x86_avx_hadd_ps_256:
11790     case Intrinsic::x86_avx_hadd_pd_256:
11791       Opcode = X86ISD::FHADD;
11792       break;
11793     case Intrinsic::x86_sse3_hsub_ps:
11794     case Intrinsic::x86_sse3_hsub_pd:
11795     case Intrinsic::x86_avx_hsub_ps_256:
11796     case Intrinsic::x86_avx_hsub_pd_256:
11797       Opcode = X86ISD::FHSUB;
11798       break;
11799     case Intrinsic::x86_ssse3_phadd_w_128:
11800     case Intrinsic::x86_ssse3_phadd_d_128:
11801     case Intrinsic::x86_avx2_phadd_w:
11802     case Intrinsic::x86_avx2_phadd_d:
11803       Opcode = X86ISD::HADD;
11804       break;
11805     case Intrinsic::x86_ssse3_phsub_w_128:
11806     case Intrinsic::x86_ssse3_phsub_d_128:
11807     case Intrinsic::x86_avx2_phsub_w:
11808     case Intrinsic::x86_avx2_phsub_d:
11809       Opcode = X86ISD::HSUB;
11810       break;
11811     }
11812     return DAG.getNode(Opcode, dl, Op.getValueType(),
11813                        Op.getOperand(1), Op.getOperand(2));
11814   }
11815
11816   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11817   case Intrinsic::x86_sse2_pmaxu_b:
11818   case Intrinsic::x86_sse41_pmaxuw:
11819   case Intrinsic::x86_sse41_pmaxud:
11820   case Intrinsic::x86_avx2_pmaxu_b:
11821   case Intrinsic::x86_avx2_pmaxu_w:
11822   case Intrinsic::x86_avx2_pmaxu_d:
11823   case Intrinsic::x86_sse2_pminu_b:
11824   case Intrinsic::x86_sse41_pminuw:
11825   case Intrinsic::x86_sse41_pminud:
11826   case Intrinsic::x86_avx2_pminu_b:
11827   case Intrinsic::x86_avx2_pminu_w:
11828   case Intrinsic::x86_avx2_pminu_d:
11829   case Intrinsic::x86_sse41_pmaxsb:
11830   case Intrinsic::x86_sse2_pmaxs_w:
11831   case Intrinsic::x86_sse41_pmaxsd:
11832   case Intrinsic::x86_avx2_pmaxs_b:
11833   case Intrinsic::x86_avx2_pmaxs_w:
11834   case Intrinsic::x86_avx2_pmaxs_d:
11835   case Intrinsic::x86_sse41_pminsb:
11836   case Intrinsic::x86_sse2_pmins_w:
11837   case Intrinsic::x86_sse41_pminsd:
11838   case Intrinsic::x86_avx2_pmins_b:
11839   case Intrinsic::x86_avx2_pmins_w:
11840   case Intrinsic::x86_avx2_pmins_d: {
11841     unsigned Opcode;
11842     switch (IntNo) {
11843     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11844     case Intrinsic::x86_sse2_pmaxu_b:
11845     case Intrinsic::x86_sse41_pmaxuw:
11846     case Intrinsic::x86_sse41_pmaxud:
11847     case Intrinsic::x86_avx2_pmaxu_b:
11848     case Intrinsic::x86_avx2_pmaxu_w:
11849     case Intrinsic::x86_avx2_pmaxu_d:
11850       Opcode = X86ISD::UMAX;
11851       break;
11852     case Intrinsic::x86_sse2_pminu_b:
11853     case Intrinsic::x86_sse41_pminuw:
11854     case Intrinsic::x86_sse41_pminud:
11855     case Intrinsic::x86_avx2_pminu_b:
11856     case Intrinsic::x86_avx2_pminu_w:
11857     case Intrinsic::x86_avx2_pminu_d:
11858       Opcode = X86ISD::UMIN;
11859       break;
11860     case Intrinsic::x86_sse41_pmaxsb:
11861     case Intrinsic::x86_sse2_pmaxs_w:
11862     case Intrinsic::x86_sse41_pmaxsd:
11863     case Intrinsic::x86_avx2_pmaxs_b:
11864     case Intrinsic::x86_avx2_pmaxs_w:
11865     case Intrinsic::x86_avx2_pmaxs_d:
11866       Opcode = X86ISD::SMAX;
11867       break;
11868     case Intrinsic::x86_sse41_pminsb:
11869     case Intrinsic::x86_sse2_pmins_w:
11870     case Intrinsic::x86_sse41_pminsd:
11871     case Intrinsic::x86_avx2_pmins_b:
11872     case Intrinsic::x86_avx2_pmins_w:
11873     case Intrinsic::x86_avx2_pmins_d:
11874       Opcode = X86ISD::SMIN;
11875       break;
11876     }
11877     return DAG.getNode(Opcode, dl, Op.getValueType(),
11878                        Op.getOperand(1), Op.getOperand(2));
11879   }
11880
11881   // SSE/SSE2/AVX floating point max/min intrinsics.
11882   case Intrinsic::x86_sse_max_ps:
11883   case Intrinsic::x86_sse2_max_pd:
11884   case Intrinsic::x86_avx_max_ps_256:
11885   case Intrinsic::x86_avx_max_pd_256:
11886   case Intrinsic::x86_sse_min_ps:
11887   case Intrinsic::x86_sse2_min_pd:
11888   case Intrinsic::x86_avx_min_ps_256:
11889   case Intrinsic::x86_avx_min_pd_256: {
11890     unsigned Opcode;
11891     switch (IntNo) {
11892     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11893     case Intrinsic::x86_sse_max_ps:
11894     case Intrinsic::x86_sse2_max_pd:
11895     case Intrinsic::x86_avx_max_ps_256:
11896     case Intrinsic::x86_avx_max_pd_256:
11897       Opcode = X86ISD::FMAX;
11898       break;
11899     case Intrinsic::x86_sse_min_ps:
11900     case Intrinsic::x86_sse2_min_pd:
11901     case Intrinsic::x86_avx_min_ps_256:
11902     case Intrinsic::x86_avx_min_pd_256:
11903       Opcode = X86ISD::FMIN;
11904       break;
11905     }
11906     return DAG.getNode(Opcode, dl, Op.getValueType(),
11907                        Op.getOperand(1), Op.getOperand(2));
11908   }
11909
11910   // AVX2 variable shift intrinsics
11911   case Intrinsic::x86_avx2_psllv_d:
11912   case Intrinsic::x86_avx2_psllv_q:
11913   case Intrinsic::x86_avx2_psllv_d_256:
11914   case Intrinsic::x86_avx2_psllv_q_256:
11915   case Intrinsic::x86_avx2_psrlv_d:
11916   case Intrinsic::x86_avx2_psrlv_q:
11917   case Intrinsic::x86_avx2_psrlv_d_256:
11918   case Intrinsic::x86_avx2_psrlv_q_256:
11919   case Intrinsic::x86_avx2_psrav_d:
11920   case Intrinsic::x86_avx2_psrav_d_256: {
11921     unsigned Opcode;
11922     switch (IntNo) {
11923     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11924     case Intrinsic::x86_avx2_psllv_d:
11925     case Intrinsic::x86_avx2_psllv_q:
11926     case Intrinsic::x86_avx2_psllv_d_256:
11927     case Intrinsic::x86_avx2_psllv_q_256:
11928       Opcode = ISD::SHL;
11929       break;
11930     case Intrinsic::x86_avx2_psrlv_d:
11931     case Intrinsic::x86_avx2_psrlv_q:
11932     case Intrinsic::x86_avx2_psrlv_d_256:
11933     case Intrinsic::x86_avx2_psrlv_q_256:
11934       Opcode = ISD::SRL;
11935       break;
11936     case Intrinsic::x86_avx2_psrav_d:
11937     case Intrinsic::x86_avx2_psrav_d_256:
11938       Opcode = ISD::SRA;
11939       break;
11940     }
11941     return DAG.getNode(Opcode, dl, Op.getValueType(),
11942                        Op.getOperand(1), Op.getOperand(2));
11943   }
11944
11945   case Intrinsic::x86_ssse3_pshuf_b_128:
11946   case Intrinsic::x86_avx2_pshuf_b:
11947     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11948                        Op.getOperand(1), Op.getOperand(2));
11949
11950   case Intrinsic::x86_ssse3_psign_b_128:
11951   case Intrinsic::x86_ssse3_psign_w_128:
11952   case Intrinsic::x86_ssse3_psign_d_128:
11953   case Intrinsic::x86_avx2_psign_b:
11954   case Intrinsic::x86_avx2_psign_w:
11955   case Intrinsic::x86_avx2_psign_d:
11956     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11957                        Op.getOperand(1), Op.getOperand(2));
11958
11959   case Intrinsic::x86_sse41_insertps:
11960     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11961                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11962
11963   case Intrinsic::x86_avx_vperm2f128_ps_256:
11964   case Intrinsic::x86_avx_vperm2f128_pd_256:
11965   case Intrinsic::x86_avx_vperm2f128_si_256:
11966   case Intrinsic::x86_avx2_vperm2i128:
11967     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11968                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11969
11970   case Intrinsic::x86_avx2_permd:
11971   case Intrinsic::x86_avx2_permps:
11972     // Operands intentionally swapped. Mask is last operand to intrinsic,
11973     // but second operand for node/instruction.
11974     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11975                        Op.getOperand(2), Op.getOperand(1));
11976
11977   case Intrinsic::x86_sse_sqrt_ps:
11978   case Intrinsic::x86_sse2_sqrt_pd:
11979   case Intrinsic::x86_avx_sqrt_ps_256:
11980   case Intrinsic::x86_avx_sqrt_pd_256:
11981     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11982
11983   // ptest and testp intrinsics. The intrinsic these come from are designed to
11984   // return an integer value, not just an instruction so lower it to the ptest
11985   // or testp pattern and a setcc for the result.
11986   case Intrinsic::x86_sse41_ptestz:
11987   case Intrinsic::x86_sse41_ptestc:
11988   case Intrinsic::x86_sse41_ptestnzc:
11989   case Intrinsic::x86_avx_ptestz_256:
11990   case Intrinsic::x86_avx_ptestc_256:
11991   case Intrinsic::x86_avx_ptestnzc_256:
11992   case Intrinsic::x86_avx_vtestz_ps:
11993   case Intrinsic::x86_avx_vtestc_ps:
11994   case Intrinsic::x86_avx_vtestnzc_ps:
11995   case Intrinsic::x86_avx_vtestz_pd:
11996   case Intrinsic::x86_avx_vtestc_pd:
11997   case Intrinsic::x86_avx_vtestnzc_pd:
11998   case Intrinsic::x86_avx_vtestz_ps_256:
11999   case Intrinsic::x86_avx_vtestc_ps_256:
12000   case Intrinsic::x86_avx_vtestnzc_ps_256:
12001   case Intrinsic::x86_avx_vtestz_pd_256:
12002   case Intrinsic::x86_avx_vtestc_pd_256:
12003   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12004     bool IsTestPacked = false;
12005     unsigned X86CC;
12006     switch (IntNo) {
12007     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12008     case Intrinsic::x86_avx_vtestz_ps:
12009     case Intrinsic::x86_avx_vtestz_pd:
12010     case Intrinsic::x86_avx_vtestz_ps_256:
12011     case Intrinsic::x86_avx_vtestz_pd_256:
12012       IsTestPacked = true; // Fallthrough
12013     case Intrinsic::x86_sse41_ptestz:
12014     case Intrinsic::x86_avx_ptestz_256:
12015       // ZF = 1
12016       X86CC = X86::COND_E;
12017       break;
12018     case Intrinsic::x86_avx_vtestc_ps:
12019     case Intrinsic::x86_avx_vtestc_pd:
12020     case Intrinsic::x86_avx_vtestc_ps_256:
12021     case Intrinsic::x86_avx_vtestc_pd_256:
12022       IsTestPacked = true; // Fallthrough
12023     case Intrinsic::x86_sse41_ptestc:
12024     case Intrinsic::x86_avx_ptestc_256:
12025       // CF = 1
12026       X86CC = X86::COND_B;
12027       break;
12028     case Intrinsic::x86_avx_vtestnzc_ps:
12029     case Intrinsic::x86_avx_vtestnzc_pd:
12030     case Intrinsic::x86_avx_vtestnzc_ps_256:
12031     case Intrinsic::x86_avx_vtestnzc_pd_256:
12032       IsTestPacked = true; // Fallthrough
12033     case Intrinsic::x86_sse41_ptestnzc:
12034     case Intrinsic::x86_avx_ptestnzc_256:
12035       // ZF and CF = 0
12036       X86CC = X86::COND_A;
12037       break;
12038     }
12039
12040     SDValue LHS = Op.getOperand(1);
12041     SDValue RHS = Op.getOperand(2);
12042     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12043     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12044     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12045     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12046     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12047   }
12048   case Intrinsic::x86_avx512_kortestz_w:
12049   case Intrinsic::x86_avx512_kortestc_w: {
12050     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12051     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12052     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12053     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12054     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12055     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12056     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12057   }
12058
12059   // SSE/AVX shift intrinsics
12060   case Intrinsic::x86_sse2_psll_w:
12061   case Intrinsic::x86_sse2_psll_d:
12062   case Intrinsic::x86_sse2_psll_q:
12063   case Intrinsic::x86_avx2_psll_w:
12064   case Intrinsic::x86_avx2_psll_d:
12065   case Intrinsic::x86_avx2_psll_q:
12066   case Intrinsic::x86_sse2_psrl_w:
12067   case Intrinsic::x86_sse2_psrl_d:
12068   case Intrinsic::x86_sse2_psrl_q:
12069   case Intrinsic::x86_avx2_psrl_w:
12070   case Intrinsic::x86_avx2_psrl_d:
12071   case Intrinsic::x86_avx2_psrl_q:
12072   case Intrinsic::x86_sse2_psra_w:
12073   case Intrinsic::x86_sse2_psra_d:
12074   case Intrinsic::x86_avx2_psra_w:
12075   case Intrinsic::x86_avx2_psra_d: {
12076     unsigned Opcode;
12077     switch (IntNo) {
12078     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12079     case Intrinsic::x86_sse2_psll_w:
12080     case Intrinsic::x86_sse2_psll_d:
12081     case Intrinsic::x86_sse2_psll_q:
12082     case Intrinsic::x86_avx2_psll_w:
12083     case Intrinsic::x86_avx2_psll_d:
12084     case Intrinsic::x86_avx2_psll_q:
12085       Opcode = X86ISD::VSHL;
12086       break;
12087     case Intrinsic::x86_sse2_psrl_w:
12088     case Intrinsic::x86_sse2_psrl_d:
12089     case Intrinsic::x86_sse2_psrl_q:
12090     case Intrinsic::x86_avx2_psrl_w:
12091     case Intrinsic::x86_avx2_psrl_d:
12092     case Intrinsic::x86_avx2_psrl_q:
12093       Opcode = X86ISD::VSRL;
12094       break;
12095     case Intrinsic::x86_sse2_psra_w:
12096     case Intrinsic::x86_sse2_psra_d:
12097     case Intrinsic::x86_avx2_psra_w:
12098     case Intrinsic::x86_avx2_psra_d:
12099       Opcode = X86ISD::VSRA;
12100       break;
12101     }
12102     return DAG.getNode(Opcode, dl, Op.getValueType(),
12103                        Op.getOperand(1), Op.getOperand(2));
12104   }
12105
12106   // SSE/AVX immediate shift intrinsics
12107   case Intrinsic::x86_sse2_pslli_w:
12108   case Intrinsic::x86_sse2_pslli_d:
12109   case Intrinsic::x86_sse2_pslli_q:
12110   case Intrinsic::x86_avx2_pslli_w:
12111   case Intrinsic::x86_avx2_pslli_d:
12112   case Intrinsic::x86_avx2_pslli_q:
12113   case Intrinsic::x86_sse2_psrli_w:
12114   case Intrinsic::x86_sse2_psrli_d:
12115   case Intrinsic::x86_sse2_psrli_q:
12116   case Intrinsic::x86_avx2_psrli_w:
12117   case Intrinsic::x86_avx2_psrli_d:
12118   case Intrinsic::x86_avx2_psrli_q:
12119   case Intrinsic::x86_sse2_psrai_w:
12120   case Intrinsic::x86_sse2_psrai_d:
12121   case Intrinsic::x86_avx2_psrai_w:
12122   case Intrinsic::x86_avx2_psrai_d: {
12123     unsigned Opcode;
12124     switch (IntNo) {
12125     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12126     case Intrinsic::x86_sse2_pslli_w:
12127     case Intrinsic::x86_sse2_pslli_d:
12128     case Intrinsic::x86_sse2_pslli_q:
12129     case Intrinsic::x86_avx2_pslli_w:
12130     case Intrinsic::x86_avx2_pslli_d:
12131     case Intrinsic::x86_avx2_pslli_q:
12132       Opcode = X86ISD::VSHLI;
12133       break;
12134     case Intrinsic::x86_sse2_psrli_w:
12135     case Intrinsic::x86_sse2_psrli_d:
12136     case Intrinsic::x86_sse2_psrli_q:
12137     case Intrinsic::x86_avx2_psrli_w:
12138     case Intrinsic::x86_avx2_psrli_d:
12139     case Intrinsic::x86_avx2_psrli_q:
12140       Opcode = X86ISD::VSRLI;
12141       break;
12142     case Intrinsic::x86_sse2_psrai_w:
12143     case Intrinsic::x86_sse2_psrai_d:
12144     case Intrinsic::x86_avx2_psrai_w:
12145     case Intrinsic::x86_avx2_psrai_d:
12146       Opcode = X86ISD::VSRAI;
12147       break;
12148     }
12149     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12150                                Op.getOperand(1), Op.getOperand(2), DAG);
12151   }
12152
12153   case Intrinsic::x86_sse42_pcmpistria128:
12154   case Intrinsic::x86_sse42_pcmpestria128:
12155   case Intrinsic::x86_sse42_pcmpistric128:
12156   case Intrinsic::x86_sse42_pcmpestric128:
12157   case Intrinsic::x86_sse42_pcmpistrio128:
12158   case Intrinsic::x86_sse42_pcmpestrio128:
12159   case Intrinsic::x86_sse42_pcmpistris128:
12160   case Intrinsic::x86_sse42_pcmpestris128:
12161   case Intrinsic::x86_sse42_pcmpistriz128:
12162   case Intrinsic::x86_sse42_pcmpestriz128: {
12163     unsigned Opcode;
12164     unsigned X86CC;
12165     switch (IntNo) {
12166     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12167     case Intrinsic::x86_sse42_pcmpistria128:
12168       Opcode = X86ISD::PCMPISTRI;
12169       X86CC = X86::COND_A;
12170       break;
12171     case Intrinsic::x86_sse42_pcmpestria128:
12172       Opcode = X86ISD::PCMPESTRI;
12173       X86CC = X86::COND_A;
12174       break;
12175     case Intrinsic::x86_sse42_pcmpistric128:
12176       Opcode = X86ISD::PCMPISTRI;
12177       X86CC = X86::COND_B;
12178       break;
12179     case Intrinsic::x86_sse42_pcmpestric128:
12180       Opcode = X86ISD::PCMPESTRI;
12181       X86CC = X86::COND_B;
12182       break;
12183     case Intrinsic::x86_sse42_pcmpistrio128:
12184       Opcode = X86ISD::PCMPISTRI;
12185       X86CC = X86::COND_O;
12186       break;
12187     case Intrinsic::x86_sse42_pcmpestrio128:
12188       Opcode = X86ISD::PCMPESTRI;
12189       X86CC = X86::COND_O;
12190       break;
12191     case Intrinsic::x86_sse42_pcmpistris128:
12192       Opcode = X86ISD::PCMPISTRI;
12193       X86CC = X86::COND_S;
12194       break;
12195     case Intrinsic::x86_sse42_pcmpestris128:
12196       Opcode = X86ISD::PCMPESTRI;
12197       X86CC = X86::COND_S;
12198       break;
12199     case Intrinsic::x86_sse42_pcmpistriz128:
12200       Opcode = X86ISD::PCMPISTRI;
12201       X86CC = X86::COND_E;
12202       break;
12203     case Intrinsic::x86_sse42_pcmpestriz128:
12204       Opcode = X86ISD::PCMPESTRI;
12205       X86CC = X86::COND_E;
12206       break;
12207     }
12208     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12209     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12210     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12211     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12212                                 DAG.getConstant(X86CC, MVT::i8),
12213                                 SDValue(PCMP.getNode(), 1));
12214     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12215   }
12216
12217   case Intrinsic::x86_sse42_pcmpistri128:
12218   case Intrinsic::x86_sse42_pcmpestri128: {
12219     unsigned Opcode;
12220     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12221       Opcode = X86ISD::PCMPISTRI;
12222     else
12223       Opcode = X86ISD::PCMPESTRI;
12224
12225     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12226     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12227     return DAG.getNode(Opcode, dl, VTs, NewOps);
12228   }
12229   case Intrinsic::x86_fma_vfmadd_ps:
12230   case Intrinsic::x86_fma_vfmadd_pd:
12231   case Intrinsic::x86_fma_vfmsub_ps:
12232   case Intrinsic::x86_fma_vfmsub_pd:
12233   case Intrinsic::x86_fma_vfnmadd_ps:
12234   case Intrinsic::x86_fma_vfnmadd_pd:
12235   case Intrinsic::x86_fma_vfnmsub_ps:
12236   case Intrinsic::x86_fma_vfnmsub_pd:
12237   case Intrinsic::x86_fma_vfmaddsub_ps:
12238   case Intrinsic::x86_fma_vfmaddsub_pd:
12239   case Intrinsic::x86_fma_vfmsubadd_ps:
12240   case Intrinsic::x86_fma_vfmsubadd_pd:
12241   case Intrinsic::x86_fma_vfmadd_ps_256:
12242   case Intrinsic::x86_fma_vfmadd_pd_256:
12243   case Intrinsic::x86_fma_vfmsub_ps_256:
12244   case Intrinsic::x86_fma_vfmsub_pd_256:
12245   case Intrinsic::x86_fma_vfnmadd_ps_256:
12246   case Intrinsic::x86_fma_vfnmadd_pd_256:
12247   case Intrinsic::x86_fma_vfnmsub_ps_256:
12248   case Intrinsic::x86_fma_vfnmsub_pd_256:
12249   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12250   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12251   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12252   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12253   case Intrinsic::x86_fma_vfmadd_ps_512:
12254   case Intrinsic::x86_fma_vfmadd_pd_512:
12255   case Intrinsic::x86_fma_vfmsub_ps_512:
12256   case Intrinsic::x86_fma_vfmsub_pd_512:
12257   case Intrinsic::x86_fma_vfnmadd_ps_512:
12258   case Intrinsic::x86_fma_vfnmadd_pd_512:
12259   case Intrinsic::x86_fma_vfnmsub_ps_512:
12260   case Intrinsic::x86_fma_vfnmsub_pd_512:
12261   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12262   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12263   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12264   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12265     unsigned Opc;
12266     switch (IntNo) {
12267     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12268     case Intrinsic::x86_fma_vfmadd_ps:
12269     case Intrinsic::x86_fma_vfmadd_pd:
12270     case Intrinsic::x86_fma_vfmadd_ps_256:
12271     case Intrinsic::x86_fma_vfmadd_pd_256:
12272     case Intrinsic::x86_fma_vfmadd_ps_512:
12273     case Intrinsic::x86_fma_vfmadd_pd_512:
12274       Opc = X86ISD::FMADD;
12275       break;
12276     case Intrinsic::x86_fma_vfmsub_ps:
12277     case Intrinsic::x86_fma_vfmsub_pd:
12278     case Intrinsic::x86_fma_vfmsub_ps_256:
12279     case Intrinsic::x86_fma_vfmsub_pd_256:
12280     case Intrinsic::x86_fma_vfmsub_ps_512:
12281     case Intrinsic::x86_fma_vfmsub_pd_512:
12282       Opc = X86ISD::FMSUB;
12283       break;
12284     case Intrinsic::x86_fma_vfnmadd_ps:
12285     case Intrinsic::x86_fma_vfnmadd_pd:
12286     case Intrinsic::x86_fma_vfnmadd_ps_256:
12287     case Intrinsic::x86_fma_vfnmadd_pd_256:
12288     case Intrinsic::x86_fma_vfnmadd_ps_512:
12289     case Intrinsic::x86_fma_vfnmadd_pd_512:
12290       Opc = X86ISD::FNMADD;
12291       break;
12292     case Intrinsic::x86_fma_vfnmsub_ps:
12293     case Intrinsic::x86_fma_vfnmsub_pd:
12294     case Intrinsic::x86_fma_vfnmsub_ps_256:
12295     case Intrinsic::x86_fma_vfnmsub_pd_256:
12296     case Intrinsic::x86_fma_vfnmsub_ps_512:
12297     case Intrinsic::x86_fma_vfnmsub_pd_512:
12298       Opc = X86ISD::FNMSUB;
12299       break;
12300     case Intrinsic::x86_fma_vfmaddsub_ps:
12301     case Intrinsic::x86_fma_vfmaddsub_pd:
12302     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12303     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12304     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12305     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12306       Opc = X86ISD::FMADDSUB;
12307       break;
12308     case Intrinsic::x86_fma_vfmsubadd_ps:
12309     case Intrinsic::x86_fma_vfmsubadd_pd:
12310     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12311     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12312     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12313     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12314       Opc = X86ISD::FMSUBADD;
12315       break;
12316     }
12317
12318     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12319                        Op.getOperand(2), Op.getOperand(3));
12320   }
12321   }
12322 }
12323
12324 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12325                              SDValue Base, SDValue Index,
12326                              SDValue ScaleOp, SDValue Chain,
12327                              const X86Subtarget * Subtarget) {
12328   SDLoc dl(Op);
12329   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12330   assert(C && "Invalid scale type");
12331   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12332   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12333   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12334                              Index.getSimpleValueType().getVectorNumElements());
12335   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12336   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12337   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12338   SDValue Segment = DAG.getRegister(0, MVT::i32);
12339   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12340   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12341   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12342   return DAG.getMergeValues(RetOps, dl);
12343 }
12344
12345 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12346                               SDValue Src, SDValue Mask, SDValue Base,
12347                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12348                               const X86Subtarget * Subtarget) {
12349   SDLoc dl(Op);
12350   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12351   assert(C && "Invalid scale type");
12352   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12353   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12354                              Index.getSimpleValueType().getVectorNumElements());
12355   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12356   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12357   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12358   SDValue Segment = DAG.getRegister(0, MVT::i32);
12359   if (Src.getOpcode() == ISD::UNDEF)
12360     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12361   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12362   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12363   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12364   return DAG.getMergeValues(RetOps, dl);
12365 }
12366
12367 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12368                               SDValue Src, SDValue Base, SDValue Index,
12369                               SDValue ScaleOp, SDValue Chain) {
12370   SDLoc dl(Op);
12371   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12372   assert(C && "Invalid scale type");
12373   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12374   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12375   SDValue Segment = DAG.getRegister(0, MVT::i32);
12376   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12377                              Index.getSimpleValueType().getVectorNumElements());
12378   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12379   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12380   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12381   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12382   return SDValue(Res, 1);
12383 }
12384
12385 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12386                                SDValue Src, SDValue Mask, SDValue Base,
12387                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12388   SDLoc dl(Op);
12389   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12390   assert(C && "Invalid scale type");
12391   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12392   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12393   SDValue Segment = DAG.getRegister(0, MVT::i32);
12394   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12395                              Index.getSimpleValueType().getVectorNumElements());
12396   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12397   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12398   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12399   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12400   return SDValue(Res, 1);
12401 }
12402
12403 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12404 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12405 // also used to custom lower READCYCLECOUNTER nodes.
12406 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12407                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12408                               SmallVectorImpl<SDValue> &Results) {
12409   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12410   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12411   SDValue LO, HI;
12412
12413   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12414   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12415   // and the EAX register is loaded with the low-order 32 bits.
12416   if (Subtarget->is64Bit()) {
12417     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12418     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12419                             LO.getValue(2));
12420   } else {
12421     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12422     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12423                             LO.getValue(2));
12424   }
12425   SDValue Chain = HI.getValue(1);
12426
12427   if (Opcode == X86ISD::RDTSCP_DAG) {
12428     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12429
12430     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12431     // the ECX register. Add 'ecx' explicitly to the chain.
12432     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12433                                      HI.getValue(2));
12434     // Explicitly store the content of ECX at the location passed in input
12435     // to the 'rdtscp' intrinsic.
12436     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12437                          MachinePointerInfo(), false, false, 0);
12438   }
12439
12440   if (Subtarget->is64Bit()) {
12441     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12442     // the EAX register is loaded with the low-order 32 bits.
12443     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12444                               DAG.getConstant(32, MVT::i8));
12445     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12446     Results.push_back(Chain);
12447     return;
12448   }
12449
12450   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12451   SDValue Ops[] = { LO, HI };
12452   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12453   Results.push_back(Pair);
12454   Results.push_back(Chain);
12455 }
12456
12457 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12458                                      SelectionDAG &DAG) {
12459   SmallVector<SDValue, 2> Results;
12460   SDLoc DL(Op);
12461   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12462                           Results);
12463   return DAG.getMergeValues(Results, DL);
12464 }
12465
12466 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12467                                       SelectionDAG &DAG) {
12468   SDLoc dl(Op);
12469   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12470   switch (IntNo) {
12471   default: return SDValue();    // Don't custom lower most intrinsics.
12472
12473   // RDRAND/RDSEED intrinsics.
12474   case Intrinsic::x86_rdrand_16:
12475   case Intrinsic::x86_rdrand_32:
12476   case Intrinsic::x86_rdrand_64:
12477   case Intrinsic::x86_rdseed_16:
12478   case Intrinsic::x86_rdseed_32:
12479   case Intrinsic::x86_rdseed_64: {
12480     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12481                        IntNo == Intrinsic::x86_rdseed_32 ||
12482                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12483                                                             X86ISD::RDRAND;
12484     // Emit the node with the right value type.
12485     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12486     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12487
12488     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12489     // Otherwise return the value from Rand, which is always 0, casted to i32.
12490     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12491                       DAG.getConstant(1, Op->getValueType(1)),
12492                       DAG.getConstant(X86::COND_B, MVT::i32),
12493                       SDValue(Result.getNode(), 1) };
12494     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12495                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12496                                   Ops);
12497
12498     // Return { result, isValid, chain }.
12499     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12500                        SDValue(Result.getNode(), 2));
12501   }
12502   //int_gather(index, base, scale);
12503   case Intrinsic::x86_avx512_gather_qpd_512:
12504   case Intrinsic::x86_avx512_gather_qps_512:
12505   case Intrinsic::x86_avx512_gather_dpd_512:
12506   case Intrinsic::x86_avx512_gather_qpi_512:
12507   case Intrinsic::x86_avx512_gather_qpq_512:
12508   case Intrinsic::x86_avx512_gather_dpq_512:
12509   case Intrinsic::x86_avx512_gather_dps_512:
12510   case Intrinsic::x86_avx512_gather_dpi_512: {
12511     unsigned Opc;
12512     switch (IntNo) {
12513     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12514     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12515     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12516     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12517     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12518     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12519     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12520     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12521     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12522     }
12523     SDValue Chain = Op.getOperand(0);
12524     SDValue Index = Op.getOperand(2);
12525     SDValue Base  = Op.getOperand(3);
12526     SDValue Scale = Op.getOperand(4);
12527     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12528   }
12529   //int_gather_mask(v1, mask, index, base, scale);
12530   case Intrinsic::x86_avx512_gather_qps_mask_512:
12531   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12532   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12533   case Intrinsic::x86_avx512_gather_dps_mask_512:
12534   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12535   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12536   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12537   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12538     unsigned Opc;
12539     switch (IntNo) {
12540     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12541     case Intrinsic::x86_avx512_gather_qps_mask_512:
12542       Opc = X86::VGATHERQPSZrm; break;
12543     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12544       Opc = X86::VGATHERQPDZrm; break;
12545     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12546       Opc = X86::VGATHERDPDZrm; break;
12547     case Intrinsic::x86_avx512_gather_dps_mask_512:
12548       Opc = X86::VGATHERDPSZrm; break;
12549     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12550       Opc = X86::VPGATHERQDZrm; break;
12551     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12552       Opc = X86::VPGATHERQQZrm; break;
12553     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12554       Opc = X86::VPGATHERDDZrm; break;
12555     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12556       Opc = X86::VPGATHERDQZrm; break;
12557     }
12558     SDValue Chain = Op.getOperand(0);
12559     SDValue Src   = Op.getOperand(2);
12560     SDValue Mask  = Op.getOperand(3);
12561     SDValue Index = Op.getOperand(4);
12562     SDValue Base  = Op.getOperand(5);
12563     SDValue Scale = Op.getOperand(6);
12564     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12565                           Subtarget);
12566   }
12567   //int_scatter(base, index, v1, scale);
12568   case Intrinsic::x86_avx512_scatter_qpd_512:
12569   case Intrinsic::x86_avx512_scatter_qps_512:
12570   case Intrinsic::x86_avx512_scatter_dpd_512:
12571   case Intrinsic::x86_avx512_scatter_qpi_512:
12572   case Intrinsic::x86_avx512_scatter_qpq_512:
12573   case Intrinsic::x86_avx512_scatter_dpq_512:
12574   case Intrinsic::x86_avx512_scatter_dps_512:
12575   case Intrinsic::x86_avx512_scatter_dpi_512: {
12576     unsigned Opc;
12577     switch (IntNo) {
12578     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12579     case Intrinsic::x86_avx512_scatter_qpd_512:
12580       Opc = X86::VSCATTERQPDZmr; break;
12581     case Intrinsic::x86_avx512_scatter_qps_512:
12582       Opc = X86::VSCATTERQPSZmr; break;
12583     case Intrinsic::x86_avx512_scatter_dpd_512:
12584       Opc = X86::VSCATTERDPDZmr; break;
12585     case Intrinsic::x86_avx512_scatter_dps_512:
12586       Opc = X86::VSCATTERDPSZmr; break;
12587     case Intrinsic::x86_avx512_scatter_qpi_512:
12588       Opc = X86::VPSCATTERQDZmr; break;
12589     case Intrinsic::x86_avx512_scatter_qpq_512:
12590       Opc = X86::VPSCATTERQQZmr; break;
12591     case Intrinsic::x86_avx512_scatter_dpq_512:
12592       Opc = X86::VPSCATTERDQZmr; break;
12593     case Intrinsic::x86_avx512_scatter_dpi_512:
12594       Opc = X86::VPSCATTERDDZmr; break;
12595     }
12596     SDValue Chain = Op.getOperand(0);
12597     SDValue Base  = Op.getOperand(2);
12598     SDValue Index = Op.getOperand(3);
12599     SDValue Src   = Op.getOperand(4);
12600     SDValue Scale = Op.getOperand(5);
12601     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12602   }
12603   //int_scatter_mask(base, mask, index, v1, scale);
12604   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12605   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12606   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12607   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12608   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12609   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12610   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12611   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12612     unsigned Opc;
12613     switch (IntNo) {
12614     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12615     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12616       Opc = X86::VSCATTERQPDZmr; break;
12617     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12618       Opc = X86::VSCATTERQPSZmr; break;
12619     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12620       Opc = X86::VSCATTERDPDZmr; break;
12621     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12622       Opc = X86::VSCATTERDPSZmr; break;
12623     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12624       Opc = X86::VPSCATTERQDZmr; break;
12625     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12626       Opc = X86::VPSCATTERQQZmr; break;
12627     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12628       Opc = X86::VPSCATTERDQZmr; break;
12629     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12630       Opc = X86::VPSCATTERDDZmr; break;
12631     }
12632     SDValue Chain = Op.getOperand(0);
12633     SDValue Base  = Op.getOperand(2);
12634     SDValue Mask  = Op.getOperand(3);
12635     SDValue Index = Op.getOperand(4);
12636     SDValue Src   = Op.getOperand(5);
12637     SDValue Scale = Op.getOperand(6);
12638     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12639   }
12640   // Read Time Stamp Counter (RDTSC).
12641   case Intrinsic::x86_rdtsc:
12642   // Read Time Stamp Counter and Processor ID (RDTSCP).
12643   case Intrinsic::x86_rdtscp: {
12644     unsigned Opc;
12645     switch (IntNo) {
12646     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12647     case Intrinsic::x86_rdtsc:
12648       Opc = X86ISD::RDTSC_DAG; break;
12649     case Intrinsic::x86_rdtscp:
12650       Opc = X86ISD::RDTSCP_DAG; break;
12651     }
12652     SmallVector<SDValue, 2> Results;
12653     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12654     return DAG.getMergeValues(Results, dl);
12655   }
12656   // XTEST intrinsics.
12657   case Intrinsic::x86_xtest: {
12658     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12659     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12660     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12661                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12662                                 InTrans);
12663     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12664     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12665                        Ret, SDValue(InTrans.getNode(), 1));
12666   }
12667   }
12668 }
12669
12670 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12671                                            SelectionDAG &DAG) const {
12672   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12673   MFI->setReturnAddressIsTaken(true);
12674
12675   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12676     return SDValue();
12677
12678   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12679   SDLoc dl(Op);
12680   EVT PtrVT = getPointerTy();
12681
12682   if (Depth > 0) {
12683     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12684     const X86RegisterInfo *RegInfo =
12685       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12686     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12687     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12688                        DAG.getNode(ISD::ADD, dl, PtrVT,
12689                                    FrameAddr, Offset),
12690                        MachinePointerInfo(), false, false, false, 0);
12691   }
12692
12693   // Just load the return address.
12694   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12695   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12696                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12697 }
12698
12699 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12700   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12701   MFI->setFrameAddressIsTaken(true);
12702
12703   EVT VT = Op.getValueType();
12704   SDLoc dl(Op);  // FIXME probably not meaningful
12705   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12706   const X86RegisterInfo *RegInfo =
12707     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12708   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12709   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12710           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12711          "Invalid Frame Register!");
12712   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12713   while (Depth--)
12714     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12715                             MachinePointerInfo(),
12716                             false, false, false, 0);
12717   return FrameAddr;
12718 }
12719
12720 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12721                                                      SelectionDAG &DAG) const {
12722   const X86RegisterInfo *RegInfo =
12723     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12724   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12725 }
12726
12727 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12728   SDValue Chain     = Op.getOperand(0);
12729   SDValue Offset    = Op.getOperand(1);
12730   SDValue Handler   = Op.getOperand(2);
12731   SDLoc dl      (Op);
12732
12733   EVT PtrVT = getPointerTy();
12734   const X86RegisterInfo *RegInfo =
12735     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12736   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12737   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12738           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12739          "Invalid Frame Register!");
12740   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12741   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12742
12743   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12744                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12745   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12746   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12747                        false, false, 0);
12748   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12749
12750   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12751                      DAG.getRegister(StoreAddrReg, PtrVT));
12752 }
12753
12754 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12755                                                SelectionDAG &DAG) const {
12756   SDLoc DL(Op);
12757   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12758                      DAG.getVTList(MVT::i32, MVT::Other),
12759                      Op.getOperand(0), Op.getOperand(1));
12760 }
12761
12762 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12763                                                 SelectionDAG &DAG) const {
12764   SDLoc DL(Op);
12765   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12766                      Op.getOperand(0), Op.getOperand(1));
12767 }
12768
12769 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12770   return Op.getOperand(0);
12771 }
12772
12773 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12774                                                 SelectionDAG &DAG) const {
12775   SDValue Root = Op.getOperand(0);
12776   SDValue Trmp = Op.getOperand(1); // trampoline
12777   SDValue FPtr = Op.getOperand(2); // nested function
12778   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12779   SDLoc dl (Op);
12780
12781   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12782   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12783
12784   if (Subtarget->is64Bit()) {
12785     SDValue OutChains[6];
12786
12787     // Large code-model.
12788     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12789     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12790
12791     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12792     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12793
12794     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12795
12796     // Load the pointer to the nested function into R11.
12797     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12798     SDValue Addr = Trmp;
12799     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12800                                 Addr, MachinePointerInfo(TrmpAddr),
12801                                 false, false, 0);
12802
12803     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12804                        DAG.getConstant(2, MVT::i64));
12805     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12806                                 MachinePointerInfo(TrmpAddr, 2),
12807                                 false, false, 2);
12808
12809     // Load the 'nest' parameter value into R10.
12810     // R10 is specified in X86CallingConv.td
12811     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12812     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12813                        DAG.getConstant(10, MVT::i64));
12814     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12815                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12816                                 false, false, 0);
12817
12818     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12819                        DAG.getConstant(12, MVT::i64));
12820     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12821                                 MachinePointerInfo(TrmpAddr, 12),
12822                                 false, false, 2);
12823
12824     // Jump to the nested function.
12825     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12826     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12827                        DAG.getConstant(20, MVT::i64));
12828     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12829                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12830                                 false, false, 0);
12831
12832     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12833     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12834                        DAG.getConstant(22, MVT::i64));
12835     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12836                                 MachinePointerInfo(TrmpAddr, 22),
12837                                 false, false, 0);
12838
12839     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12840   } else {
12841     const Function *Func =
12842       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12843     CallingConv::ID CC = Func->getCallingConv();
12844     unsigned NestReg;
12845
12846     switch (CC) {
12847     default:
12848       llvm_unreachable("Unsupported calling convention");
12849     case CallingConv::C:
12850     case CallingConv::X86_StdCall: {
12851       // Pass 'nest' parameter in ECX.
12852       // Must be kept in sync with X86CallingConv.td
12853       NestReg = X86::ECX;
12854
12855       // Check that ECX wasn't needed by an 'inreg' parameter.
12856       FunctionType *FTy = Func->getFunctionType();
12857       const AttributeSet &Attrs = Func->getAttributes();
12858
12859       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12860         unsigned InRegCount = 0;
12861         unsigned Idx = 1;
12862
12863         for (FunctionType::param_iterator I = FTy->param_begin(),
12864              E = FTy->param_end(); I != E; ++I, ++Idx)
12865           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12866             // FIXME: should only count parameters that are lowered to integers.
12867             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12868
12869         if (InRegCount > 2) {
12870           report_fatal_error("Nest register in use - reduce number of inreg"
12871                              " parameters!");
12872         }
12873       }
12874       break;
12875     }
12876     case CallingConv::X86_FastCall:
12877     case CallingConv::X86_ThisCall:
12878     case CallingConv::Fast:
12879       // Pass 'nest' parameter in EAX.
12880       // Must be kept in sync with X86CallingConv.td
12881       NestReg = X86::EAX;
12882       break;
12883     }
12884
12885     SDValue OutChains[4];
12886     SDValue Addr, Disp;
12887
12888     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12889                        DAG.getConstant(10, MVT::i32));
12890     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12891
12892     // This is storing the opcode for MOV32ri.
12893     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12894     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12895     OutChains[0] = DAG.getStore(Root, dl,
12896                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12897                                 Trmp, MachinePointerInfo(TrmpAddr),
12898                                 false, false, 0);
12899
12900     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12901                        DAG.getConstant(1, MVT::i32));
12902     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12903                                 MachinePointerInfo(TrmpAddr, 1),
12904                                 false, false, 1);
12905
12906     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12907     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12908                        DAG.getConstant(5, MVT::i32));
12909     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12910                                 MachinePointerInfo(TrmpAddr, 5),
12911                                 false, false, 1);
12912
12913     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12914                        DAG.getConstant(6, MVT::i32));
12915     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12916                                 MachinePointerInfo(TrmpAddr, 6),
12917                                 false, false, 1);
12918
12919     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12920   }
12921 }
12922
12923 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12924                                             SelectionDAG &DAG) const {
12925   /*
12926    The rounding mode is in bits 11:10 of FPSR, and has the following
12927    settings:
12928      00 Round to nearest
12929      01 Round to -inf
12930      10 Round to +inf
12931      11 Round to 0
12932
12933   FLT_ROUNDS, on the other hand, expects the following:
12934     -1 Undefined
12935      0 Round to 0
12936      1 Round to nearest
12937      2 Round to +inf
12938      3 Round to -inf
12939
12940   To perform the conversion, we do:
12941     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12942   */
12943
12944   MachineFunction &MF = DAG.getMachineFunction();
12945   const TargetMachine &TM = MF.getTarget();
12946   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12947   unsigned StackAlignment = TFI.getStackAlignment();
12948   MVT VT = Op.getSimpleValueType();
12949   SDLoc DL(Op);
12950
12951   // Save FP Control Word to stack slot
12952   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12953   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12954
12955   MachineMemOperand *MMO =
12956    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12957                            MachineMemOperand::MOStore, 2, 2);
12958
12959   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12960   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12961                                           DAG.getVTList(MVT::Other),
12962                                           Ops, MVT::i16, MMO);
12963
12964   // Load FP Control Word from stack slot
12965   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12966                             MachinePointerInfo(), false, false, false, 0);
12967
12968   // Transform as necessary
12969   SDValue CWD1 =
12970     DAG.getNode(ISD::SRL, DL, MVT::i16,
12971                 DAG.getNode(ISD::AND, DL, MVT::i16,
12972                             CWD, DAG.getConstant(0x800, MVT::i16)),
12973                 DAG.getConstant(11, MVT::i8));
12974   SDValue CWD2 =
12975     DAG.getNode(ISD::SRL, DL, MVT::i16,
12976                 DAG.getNode(ISD::AND, DL, MVT::i16,
12977                             CWD, DAG.getConstant(0x400, MVT::i16)),
12978                 DAG.getConstant(9, MVT::i8));
12979
12980   SDValue RetVal =
12981     DAG.getNode(ISD::AND, DL, MVT::i16,
12982                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12983                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12984                             DAG.getConstant(1, MVT::i16)),
12985                 DAG.getConstant(3, MVT::i16));
12986
12987   return DAG.getNode((VT.getSizeInBits() < 16 ?
12988                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12989 }
12990
12991 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12992   MVT VT = Op.getSimpleValueType();
12993   EVT OpVT = VT;
12994   unsigned NumBits = VT.getSizeInBits();
12995   SDLoc dl(Op);
12996
12997   Op = Op.getOperand(0);
12998   if (VT == MVT::i8) {
12999     // Zero extend to i32 since there is not an i8 bsr.
13000     OpVT = MVT::i32;
13001     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13002   }
13003
13004   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13005   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13006   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13007
13008   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13009   SDValue Ops[] = {
13010     Op,
13011     DAG.getConstant(NumBits+NumBits-1, OpVT),
13012     DAG.getConstant(X86::COND_E, MVT::i8),
13013     Op.getValue(1)
13014   };
13015   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13016
13017   // Finally xor with NumBits-1.
13018   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13019
13020   if (VT == MVT::i8)
13021     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13022   return Op;
13023 }
13024
13025 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13026   MVT VT = Op.getSimpleValueType();
13027   EVT OpVT = VT;
13028   unsigned NumBits = VT.getSizeInBits();
13029   SDLoc dl(Op);
13030
13031   Op = Op.getOperand(0);
13032   if (VT == MVT::i8) {
13033     // Zero extend to i32 since there is not an i8 bsr.
13034     OpVT = MVT::i32;
13035     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13036   }
13037
13038   // Issue a bsr (scan bits in reverse).
13039   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13040   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13041
13042   // And xor with NumBits-1.
13043   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13044
13045   if (VT == MVT::i8)
13046     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13047   return Op;
13048 }
13049
13050 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13051   MVT VT = Op.getSimpleValueType();
13052   unsigned NumBits = VT.getSizeInBits();
13053   SDLoc dl(Op);
13054   Op = Op.getOperand(0);
13055
13056   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13057   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13058   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13059
13060   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13061   SDValue Ops[] = {
13062     Op,
13063     DAG.getConstant(NumBits, VT),
13064     DAG.getConstant(X86::COND_E, MVT::i8),
13065     Op.getValue(1)
13066   };
13067   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13068 }
13069
13070 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13071 // ones, and then concatenate the result back.
13072 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13073   MVT VT = Op.getSimpleValueType();
13074
13075   assert(VT.is256BitVector() && VT.isInteger() &&
13076          "Unsupported value type for operation");
13077
13078   unsigned NumElems = VT.getVectorNumElements();
13079   SDLoc dl(Op);
13080
13081   // Extract the LHS vectors
13082   SDValue LHS = Op.getOperand(0);
13083   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13084   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13085
13086   // Extract the RHS vectors
13087   SDValue RHS = Op.getOperand(1);
13088   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13089   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13090
13091   MVT EltVT = VT.getVectorElementType();
13092   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13093
13094   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13095                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13096                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13097 }
13098
13099 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13100   assert(Op.getSimpleValueType().is256BitVector() &&
13101          Op.getSimpleValueType().isInteger() &&
13102          "Only handle AVX 256-bit vector integer operation");
13103   return Lower256IntArith(Op, DAG);
13104 }
13105
13106 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13107   assert(Op.getSimpleValueType().is256BitVector() &&
13108          Op.getSimpleValueType().isInteger() &&
13109          "Only handle AVX 256-bit vector integer operation");
13110   return Lower256IntArith(Op, DAG);
13111 }
13112
13113 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13114                         SelectionDAG &DAG) {
13115   SDLoc dl(Op);
13116   MVT VT = Op.getSimpleValueType();
13117
13118   // Decompose 256-bit ops into smaller 128-bit ops.
13119   if (VT.is256BitVector() && !Subtarget->hasInt256())
13120     return Lower256IntArith(Op, DAG);
13121
13122   SDValue A = Op.getOperand(0);
13123   SDValue B = Op.getOperand(1);
13124
13125   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13126   if (VT == MVT::v4i32) {
13127     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13128            "Should not custom lower when pmuldq is available!");
13129
13130     // Extract the odd parts.
13131     static const int UnpackMask[] = { 1, -1, 3, -1 };
13132     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13133     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13134
13135     // Multiply the even parts.
13136     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13137     // Now multiply odd parts.
13138     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13139
13140     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13141     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13142
13143     // Merge the two vectors back together with a shuffle. This expands into 2
13144     // shuffles.
13145     static const int ShufMask[] = { 0, 4, 2, 6 };
13146     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13147   }
13148
13149   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13150          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13151
13152   //  Ahi = psrlqi(a, 32);
13153   //  Bhi = psrlqi(b, 32);
13154   //
13155   //  AloBlo = pmuludq(a, b);
13156   //  AloBhi = pmuludq(a, Bhi);
13157   //  AhiBlo = pmuludq(Ahi, b);
13158
13159   //  AloBhi = psllqi(AloBhi, 32);
13160   //  AhiBlo = psllqi(AhiBlo, 32);
13161   //  return AloBlo + AloBhi + AhiBlo;
13162
13163   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13164   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13165
13166   // Bit cast to 32-bit vectors for MULUDQ
13167   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13168                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13169   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13170   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13171   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13172   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13173
13174   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13175   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13176   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13177
13178   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13179   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13180
13181   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13182   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13183 }
13184
13185 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13186                              SelectionDAG &DAG) {
13187   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13188   EVT VT = Op0.getValueType();
13189   SDLoc dl(Op);
13190
13191   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13192          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13193
13194   // Get the high parts.
13195   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13196   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13197   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13198
13199   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13200   // ints.
13201   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13202   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13203   unsigned Opcode =
13204       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13205   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13206                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13207   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13208                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13209
13210   // Shuffle it back into the right order.
13211   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13212   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13213   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13214   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13215
13216   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13217   // unsigned multiply.
13218   if (IsSigned && !Subtarget->hasSSE41()) {
13219     SDValue ShAmt =
13220         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13221     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13222                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13223     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13224                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13225
13226     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13227     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13228   }
13229
13230   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13231 }
13232
13233 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13234                                          const X86Subtarget *Subtarget) {
13235   MVT VT = Op.getSimpleValueType();
13236   SDLoc dl(Op);
13237   SDValue R = Op.getOperand(0);
13238   SDValue Amt = Op.getOperand(1);
13239
13240   // Optimize shl/srl/sra with constant shift amount.
13241   if (isSplatVector(Amt.getNode())) {
13242     SDValue SclrAmt = Amt->getOperand(0);
13243     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13244       uint64_t ShiftAmt = C->getZExtValue();
13245
13246       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13247           (Subtarget->hasInt256() &&
13248            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13249           (Subtarget->hasAVX512() &&
13250            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13251         if (Op.getOpcode() == ISD::SHL)
13252           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13253                                             DAG);
13254         if (Op.getOpcode() == ISD::SRL)
13255           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13256                                             DAG);
13257         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13258           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13259                                             DAG);
13260       }
13261
13262       if (VT == MVT::v16i8) {
13263         if (Op.getOpcode() == ISD::SHL) {
13264           // Make a large shift.
13265           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13266                                                    MVT::v8i16, R, ShiftAmt,
13267                                                    DAG);
13268           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13269           // Zero out the rightmost bits.
13270           SmallVector<SDValue, 16> V(16,
13271                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13272                                                      MVT::i8));
13273           return DAG.getNode(ISD::AND, dl, VT, SHL,
13274                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13275         }
13276         if (Op.getOpcode() == ISD::SRL) {
13277           // Make a large shift.
13278           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13279                                                    MVT::v8i16, R, ShiftAmt,
13280                                                    DAG);
13281           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13282           // Zero out the leftmost bits.
13283           SmallVector<SDValue, 16> V(16,
13284                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13285                                                      MVT::i8));
13286           return DAG.getNode(ISD::AND, dl, VT, SRL,
13287                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13288         }
13289         if (Op.getOpcode() == ISD::SRA) {
13290           if (ShiftAmt == 7) {
13291             // R s>> 7  ===  R s< 0
13292             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13293             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13294           }
13295
13296           // R s>> a === ((R u>> a) ^ m) - m
13297           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13298           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13299                                                          MVT::i8));
13300           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13301           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13302           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13303           return Res;
13304         }
13305         llvm_unreachable("Unknown shift opcode.");
13306       }
13307
13308       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13309         if (Op.getOpcode() == ISD::SHL) {
13310           // Make a large shift.
13311           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13312                                                    MVT::v16i16, R, ShiftAmt,
13313                                                    DAG);
13314           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13315           // Zero out the rightmost bits.
13316           SmallVector<SDValue, 32> V(32,
13317                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13318                                                      MVT::i8));
13319           return DAG.getNode(ISD::AND, dl, VT, SHL,
13320                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13321         }
13322         if (Op.getOpcode() == ISD::SRL) {
13323           // Make a large shift.
13324           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13325                                                    MVT::v16i16, R, ShiftAmt,
13326                                                    DAG);
13327           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13328           // Zero out the leftmost bits.
13329           SmallVector<SDValue, 32> V(32,
13330                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13331                                                      MVT::i8));
13332           return DAG.getNode(ISD::AND, dl, VT, SRL,
13333                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13334         }
13335         if (Op.getOpcode() == ISD::SRA) {
13336           if (ShiftAmt == 7) {
13337             // R s>> 7  ===  R s< 0
13338             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13339             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13340           }
13341
13342           // R s>> a === ((R u>> a) ^ m) - m
13343           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13344           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13345                                                          MVT::i8));
13346           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13347           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13348           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13349           return Res;
13350         }
13351         llvm_unreachable("Unknown shift opcode.");
13352       }
13353     }
13354   }
13355
13356   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13357   if (!Subtarget->is64Bit() &&
13358       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13359       Amt.getOpcode() == ISD::BITCAST &&
13360       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13361     Amt = Amt.getOperand(0);
13362     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13363                      VT.getVectorNumElements();
13364     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13365     uint64_t ShiftAmt = 0;
13366     for (unsigned i = 0; i != Ratio; ++i) {
13367       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13368       if (!C)
13369         return SDValue();
13370       // 6 == Log2(64)
13371       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13372     }
13373     // Check remaining shift amounts.
13374     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13375       uint64_t ShAmt = 0;
13376       for (unsigned j = 0; j != Ratio; ++j) {
13377         ConstantSDNode *C =
13378           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13379         if (!C)
13380           return SDValue();
13381         // 6 == Log2(64)
13382         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13383       }
13384       if (ShAmt != ShiftAmt)
13385         return SDValue();
13386     }
13387     switch (Op.getOpcode()) {
13388     default:
13389       llvm_unreachable("Unknown shift opcode!");
13390     case ISD::SHL:
13391       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13392                                         DAG);
13393     case ISD::SRL:
13394       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13395                                         DAG);
13396     case ISD::SRA:
13397       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13398                                         DAG);
13399     }
13400   }
13401
13402   return SDValue();
13403 }
13404
13405 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13406                                         const X86Subtarget* Subtarget) {
13407   MVT VT = Op.getSimpleValueType();
13408   SDLoc dl(Op);
13409   SDValue R = Op.getOperand(0);
13410   SDValue Amt = Op.getOperand(1);
13411
13412   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13413       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13414       (Subtarget->hasInt256() &&
13415        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13416         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13417        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13418     SDValue BaseShAmt;
13419     EVT EltVT = VT.getVectorElementType();
13420
13421     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13422       unsigned NumElts = VT.getVectorNumElements();
13423       unsigned i, j;
13424       for (i = 0; i != NumElts; ++i) {
13425         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13426           continue;
13427         break;
13428       }
13429       for (j = i; j != NumElts; ++j) {
13430         SDValue Arg = Amt.getOperand(j);
13431         if (Arg.getOpcode() == ISD::UNDEF) continue;
13432         if (Arg != Amt.getOperand(i))
13433           break;
13434       }
13435       if (i != NumElts && j == NumElts)
13436         BaseShAmt = Amt.getOperand(i);
13437     } else {
13438       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13439         Amt = Amt.getOperand(0);
13440       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13441                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13442         SDValue InVec = Amt.getOperand(0);
13443         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13444           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13445           unsigned i = 0;
13446           for (; i != NumElts; ++i) {
13447             SDValue Arg = InVec.getOperand(i);
13448             if (Arg.getOpcode() == ISD::UNDEF) continue;
13449             BaseShAmt = Arg;
13450             break;
13451           }
13452         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13453            if (ConstantSDNode *C =
13454                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13455              unsigned SplatIdx =
13456                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13457              if (C->getZExtValue() == SplatIdx)
13458                BaseShAmt = InVec.getOperand(1);
13459            }
13460         }
13461         if (!BaseShAmt.getNode())
13462           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13463                                   DAG.getIntPtrConstant(0));
13464       }
13465     }
13466
13467     if (BaseShAmt.getNode()) {
13468       if (EltVT.bitsGT(MVT::i32))
13469         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13470       else if (EltVT.bitsLT(MVT::i32))
13471         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13472
13473       switch (Op.getOpcode()) {
13474       default:
13475         llvm_unreachable("Unknown shift opcode!");
13476       case ISD::SHL:
13477         switch (VT.SimpleTy) {
13478         default: return SDValue();
13479         case MVT::v2i64:
13480         case MVT::v4i32:
13481         case MVT::v8i16:
13482         case MVT::v4i64:
13483         case MVT::v8i32:
13484         case MVT::v16i16:
13485         case MVT::v16i32:
13486         case MVT::v8i64:
13487           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13488         }
13489       case ISD::SRA:
13490         switch (VT.SimpleTy) {
13491         default: return SDValue();
13492         case MVT::v4i32:
13493         case MVT::v8i16:
13494         case MVT::v8i32:
13495         case MVT::v16i16:
13496         case MVT::v16i32:
13497         case MVT::v8i64:
13498           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13499         }
13500       case ISD::SRL:
13501         switch (VT.SimpleTy) {
13502         default: return SDValue();
13503         case MVT::v2i64:
13504         case MVT::v4i32:
13505         case MVT::v8i16:
13506         case MVT::v4i64:
13507         case MVT::v8i32:
13508         case MVT::v16i16:
13509         case MVT::v16i32:
13510         case MVT::v8i64:
13511           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13512         }
13513       }
13514     }
13515   }
13516
13517   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13518   if (!Subtarget->is64Bit() &&
13519       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13520       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13521       Amt.getOpcode() == ISD::BITCAST &&
13522       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13523     Amt = Amt.getOperand(0);
13524     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13525                      VT.getVectorNumElements();
13526     std::vector<SDValue> Vals(Ratio);
13527     for (unsigned i = 0; i != Ratio; ++i)
13528       Vals[i] = Amt.getOperand(i);
13529     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13530       for (unsigned j = 0; j != Ratio; ++j)
13531         if (Vals[j] != Amt.getOperand(i + j))
13532           return SDValue();
13533     }
13534     switch (Op.getOpcode()) {
13535     default:
13536       llvm_unreachable("Unknown shift opcode!");
13537     case ISD::SHL:
13538       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13539     case ISD::SRL:
13540       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13541     case ISD::SRA:
13542       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13543     }
13544   }
13545
13546   return SDValue();
13547 }
13548
13549 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13550                           SelectionDAG &DAG) {
13551
13552   MVT VT = Op.getSimpleValueType();
13553   SDLoc dl(Op);
13554   SDValue R = Op.getOperand(0);
13555   SDValue Amt = Op.getOperand(1);
13556   SDValue V;
13557
13558   if (!Subtarget->hasSSE2())
13559     return SDValue();
13560
13561   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13562   if (V.getNode())
13563     return V;
13564
13565   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13566   if (V.getNode())
13567       return V;
13568
13569   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13570     return Op;
13571   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13572   if (Subtarget->hasInt256()) {
13573     if (Op.getOpcode() == ISD::SRL &&
13574         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13575          VT == MVT::v4i64 || VT == MVT::v8i32))
13576       return Op;
13577     if (Op.getOpcode() == ISD::SHL &&
13578         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13579          VT == MVT::v4i64 || VT == MVT::v8i32))
13580       return Op;
13581     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13582       return Op;
13583   }
13584
13585   // If possible, lower this packed shift into a vector multiply instead of
13586   // expanding it into a sequence of scalar shifts.
13587   // Do this only if the vector shift count is a constant build_vector.
13588   if (Op.getOpcode() == ISD::SHL && 
13589       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13590        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13591       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13592     SmallVector<SDValue, 8> Elts;
13593     EVT SVT = VT.getScalarType();
13594     unsigned SVTBits = SVT.getSizeInBits();
13595     const APInt &One = APInt(SVTBits, 1);
13596     unsigned NumElems = VT.getVectorNumElements();
13597
13598     for (unsigned i=0; i !=NumElems; ++i) {
13599       SDValue Op = Amt->getOperand(i);
13600       if (Op->getOpcode() == ISD::UNDEF) {
13601         Elts.push_back(Op);
13602         continue;
13603       }
13604
13605       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13606       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13607       uint64_t ShAmt = C.getZExtValue();
13608       if (ShAmt >= SVTBits) {
13609         Elts.push_back(DAG.getUNDEF(SVT));
13610         continue;
13611       }
13612       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13613     }
13614     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13615     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13616   }
13617
13618   // Lower SHL with variable shift amount.
13619   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13620     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13621
13622     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13623     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13624     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13625     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13626   }
13627
13628   // If possible, lower this shift as a sequence of two shifts by
13629   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13630   // Example:
13631   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13632   //
13633   // Could be rewritten as:
13634   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13635   //
13636   // The advantage is that the two shifts from the example would be
13637   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13638   // the vector shift into four scalar shifts plus four pairs of vector
13639   // insert/extract.
13640   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13641       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13642     unsigned TargetOpcode = X86ISD::MOVSS;
13643     bool CanBeSimplified;
13644     // The splat value for the first packed shift (the 'X' from the example).
13645     SDValue Amt1 = Amt->getOperand(0);
13646     // The splat value for the second packed shift (the 'Y' from the example).
13647     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13648                                         Amt->getOperand(2);
13649
13650     // See if it is possible to replace this node with a sequence of
13651     // two shifts followed by a MOVSS/MOVSD
13652     if (VT == MVT::v4i32) {
13653       // Check if it is legal to use a MOVSS.
13654       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13655                         Amt2 == Amt->getOperand(3);
13656       if (!CanBeSimplified) {
13657         // Otherwise, check if we can still simplify this node using a MOVSD.
13658         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13659                           Amt->getOperand(2) == Amt->getOperand(3);
13660         TargetOpcode = X86ISD::MOVSD;
13661         Amt2 = Amt->getOperand(2);
13662       }
13663     } else {
13664       // Do similar checks for the case where the machine value type
13665       // is MVT::v8i16.
13666       CanBeSimplified = Amt1 == Amt->getOperand(1);
13667       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13668         CanBeSimplified = Amt2 == Amt->getOperand(i);
13669
13670       if (!CanBeSimplified) {
13671         TargetOpcode = X86ISD::MOVSD;
13672         CanBeSimplified = true;
13673         Amt2 = Amt->getOperand(4);
13674         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13675           CanBeSimplified = Amt1 == Amt->getOperand(i);
13676         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13677           CanBeSimplified = Amt2 == Amt->getOperand(j);
13678       }
13679     }
13680     
13681     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13682         isa<ConstantSDNode>(Amt2)) {
13683       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13684       EVT CastVT = MVT::v4i32;
13685       SDValue Splat1 = 
13686         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13687       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13688       SDValue Splat2 = 
13689         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13690       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13691       if (TargetOpcode == X86ISD::MOVSD)
13692         CastVT = MVT::v2i64;
13693       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13694       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13695       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13696                                             BitCast1, DAG);
13697       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13698     }
13699   }
13700
13701   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13702     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13703
13704     // a = a << 5;
13705     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13706     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13707
13708     // Turn 'a' into a mask suitable for VSELECT
13709     SDValue VSelM = DAG.getConstant(0x80, VT);
13710     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13711     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13712
13713     SDValue CM1 = DAG.getConstant(0x0f, VT);
13714     SDValue CM2 = DAG.getConstant(0x3f, VT);
13715
13716     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13717     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13718     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13719     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13720     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13721
13722     // a += a
13723     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13724     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13725     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13726
13727     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13728     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13729     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13730     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13731     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13732
13733     // a += a
13734     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13735     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13736     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13737
13738     // return VSELECT(r, r+r, a);
13739     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13740                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13741     return R;
13742   }
13743
13744   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13745   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13746   // solution better.
13747   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13748     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13749     unsigned ExtOpc =
13750         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13751     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13752     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13753     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13754                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13755     }
13756
13757   // Decompose 256-bit shifts into smaller 128-bit shifts.
13758   if (VT.is256BitVector()) {
13759     unsigned NumElems = VT.getVectorNumElements();
13760     MVT EltVT = VT.getVectorElementType();
13761     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13762
13763     // Extract the two vectors
13764     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13765     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13766
13767     // Recreate the shift amount vectors
13768     SDValue Amt1, Amt2;
13769     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13770       // Constant shift amount
13771       SmallVector<SDValue, 4> Amt1Csts;
13772       SmallVector<SDValue, 4> Amt2Csts;
13773       for (unsigned i = 0; i != NumElems/2; ++i)
13774         Amt1Csts.push_back(Amt->getOperand(i));
13775       for (unsigned i = NumElems/2; i != NumElems; ++i)
13776         Amt2Csts.push_back(Amt->getOperand(i));
13777
13778       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13779       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13780     } else {
13781       // Variable shift amount
13782       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13783       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13784     }
13785
13786     // Issue new vector shifts for the smaller types
13787     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13788     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13789
13790     // Concatenate the result back
13791     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13792   }
13793
13794   return SDValue();
13795 }
13796
13797 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13798   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13799   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13800   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13801   // has only one use.
13802   SDNode *N = Op.getNode();
13803   SDValue LHS = N->getOperand(0);
13804   SDValue RHS = N->getOperand(1);
13805   unsigned BaseOp = 0;
13806   unsigned Cond = 0;
13807   SDLoc DL(Op);
13808   switch (Op.getOpcode()) {
13809   default: llvm_unreachable("Unknown ovf instruction!");
13810   case ISD::SADDO:
13811     // A subtract of one will be selected as a INC. Note that INC doesn't
13812     // set CF, so we can't do this for UADDO.
13813     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13814       if (C->isOne()) {
13815         BaseOp = X86ISD::INC;
13816         Cond = X86::COND_O;
13817         break;
13818       }
13819     BaseOp = X86ISD::ADD;
13820     Cond = X86::COND_O;
13821     break;
13822   case ISD::UADDO:
13823     BaseOp = X86ISD::ADD;
13824     Cond = X86::COND_B;
13825     break;
13826   case ISD::SSUBO:
13827     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13828     // set CF, so we can't do this for USUBO.
13829     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13830       if (C->isOne()) {
13831         BaseOp = X86ISD::DEC;
13832         Cond = X86::COND_O;
13833         break;
13834       }
13835     BaseOp = X86ISD::SUB;
13836     Cond = X86::COND_O;
13837     break;
13838   case ISD::USUBO:
13839     BaseOp = X86ISD::SUB;
13840     Cond = X86::COND_B;
13841     break;
13842   case ISD::SMULO:
13843     BaseOp = X86ISD::SMUL;
13844     Cond = X86::COND_O;
13845     break;
13846   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13847     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13848                                  MVT::i32);
13849     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13850
13851     SDValue SetCC =
13852       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13853                   DAG.getConstant(X86::COND_O, MVT::i32),
13854                   SDValue(Sum.getNode(), 2));
13855
13856     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13857   }
13858   }
13859
13860   // Also sets EFLAGS.
13861   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13862   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13863
13864   SDValue SetCC =
13865     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13866                 DAG.getConstant(Cond, MVT::i32),
13867                 SDValue(Sum.getNode(), 1));
13868
13869   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13870 }
13871
13872 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13873                                                   SelectionDAG &DAG) const {
13874   SDLoc dl(Op);
13875   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13876   MVT VT = Op.getSimpleValueType();
13877
13878   if (!Subtarget->hasSSE2() || !VT.isVector())
13879     return SDValue();
13880
13881   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13882                       ExtraVT.getScalarType().getSizeInBits();
13883
13884   switch (VT.SimpleTy) {
13885     default: return SDValue();
13886     case MVT::v8i32:
13887     case MVT::v16i16:
13888       if (!Subtarget->hasFp256())
13889         return SDValue();
13890       if (!Subtarget->hasInt256()) {
13891         // needs to be split
13892         unsigned NumElems = VT.getVectorNumElements();
13893
13894         // Extract the LHS vectors
13895         SDValue LHS = Op.getOperand(0);
13896         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13897         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13898
13899         MVT EltVT = VT.getVectorElementType();
13900         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13901
13902         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13903         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13904         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13905                                    ExtraNumElems/2);
13906         SDValue Extra = DAG.getValueType(ExtraVT);
13907
13908         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13909         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13910
13911         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13912       }
13913       // fall through
13914     case MVT::v4i32:
13915     case MVT::v8i16: {
13916       SDValue Op0 = Op.getOperand(0);
13917       SDValue Op00 = Op0.getOperand(0);
13918       SDValue Tmp1;
13919       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13920       if (Op0.getOpcode() == ISD::BITCAST &&
13921           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13922         // (sext (vzext x)) -> (vsext x)
13923         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13924         if (Tmp1.getNode()) {
13925           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13926           // This folding is only valid when the in-reg type is a vector of i8,
13927           // i16, or i32.
13928           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13929               ExtraEltVT == MVT::i32) {
13930             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13931             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13932                    "This optimization is invalid without a VZEXT.");
13933             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13934           }
13935           Op0 = Tmp1;
13936         }
13937       }
13938
13939       // If the above didn't work, then just use Shift-Left + Shift-Right.
13940       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13941                                         DAG);
13942       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13943                                         DAG);
13944     }
13945   }
13946 }
13947
13948 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13949                                  SelectionDAG &DAG) {
13950   SDLoc dl(Op);
13951   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13952     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13953   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13954     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13955
13956   // The only fence that needs an instruction is a sequentially-consistent
13957   // cross-thread fence.
13958   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13959     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13960     // no-sse2). There isn't any reason to disable it if the target processor
13961     // supports it.
13962     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13963       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13964
13965     SDValue Chain = Op.getOperand(0);
13966     SDValue Zero = DAG.getConstant(0, MVT::i32);
13967     SDValue Ops[] = {
13968       DAG.getRegister(X86::ESP, MVT::i32), // Base
13969       DAG.getTargetConstant(1, MVT::i8),   // Scale
13970       DAG.getRegister(0, MVT::i32),        // Index
13971       DAG.getTargetConstant(0, MVT::i32),  // Disp
13972       DAG.getRegister(0, MVT::i32),        // Segment.
13973       Zero,
13974       Chain
13975     };
13976     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13977     return SDValue(Res, 0);
13978   }
13979
13980   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13981   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13982 }
13983
13984 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13985                              SelectionDAG &DAG) {
13986   MVT T = Op.getSimpleValueType();
13987   SDLoc DL(Op);
13988   unsigned Reg = 0;
13989   unsigned size = 0;
13990   switch(T.SimpleTy) {
13991   default: llvm_unreachable("Invalid value type!");
13992   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13993   case MVT::i16: Reg = X86::AX;  size = 2; break;
13994   case MVT::i32: Reg = X86::EAX; size = 4; break;
13995   case MVT::i64:
13996     assert(Subtarget->is64Bit() && "Node not type legal!");
13997     Reg = X86::RAX; size = 8;
13998     break;
13999   }
14000   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14001                                     Op.getOperand(2), SDValue());
14002   SDValue Ops[] = { cpIn.getValue(0),
14003                     Op.getOperand(1),
14004                     Op.getOperand(3),
14005                     DAG.getTargetConstant(size, MVT::i8),
14006                     cpIn.getValue(1) };
14007   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14008   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14009   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14010                                            Ops, T, MMO);
14011   SDValue cpOut =
14012     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14013   return cpOut;
14014 }
14015
14016 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14017                             SelectionDAG &DAG) {
14018   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14019   MVT DstVT = Op.getSimpleValueType();
14020   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14021          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14022   assert((DstVT == MVT::i64 ||
14023           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14024          "Unexpected custom BITCAST");
14025   // i64 <=> MMX conversions are Legal.
14026   if (SrcVT==MVT::i64 && DstVT.isVector())
14027     return Op;
14028   if (DstVT==MVT::i64 && SrcVT.isVector())
14029     return Op;
14030   // MMX <=> MMX conversions are Legal.
14031   if (SrcVT.isVector() && DstVT.isVector())
14032     return Op;
14033   // All other conversions need to be expanded.
14034   return SDValue();
14035 }
14036
14037 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14038   SDNode *Node = Op.getNode();
14039   SDLoc dl(Node);
14040   EVT T = Node->getValueType(0);
14041   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14042                               DAG.getConstant(0, T), Node->getOperand(2));
14043   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14044                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14045                        Node->getOperand(0),
14046                        Node->getOperand(1), negOp,
14047                        cast<AtomicSDNode>(Node)->getMemOperand(),
14048                        cast<AtomicSDNode>(Node)->getOrdering(),
14049                        cast<AtomicSDNode>(Node)->getSynchScope());
14050 }
14051
14052 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14053   SDNode *Node = Op.getNode();
14054   SDLoc dl(Node);
14055   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14056
14057   // Convert seq_cst store -> xchg
14058   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14059   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14060   //        (The only way to get a 16-byte store is cmpxchg16b)
14061   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14062   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14063       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14064     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14065                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14066                                  Node->getOperand(0),
14067                                  Node->getOperand(1), Node->getOperand(2),
14068                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14069                                  cast<AtomicSDNode>(Node)->getOrdering(),
14070                                  cast<AtomicSDNode>(Node)->getSynchScope());
14071     return Swap.getValue(1);
14072   }
14073   // Other atomic stores have a simple pattern.
14074   return Op;
14075 }
14076
14077 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14078   EVT VT = Op.getNode()->getSimpleValueType(0);
14079
14080   // Let legalize expand this if it isn't a legal type yet.
14081   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14082     return SDValue();
14083
14084   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14085
14086   unsigned Opc;
14087   bool ExtraOp = false;
14088   switch (Op.getOpcode()) {
14089   default: llvm_unreachable("Invalid code");
14090   case ISD::ADDC: Opc = X86ISD::ADD; break;
14091   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14092   case ISD::SUBC: Opc = X86ISD::SUB; break;
14093   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14094   }
14095
14096   if (!ExtraOp)
14097     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14098                        Op.getOperand(1));
14099   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14100                      Op.getOperand(1), Op.getOperand(2));
14101 }
14102
14103 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14104                             SelectionDAG &DAG) {
14105   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14106
14107   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14108   // which returns the values as { float, float } (in XMM0) or
14109   // { double, double } (which is returned in XMM0, XMM1).
14110   SDLoc dl(Op);
14111   SDValue Arg = Op.getOperand(0);
14112   EVT ArgVT = Arg.getValueType();
14113   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14114
14115   TargetLowering::ArgListTy Args;
14116   TargetLowering::ArgListEntry Entry;
14117
14118   Entry.Node = Arg;
14119   Entry.Ty = ArgTy;
14120   Entry.isSExt = false;
14121   Entry.isZExt = false;
14122   Args.push_back(Entry);
14123
14124   bool isF64 = ArgVT == MVT::f64;
14125   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14126   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14127   // the results are returned via SRet in memory.
14128   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14130   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14131
14132   Type *RetTy = isF64
14133     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14134     : (Type*)VectorType::get(ArgTy, 4);
14135   TargetLowering::
14136     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14137                          false, false, false, false, 0,
14138                          CallingConv::C, /*isTaillCall=*/false,
14139                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14140                          Callee, Args, DAG, dl);
14141   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14142
14143   if (isF64)
14144     // Returned in xmm0 and xmm1.
14145     return CallResult.first;
14146
14147   // Returned in bits 0:31 and 32:64 xmm0.
14148   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14149                                CallResult.first, DAG.getIntPtrConstant(0));
14150   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14151                                CallResult.first, DAG.getIntPtrConstant(1));
14152   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14153   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14154 }
14155
14156 /// LowerOperation - Provide custom lowering hooks for some operations.
14157 ///
14158 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14159   switch (Op.getOpcode()) {
14160   default: llvm_unreachable("Should not custom lower this!");
14161   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14162   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14163   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14164   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14165   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14166   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14167   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14168   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14169   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14170   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14171   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14172   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14173   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14174   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14175   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14176   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14177   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14178   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14179   case ISD::SHL_PARTS:
14180   case ISD::SRA_PARTS:
14181   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14182   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14183   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14184   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14185   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14186   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14187   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14188   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14189   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14190   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14191   case ISD::FABS:               return LowerFABS(Op, DAG);
14192   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14193   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14194   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14195   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14196   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14197   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14198   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14199   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14200   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14201   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14202   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14203   case ISD::INTRINSIC_VOID:
14204   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14205   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14206   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14207   case ISD::FRAME_TO_ARGS_OFFSET:
14208                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14209   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14210   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14211   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14212   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14213   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14214   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14215   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14216   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14217   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14218   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14219   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14220   case ISD::UMUL_LOHI:
14221   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14222   case ISD::SRA:
14223   case ISD::SRL:
14224   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14225   case ISD::SADDO:
14226   case ISD::UADDO:
14227   case ISD::SSUBO:
14228   case ISD::USUBO:
14229   case ISD::SMULO:
14230   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14231   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14232   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14233   case ISD::ADDC:
14234   case ISD::ADDE:
14235   case ISD::SUBC:
14236   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14237   case ISD::ADD:                return LowerADD(Op, DAG);
14238   case ISD::SUB:                return LowerSUB(Op, DAG);
14239   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14240   }
14241 }
14242
14243 static void ReplaceATOMIC_LOAD(SDNode *Node,
14244                                   SmallVectorImpl<SDValue> &Results,
14245                                   SelectionDAG &DAG) {
14246   SDLoc dl(Node);
14247   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14248
14249   // Convert wide load -> cmpxchg8b/cmpxchg16b
14250   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14251   //        (The only way to get a 16-byte load is cmpxchg16b)
14252   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14253   SDValue Zero = DAG.getConstant(0, VT);
14254   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14255                                Node->getOperand(0),
14256                                Node->getOperand(1), Zero, Zero,
14257                                cast<AtomicSDNode>(Node)->getMemOperand(),
14258                                cast<AtomicSDNode>(Node)->getOrdering(),
14259                                cast<AtomicSDNode>(Node)->getOrdering(),
14260                                cast<AtomicSDNode>(Node)->getSynchScope());
14261   Results.push_back(Swap.getValue(0));
14262   Results.push_back(Swap.getValue(1));
14263 }
14264
14265 static void
14266 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14267                         SelectionDAG &DAG, unsigned NewOp) {
14268   SDLoc dl(Node);
14269   assert (Node->getValueType(0) == MVT::i64 &&
14270           "Only know how to expand i64 atomics");
14271
14272   SDValue Chain = Node->getOperand(0);
14273   SDValue In1 = Node->getOperand(1);
14274   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14275                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14276   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14277                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14278   SDValue Ops[] = { Chain, In1, In2L, In2H };
14279   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14280   SDValue Result =
14281     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14282                             cast<MemSDNode>(Node)->getMemOperand());
14283   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14284   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14285   Results.push_back(Result.getValue(2));
14286 }
14287
14288 /// ReplaceNodeResults - Replace a node with an illegal result type
14289 /// with a new node built out of custom code.
14290 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14291                                            SmallVectorImpl<SDValue>&Results,
14292                                            SelectionDAG &DAG) const {
14293   SDLoc dl(N);
14294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14295   switch (N->getOpcode()) {
14296   default:
14297     llvm_unreachable("Do not know how to custom type legalize this operation!");
14298   case ISD::SIGN_EXTEND_INREG:
14299   case ISD::ADDC:
14300   case ISD::ADDE:
14301   case ISD::SUBC:
14302   case ISD::SUBE:
14303     // We don't want to expand or promote these.
14304     return;
14305   case ISD::FP_TO_SINT:
14306   case ISD::FP_TO_UINT: {
14307     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14308
14309     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14310       return;
14311
14312     std::pair<SDValue,SDValue> Vals =
14313         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14314     SDValue FIST = Vals.first, StackSlot = Vals.second;
14315     if (FIST.getNode()) {
14316       EVT VT = N->getValueType(0);
14317       // Return a load from the stack slot.
14318       if (StackSlot.getNode())
14319         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14320                                       MachinePointerInfo(),
14321                                       false, false, false, 0));
14322       else
14323         Results.push_back(FIST);
14324     }
14325     return;
14326   }
14327   case ISD::UINT_TO_FP: {
14328     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14329     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14330         N->getValueType(0) != MVT::v2f32)
14331       return;
14332     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14333                                  N->getOperand(0));
14334     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14335                                      MVT::f64);
14336     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14337     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14338                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14339     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14340     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14341     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14342     return;
14343   }
14344   case ISD::FP_ROUND: {
14345     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14346         return;
14347     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14348     Results.push_back(V);
14349     return;
14350   }
14351   case ISD::INTRINSIC_W_CHAIN: {
14352     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14353     switch (IntNo) {
14354     default : llvm_unreachable("Do not know how to custom type "
14355                                "legalize this intrinsic operation!");
14356     case Intrinsic::x86_rdtsc:
14357       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14358                                      Results);
14359     case Intrinsic::x86_rdtscp:
14360       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14361                                      Results);
14362     }
14363   }
14364   case ISD::READCYCLECOUNTER: {
14365     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14366                                    Results);
14367   }
14368   case ISD::ATOMIC_CMP_SWAP: {
14369     EVT T = N->getValueType(0);
14370     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14371     bool Regs64bit = T == MVT::i128;
14372     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14373     SDValue cpInL, cpInH;
14374     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14375                         DAG.getConstant(0, HalfT));
14376     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14377                         DAG.getConstant(1, HalfT));
14378     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14379                              Regs64bit ? X86::RAX : X86::EAX,
14380                              cpInL, SDValue());
14381     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14382                              Regs64bit ? X86::RDX : X86::EDX,
14383                              cpInH, cpInL.getValue(1));
14384     SDValue swapInL, swapInH;
14385     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14386                           DAG.getConstant(0, HalfT));
14387     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14388                           DAG.getConstant(1, HalfT));
14389     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14390                                Regs64bit ? X86::RBX : X86::EBX,
14391                                swapInL, cpInH.getValue(1));
14392     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14393                                Regs64bit ? X86::RCX : X86::ECX,
14394                                swapInH, swapInL.getValue(1));
14395     SDValue Ops[] = { swapInH.getValue(0),
14396                       N->getOperand(1),
14397                       swapInH.getValue(1) };
14398     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14399     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14400     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14401                                   X86ISD::LCMPXCHG8_DAG;
14402     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14403     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14404                                         Regs64bit ? X86::RAX : X86::EAX,
14405                                         HalfT, Result.getValue(1));
14406     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14407                                         Regs64bit ? X86::RDX : X86::EDX,
14408                                         HalfT, cpOutL.getValue(2));
14409     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14410     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14411     Results.push_back(cpOutH.getValue(1));
14412     return;
14413   }
14414   case ISD::ATOMIC_LOAD_ADD:
14415   case ISD::ATOMIC_LOAD_AND:
14416   case ISD::ATOMIC_LOAD_NAND:
14417   case ISD::ATOMIC_LOAD_OR:
14418   case ISD::ATOMIC_LOAD_SUB:
14419   case ISD::ATOMIC_LOAD_XOR:
14420   case ISD::ATOMIC_LOAD_MAX:
14421   case ISD::ATOMIC_LOAD_MIN:
14422   case ISD::ATOMIC_LOAD_UMAX:
14423   case ISD::ATOMIC_LOAD_UMIN:
14424   case ISD::ATOMIC_SWAP: {
14425     unsigned Opc;
14426     switch (N->getOpcode()) {
14427     default: llvm_unreachable("Unexpected opcode");
14428     case ISD::ATOMIC_LOAD_ADD:
14429       Opc = X86ISD::ATOMADD64_DAG;
14430       break;
14431     case ISD::ATOMIC_LOAD_AND:
14432       Opc = X86ISD::ATOMAND64_DAG;
14433       break;
14434     case ISD::ATOMIC_LOAD_NAND:
14435       Opc = X86ISD::ATOMNAND64_DAG;
14436       break;
14437     case ISD::ATOMIC_LOAD_OR:
14438       Opc = X86ISD::ATOMOR64_DAG;
14439       break;
14440     case ISD::ATOMIC_LOAD_SUB:
14441       Opc = X86ISD::ATOMSUB64_DAG;
14442       break;
14443     case ISD::ATOMIC_LOAD_XOR:
14444       Opc = X86ISD::ATOMXOR64_DAG;
14445       break;
14446     case ISD::ATOMIC_LOAD_MAX:
14447       Opc = X86ISD::ATOMMAX64_DAG;
14448       break;
14449     case ISD::ATOMIC_LOAD_MIN:
14450       Opc = X86ISD::ATOMMIN64_DAG;
14451       break;
14452     case ISD::ATOMIC_LOAD_UMAX:
14453       Opc = X86ISD::ATOMUMAX64_DAG;
14454       break;
14455     case ISD::ATOMIC_LOAD_UMIN:
14456       Opc = X86ISD::ATOMUMIN64_DAG;
14457       break;
14458     case ISD::ATOMIC_SWAP:
14459       Opc = X86ISD::ATOMSWAP64_DAG;
14460       break;
14461     }
14462     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14463     return;
14464   }
14465   case ISD::ATOMIC_LOAD:
14466     ReplaceATOMIC_LOAD(N, Results, DAG);
14467   }
14468 }
14469
14470 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14471   switch (Opcode) {
14472   default: return nullptr;
14473   case X86ISD::BSF:                return "X86ISD::BSF";
14474   case X86ISD::BSR:                return "X86ISD::BSR";
14475   case X86ISD::SHLD:               return "X86ISD::SHLD";
14476   case X86ISD::SHRD:               return "X86ISD::SHRD";
14477   case X86ISD::FAND:               return "X86ISD::FAND";
14478   case X86ISD::FANDN:              return "X86ISD::FANDN";
14479   case X86ISD::FOR:                return "X86ISD::FOR";
14480   case X86ISD::FXOR:               return "X86ISD::FXOR";
14481   case X86ISD::FSRL:               return "X86ISD::FSRL";
14482   case X86ISD::FILD:               return "X86ISD::FILD";
14483   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14484   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14485   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14486   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14487   case X86ISD::FLD:                return "X86ISD::FLD";
14488   case X86ISD::FST:                return "X86ISD::FST";
14489   case X86ISD::CALL:               return "X86ISD::CALL";
14490   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14491   case X86ISD::BT:                 return "X86ISD::BT";
14492   case X86ISD::CMP:                return "X86ISD::CMP";
14493   case X86ISD::COMI:               return "X86ISD::COMI";
14494   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14495   case X86ISD::CMPM:               return "X86ISD::CMPM";
14496   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14497   case X86ISD::SETCC:              return "X86ISD::SETCC";
14498   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14499   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14500   case X86ISD::CMOV:               return "X86ISD::CMOV";
14501   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14502   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14503   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14504   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14505   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14506   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14507   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14508   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14509   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14510   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14511   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14512   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14513   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14514   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14515   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14516   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14517   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14518   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14519   case X86ISD::HADD:               return "X86ISD::HADD";
14520   case X86ISD::HSUB:               return "X86ISD::HSUB";
14521   case X86ISD::FHADD:              return "X86ISD::FHADD";
14522   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14523   case X86ISD::UMAX:               return "X86ISD::UMAX";
14524   case X86ISD::UMIN:               return "X86ISD::UMIN";
14525   case X86ISD::SMAX:               return "X86ISD::SMAX";
14526   case X86ISD::SMIN:               return "X86ISD::SMIN";
14527   case X86ISD::FMAX:               return "X86ISD::FMAX";
14528   case X86ISD::FMIN:               return "X86ISD::FMIN";
14529   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14530   case X86ISD::FMINC:              return "X86ISD::FMINC";
14531   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14532   case X86ISD::FRCP:               return "X86ISD::FRCP";
14533   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14534   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14535   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14536   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14537   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14538   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14539   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14540   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14541   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14542   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14543   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14544   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14545   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14546   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14547   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14548   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14549   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14550   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14551   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14552   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14553   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14554   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14555   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14556   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14557   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14558   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14559   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14560   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14561   case X86ISD::VSHL:               return "X86ISD::VSHL";
14562   case X86ISD::VSRL:               return "X86ISD::VSRL";
14563   case X86ISD::VSRA:               return "X86ISD::VSRA";
14564   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14565   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14566   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14567   case X86ISD::CMPP:               return "X86ISD::CMPP";
14568   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14569   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14570   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14571   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14572   case X86ISD::ADD:                return "X86ISD::ADD";
14573   case X86ISD::SUB:                return "X86ISD::SUB";
14574   case X86ISD::ADC:                return "X86ISD::ADC";
14575   case X86ISD::SBB:                return "X86ISD::SBB";
14576   case X86ISD::SMUL:               return "X86ISD::SMUL";
14577   case X86ISD::UMUL:               return "X86ISD::UMUL";
14578   case X86ISD::INC:                return "X86ISD::INC";
14579   case X86ISD::DEC:                return "X86ISD::DEC";
14580   case X86ISD::OR:                 return "X86ISD::OR";
14581   case X86ISD::XOR:                return "X86ISD::XOR";
14582   case X86ISD::AND:                return "X86ISD::AND";
14583   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14584   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14585   case X86ISD::PTEST:              return "X86ISD::PTEST";
14586   case X86ISD::TESTP:              return "X86ISD::TESTP";
14587   case X86ISD::TESTM:              return "X86ISD::TESTM";
14588   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14589   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14590   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14591   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14592   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14593   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14594   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14595   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14596   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14597   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14598   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14599   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14600   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14601   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14602   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14603   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14604   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14605   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14606   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14607   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14608   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14609   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14610   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14611   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14612   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14613   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14614   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14615   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14616   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14617   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14618   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14619   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14620   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14621   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14622   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14623   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14624   case X86ISD::SAHF:               return "X86ISD::SAHF";
14625   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14626   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14627   case X86ISD::FMADD:              return "X86ISD::FMADD";
14628   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14629   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14630   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14631   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14632   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14633   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14634   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14635   case X86ISD::XTEST:              return "X86ISD::XTEST";
14636   }
14637 }
14638
14639 // isLegalAddressingMode - Return true if the addressing mode represented
14640 // by AM is legal for this target, for a load/store of the specified type.
14641 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14642                                               Type *Ty) const {
14643   // X86 supports extremely general addressing modes.
14644   CodeModel::Model M = getTargetMachine().getCodeModel();
14645   Reloc::Model R = getTargetMachine().getRelocationModel();
14646
14647   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14648   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14649     return false;
14650
14651   if (AM.BaseGV) {
14652     unsigned GVFlags =
14653       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14654
14655     // If a reference to this global requires an extra load, we can't fold it.
14656     if (isGlobalStubReference(GVFlags))
14657       return false;
14658
14659     // If BaseGV requires a register for the PIC base, we cannot also have a
14660     // BaseReg specified.
14661     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14662       return false;
14663
14664     // If lower 4G is not available, then we must use rip-relative addressing.
14665     if ((M != CodeModel::Small || R != Reloc::Static) &&
14666         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14667       return false;
14668   }
14669
14670   switch (AM.Scale) {
14671   case 0:
14672   case 1:
14673   case 2:
14674   case 4:
14675   case 8:
14676     // These scales always work.
14677     break;
14678   case 3:
14679   case 5:
14680   case 9:
14681     // These scales are formed with basereg+scalereg.  Only accept if there is
14682     // no basereg yet.
14683     if (AM.HasBaseReg)
14684       return false;
14685     break;
14686   default:  // Other stuff never works.
14687     return false;
14688   }
14689
14690   return true;
14691 }
14692
14693 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14694   unsigned Bits = Ty->getScalarSizeInBits();
14695
14696   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14697   // particularly cheaper than those without.
14698   if (Bits == 8)
14699     return false;
14700
14701   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14702   // variable shifts just as cheap as scalar ones.
14703   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14704     return false;
14705
14706   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14707   // fully general vector.
14708   return true;
14709 }
14710
14711 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14712   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14713     return false;
14714   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14715   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14716   return NumBits1 > NumBits2;
14717 }
14718
14719 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14720   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14721     return false;
14722
14723   if (!isTypeLegal(EVT::getEVT(Ty1)))
14724     return false;
14725
14726   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14727
14728   // Assuming the caller doesn't have a zeroext or signext return parameter,
14729   // truncation all the way down to i1 is valid.
14730   return true;
14731 }
14732
14733 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14734   return isInt<32>(Imm);
14735 }
14736
14737 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14738   // Can also use sub to handle negated immediates.
14739   return isInt<32>(Imm);
14740 }
14741
14742 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14743   if (!VT1.isInteger() || !VT2.isInteger())
14744     return false;
14745   unsigned NumBits1 = VT1.getSizeInBits();
14746   unsigned NumBits2 = VT2.getSizeInBits();
14747   return NumBits1 > NumBits2;
14748 }
14749
14750 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14751   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14752   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14753 }
14754
14755 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14756   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14757   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14758 }
14759
14760 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14761   EVT VT1 = Val.getValueType();
14762   if (isZExtFree(VT1, VT2))
14763     return true;
14764
14765   if (Val.getOpcode() != ISD::LOAD)
14766     return false;
14767
14768   if (!VT1.isSimple() || !VT1.isInteger() ||
14769       !VT2.isSimple() || !VT2.isInteger())
14770     return false;
14771
14772   switch (VT1.getSimpleVT().SimpleTy) {
14773   default: break;
14774   case MVT::i8:
14775   case MVT::i16:
14776   case MVT::i32:
14777     // X86 has 8, 16, and 32-bit zero-extending loads.
14778     return true;
14779   }
14780
14781   return false;
14782 }
14783
14784 bool
14785 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14786   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14787     return false;
14788
14789   VT = VT.getScalarType();
14790
14791   if (!VT.isSimple())
14792     return false;
14793
14794   switch (VT.getSimpleVT().SimpleTy) {
14795   case MVT::f32:
14796   case MVT::f64:
14797     return true;
14798   default:
14799     break;
14800   }
14801
14802   return false;
14803 }
14804
14805 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14806   // i16 instructions are longer (0x66 prefix) and potentially slower.
14807   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14808 }
14809
14810 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14811 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14812 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14813 /// are assumed to be legal.
14814 bool
14815 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14816                                       EVT VT) const {
14817   if (!VT.isSimple())
14818     return false;
14819
14820   MVT SVT = VT.getSimpleVT();
14821
14822   // Very little shuffling can be done for 64-bit vectors right now.
14823   if (VT.getSizeInBits() == 64)
14824     return false;
14825
14826   // FIXME: pshufb, blends, shifts.
14827   return (SVT.getVectorNumElements() == 2 ||
14828           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14829           isMOVLMask(M, SVT) ||
14830           isSHUFPMask(M, SVT) ||
14831           isPSHUFDMask(M, SVT) ||
14832           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14833           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14834           isPALIGNRMask(M, SVT, Subtarget) ||
14835           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14836           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14837           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14838           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14839 }
14840
14841 bool
14842 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14843                                           EVT VT) const {
14844   if (!VT.isSimple())
14845     return false;
14846
14847   MVT SVT = VT.getSimpleVT();
14848   unsigned NumElts = SVT.getVectorNumElements();
14849   // FIXME: This collection of masks seems suspect.
14850   if (NumElts == 2)
14851     return true;
14852   if (NumElts == 4 && SVT.is128BitVector()) {
14853     return (isMOVLMask(Mask, SVT)  ||
14854             isCommutedMOVLMask(Mask, SVT, true) ||
14855             isSHUFPMask(Mask, SVT) ||
14856             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14857   }
14858   return false;
14859 }
14860
14861 //===----------------------------------------------------------------------===//
14862 //                           X86 Scheduler Hooks
14863 //===----------------------------------------------------------------------===//
14864
14865 /// Utility function to emit xbegin specifying the start of an RTM region.
14866 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14867                                      const TargetInstrInfo *TII) {
14868   DebugLoc DL = MI->getDebugLoc();
14869
14870   const BasicBlock *BB = MBB->getBasicBlock();
14871   MachineFunction::iterator I = MBB;
14872   ++I;
14873
14874   // For the v = xbegin(), we generate
14875   //
14876   // thisMBB:
14877   //  xbegin sinkMBB
14878   //
14879   // mainMBB:
14880   //  eax = -1
14881   //
14882   // sinkMBB:
14883   //  v = eax
14884
14885   MachineBasicBlock *thisMBB = MBB;
14886   MachineFunction *MF = MBB->getParent();
14887   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14888   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14889   MF->insert(I, mainMBB);
14890   MF->insert(I, sinkMBB);
14891
14892   // Transfer the remainder of BB and its successor edges to sinkMBB.
14893   sinkMBB->splice(sinkMBB->begin(), MBB,
14894                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14895   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14896
14897   // thisMBB:
14898   //  xbegin sinkMBB
14899   //  # fallthrough to mainMBB
14900   //  # abortion to sinkMBB
14901   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14902   thisMBB->addSuccessor(mainMBB);
14903   thisMBB->addSuccessor(sinkMBB);
14904
14905   // mainMBB:
14906   //  EAX = -1
14907   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14908   mainMBB->addSuccessor(sinkMBB);
14909
14910   // sinkMBB:
14911   // EAX is live into the sinkMBB
14912   sinkMBB->addLiveIn(X86::EAX);
14913   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14914           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14915     .addReg(X86::EAX);
14916
14917   MI->eraseFromParent();
14918   return sinkMBB;
14919 }
14920
14921 // Get CMPXCHG opcode for the specified data type.
14922 static unsigned getCmpXChgOpcode(EVT VT) {
14923   switch (VT.getSimpleVT().SimpleTy) {
14924   case MVT::i8:  return X86::LCMPXCHG8;
14925   case MVT::i16: return X86::LCMPXCHG16;
14926   case MVT::i32: return X86::LCMPXCHG32;
14927   case MVT::i64: return X86::LCMPXCHG64;
14928   default:
14929     break;
14930   }
14931   llvm_unreachable("Invalid operand size!");
14932 }
14933
14934 // Get LOAD opcode for the specified data type.
14935 static unsigned getLoadOpcode(EVT VT) {
14936   switch (VT.getSimpleVT().SimpleTy) {
14937   case MVT::i8:  return X86::MOV8rm;
14938   case MVT::i16: return X86::MOV16rm;
14939   case MVT::i32: return X86::MOV32rm;
14940   case MVT::i64: return X86::MOV64rm;
14941   default:
14942     break;
14943   }
14944   llvm_unreachable("Invalid operand size!");
14945 }
14946
14947 // Get opcode of the non-atomic one from the specified atomic instruction.
14948 static unsigned getNonAtomicOpcode(unsigned Opc) {
14949   switch (Opc) {
14950   case X86::ATOMAND8:  return X86::AND8rr;
14951   case X86::ATOMAND16: return X86::AND16rr;
14952   case X86::ATOMAND32: return X86::AND32rr;
14953   case X86::ATOMAND64: return X86::AND64rr;
14954   case X86::ATOMOR8:   return X86::OR8rr;
14955   case X86::ATOMOR16:  return X86::OR16rr;
14956   case X86::ATOMOR32:  return X86::OR32rr;
14957   case X86::ATOMOR64:  return X86::OR64rr;
14958   case X86::ATOMXOR8:  return X86::XOR8rr;
14959   case X86::ATOMXOR16: return X86::XOR16rr;
14960   case X86::ATOMXOR32: return X86::XOR32rr;
14961   case X86::ATOMXOR64: return X86::XOR64rr;
14962   }
14963   llvm_unreachable("Unhandled atomic-load-op opcode!");
14964 }
14965
14966 // Get opcode of the non-atomic one from the specified atomic instruction with
14967 // extra opcode.
14968 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14969                                                unsigned &ExtraOpc) {
14970   switch (Opc) {
14971   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14972   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14973   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14974   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14975   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14976   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14977   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14978   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14979   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14980   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14981   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14982   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14983   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14984   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14985   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14986   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14987   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14988   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14989   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14990   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14991   }
14992   llvm_unreachable("Unhandled atomic-load-op opcode!");
14993 }
14994
14995 // Get opcode of the non-atomic one from the specified atomic instruction for
14996 // 64-bit data type on 32-bit target.
14997 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14998   switch (Opc) {
14999   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15000   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15001   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15002   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15003   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15004   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15005   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15006   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15007   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15008   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15009   }
15010   llvm_unreachable("Unhandled atomic-load-op opcode!");
15011 }
15012
15013 // Get opcode of the non-atomic one from the specified atomic instruction for
15014 // 64-bit data type on 32-bit target with extra opcode.
15015 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15016                                                    unsigned &HiOpc,
15017                                                    unsigned &ExtraOpc) {
15018   switch (Opc) {
15019   case X86::ATOMNAND6432:
15020     ExtraOpc = X86::NOT32r;
15021     HiOpc = X86::AND32rr;
15022     return X86::AND32rr;
15023   }
15024   llvm_unreachable("Unhandled atomic-load-op opcode!");
15025 }
15026
15027 // Get pseudo CMOV opcode from the specified data type.
15028 static unsigned getPseudoCMOVOpc(EVT VT) {
15029   switch (VT.getSimpleVT().SimpleTy) {
15030   case MVT::i8:  return X86::CMOV_GR8;
15031   case MVT::i16: return X86::CMOV_GR16;
15032   case MVT::i32: return X86::CMOV_GR32;
15033   default:
15034     break;
15035   }
15036   llvm_unreachable("Unknown CMOV opcode!");
15037 }
15038
15039 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15040 // They will be translated into a spin-loop or compare-exchange loop from
15041 //
15042 //    ...
15043 //    dst = atomic-fetch-op MI.addr, MI.val
15044 //    ...
15045 //
15046 // to
15047 //
15048 //    ...
15049 //    t1 = LOAD MI.addr
15050 // loop:
15051 //    t4 = phi(t1, t3 / loop)
15052 //    t2 = OP MI.val, t4
15053 //    EAX = t4
15054 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15055 //    t3 = EAX
15056 //    JNE loop
15057 // sink:
15058 //    dst = t3
15059 //    ...
15060 MachineBasicBlock *
15061 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15062                                        MachineBasicBlock *MBB) const {
15063   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15064   DebugLoc DL = MI->getDebugLoc();
15065
15066   MachineFunction *MF = MBB->getParent();
15067   MachineRegisterInfo &MRI = MF->getRegInfo();
15068
15069   const BasicBlock *BB = MBB->getBasicBlock();
15070   MachineFunction::iterator I = MBB;
15071   ++I;
15072
15073   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15074          "Unexpected number of operands");
15075
15076   assert(MI->hasOneMemOperand() &&
15077          "Expected atomic-load-op to have one memoperand");
15078
15079   // Memory Reference
15080   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15081   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15082
15083   unsigned DstReg, SrcReg;
15084   unsigned MemOpndSlot;
15085
15086   unsigned CurOp = 0;
15087
15088   DstReg = MI->getOperand(CurOp++).getReg();
15089   MemOpndSlot = CurOp;
15090   CurOp += X86::AddrNumOperands;
15091   SrcReg = MI->getOperand(CurOp++).getReg();
15092
15093   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15094   MVT::SimpleValueType VT = *RC->vt_begin();
15095   unsigned t1 = MRI.createVirtualRegister(RC);
15096   unsigned t2 = MRI.createVirtualRegister(RC);
15097   unsigned t3 = MRI.createVirtualRegister(RC);
15098   unsigned t4 = MRI.createVirtualRegister(RC);
15099   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15100
15101   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15102   unsigned LOADOpc = getLoadOpcode(VT);
15103
15104   // For the atomic load-arith operator, we generate
15105   //
15106   //  thisMBB:
15107   //    t1 = LOAD [MI.addr]
15108   //  mainMBB:
15109   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15110   //    t1 = OP MI.val, EAX
15111   //    EAX = t4
15112   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15113   //    t3 = EAX
15114   //    JNE mainMBB
15115   //  sinkMBB:
15116   //    dst = t3
15117
15118   MachineBasicBlock *thisMBB = MBB;
15119   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15120   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15121   MF->insert(I, mainMBB);
15122   MF->insert(I, sinkMBB);
15123
15124   MachineInstrBuilder MIB;
15125
15126   // Transfer the remainder of BB and its successor edges to sinkMBB.
15127   sinkMBB->splice(sinkMBB->begin(), MBB,
15128                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15129   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15130
15131   // thisMBB:
15132   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15133   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15134     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15135     if (NewMO.isReg())
15136       NewMO.setIsKill(false);
15137     MIB.addOperand(NewMO);
15138   }
15139   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15140     unsigned flags = (*MMOI)->getFlags();
15141     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15142     MachineMemOperand *MMO =
15143       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15144                                (*MMOI)->getSize(),
15145                                (*MMOI)->getBaseAlignment(),
15146                                (*MMOI)->getTBAAInfo(),
15147                                (*MMOI)->getRanges());
15148     MIB.addMemOperand(MMO);
15149   }
15150
15151   thisMBB->addSuccessor(mainMBB);
15152
15153   // mainMBB:
15154   MachineBasicBlock *origMainMBB = mainMBB;
15155
15156   // Add a PHI.
15157   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15158                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15159
15160   unsigned Opc = MI->getOpcode();
15161   switch (Opc) {
15162   default:
15163     llvm_unreachable("Unhandled atomic-load-op opcode!");
15164   case X86::ATOMAND8:
15165   case X86::ATOMAND16:
15166   case X86::ATOMAND32:
15167   case X86::ATOMAND64:
15168   case X86::ATOMOR8:
15169   case X86::ATOMOR16:
15170   case X86::ATOMOR32:
15171   case X86::ATOMOR64:
15172   case X86::ATOMXOR8:
15173   case X86::ATOMXOR16:
15174   case X86::ATOMXOR32:
15175   case X86::ATOMXOR64: {
15176     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15177     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15178       .addReg(t4);
15179     break;
15180   }
15181   case X86::ATOMNAND8:
15182   case X86::ATOMNAND16:
15183   case X86::ATOMNAND32:
15184   case X86::ATOMNAND64: {
15185     unsigned Tmp = MRI.createVirtualRegister(RC);
15186     unsigned NOTOpc;
15187     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15188     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15189       .addReg(t4);
15190     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15191     break;
15192   }
15193   case X86::ATOMMAX8:
15194   case X86::ATOMMAX16:
15195   case X86::ATOMMAX32:
15196   case X86::ATOMMAX64:
15197   case X86::ATOMMIN8:
15198   case X86::ATOMMIN16:
15199   case X86::ATOMMIN32:
15200   case X86::ATOMMIN64:
15201   case X86::ATOMUMAX8:
15202   case X86::ATOMUMAX16:
15203   case X86::ATOMUMAX32:
15204   case X86::ATOMUMAX64:
15205   case X86::ATOMUMIN8:
15206   case X86::ATOMUMIN16:
15207   case X86::ATOMUMIN32:
15208   case X86::ATOMUMIN64: {
15209     unsigned CMPOpc;
15210     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15211
15212     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15213       .addReg(SrcReg)
15214       .addReg(t4);
15215
15216     if (Subtarget->hasCMov()) {
15217       if (VT != MVT::i8) {
15218         // Native support
15219         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15220           .addReg(SrcReg)
15221           .addReg(t4);
15222       } else {
15223         // Promote i8 to i32 to use CMOV32
15224         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15225         const TargetRegisterClass *RC32 =
15226           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15227         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15228         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15229         unsigned Tmp = MRI.createVirtualRegister(RC32);
15230
15231         unsigned Undef = MRI.createVirtualRegister(RC32);
15232         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15233
15234         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15235           .addReg(Undef)
15236           .addReg(SrcReg)
15237           .addImm(X86::sub_8bit);
15238         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15239           .addReg(Undef)
15240           .addReg(t4)
15241           .addImm(X86::sub_8bit);
15242
15243         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15244           .addReg(SrcReg32)
15245           .addReg(AccReg32);
15246
15247         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15248           .addReg(Tmp, 0, X86::sub_8bit);
15249       }
15250     } else {
15251       // Use pseudo select and lower them.
15252       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15253              "Invalid atomic-load-op transformation!");
15254       unsigned SelOpc = getPseudoCMOVOpc(VT);
15255       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15256       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15257       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15258               .addReg(SrcReg).addReg(t4)
15259               .addImm(CC);
15260       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15261       // Replace the original PHI node as mainMBB is changed after CMOV
15262       // lowering.
15263       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15264         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15265       Phi->eraseFromParent();
15266     }
15267     break;
15268   }
15269   }
15270
15271   // Copy PhyReg back from virtual register.
15272   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15273     .addReg(t4);
15274
15275   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15276   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15277     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15278     if (NewMO.isReg())
15279       NewMO.setIsKill(false);
15280     MIB.addOperand(NewMO);
15281   }
15282   MIB.addReg(t2);
15283   MIB.setMemRefs(MMOBegin, MMOEnd);
15284
15285   // Copy PhyReg back to virtual register.
15286   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15287     .addReg(PhyReg);
15288
15289   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15290
15291   mainMBB->addSuccessor(origMainMBB);
15292   mainMBB->addSuccessor(sinkMBB);
15293
15294   // sinkMBB:
15295   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15296           TII->get(TargetOpcode::COPY), DstReg)
15297     .addReg(t3);
15298
15299   MI->eraseFromParent();
15300   return sinkMBB;
15301 }
15302
15303 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15304 // instructions. They will be translated into a spin-loop or compare-exchange
15305 // loop from
15306 //
15307 //    ...
15308 //    dst = atomic-fetch-op MI.addr, MI.val
15309 //    ...
15310 //
15311 // to
15312 //
15313 //    ...
15314 //    t1L = LOAD [MI.addr + 0]
15315 //    t1H = LOAD [MI.addr + 4]
15316 // loop:
15317 //    t4L = phi(t1L, t3L / loop)
15318 //    t4H = phi(t1H, t3H / loop)
15319 //    t2L = OP MI.val.lo, t4L
15320 //    t2H = OP MI.val.hi, t4H
15321 //    EAX = t4L
15322 //    EDX = t4H
15323 //    EBX = t2L
15324 //    ECX = t2H
15325 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15326 //    t3L = EAX
15327 //    t3H = EDX
15328 //    JNE loop
15329 // sink:
15330 //    dstL = t3L
15331 //    dstH = t3H
15332 //    ...
15333 MachineBasicBlock *
15334 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15335                                            MachineBasicBlock *MBB) const {
15336   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15337   DebugLoc DL = MI->getDebugLoc();
15338
15339   MachineFunction *MF = MBB->getParent();
15340   MachineRegisterInfo &MRI = MF->getRegInfo();
15341
15342   const BasicBlock *BB = MBB->getBasicBlock();
15343   MachineFunction::iterator I = MBB;
15344   ++I;
15345
15346   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15347          "Unexpected number of operands");
15348
15349   assert(MI->hasOneMemOperand() &&
15350          "Expected atomic-load-op32 to have one memoperand");
15351
15352   // Memory Reference
15353   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15354   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15355
15356   unsigned DstLoReg, DstHiReg;
15357   unsigned SrcLoReg, SrcHiReg;
15358   unsigned MemOpndSlot;
15359
15360   unsigned CurOp = 0;
15361
15362   DstLoReg = MI->getOperand(CurOp++).getReg();
15363   DstHiReg = MI->getOperand(CurOp++).getReg();
15364   MemOpndSlot = CurOp;
15365   CurOp += X86::AddrNumOperands;
15366   SrcLoReg = MI->getOperand(CurOp++).getReg();
15367   SrcHiReg = MI->getOperand(CurOp++).getReg();
15368
15369   const TargetRegisterClass *RC = &X86::GR32RegClass;
15370   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15371
15372   unsigned t1L = MRI.createVirtualRegister(RC);
15373   unsigned t1H = MRI.createVirtualRegister(RC);
15374   unsigned t2L = MRI.createVirtualRegister(RC);
15375   unsigned t2H = MRI.createVirtualRegister(RC);
15376   unsigned t3L = MRI.createVirtualRegister(RC);
15377   unsigned t3H = MRI.createVirtualRegister(RC);
15378   unsigned t4L = MRI.createVirtualRegister(RC);
15379   unsigned t4H = MRI.createVirtualRegister(RC);
15380
15381   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15382   unsigned LOADOpc = X86::MOV32rm;
15383
15384   // For the atomic load-arith operator, we generate
15385   //
15386   //  thisMBB:
15387   //    t1L = LOAD [MI.addr + 0]
15388   //    t1H = LOAD [MI.addr + 4]
15389   //  mainMBB:
15390   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15391   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15392   //    t2L = OP MI.val.lo, t4L
15393   //    t2H = OP MI.val.hi, 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   //  sinkMBB:
15401   //    dstL = t3L
15402   //    dstH = t3H
15403
15404   MachineBasicBlock *thisMBB = MBB;
15405   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15406   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15407   MF->insert(I, mainMBB);
15408   MF->insert(I, sinkMBB);
15409
15410   MachineInstrBuilder MIB;
15411
15412   // Transfer the remainder of BB and its successor edges to sinkMBB.
15413   sinkMBB->splice(sinkMBB->begin(), MBB,
15414                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15415   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15416
15417   // thisMBB:
15418   // Lo
15419   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15420   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15421     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15422     if (NewMO.isReg())
15423       NewMO.setIsKill(false);
15424     MIB.addOperand(NewMO);
15425   }
15426   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15427     unsigned flags = (*MMOI)->getFlags();
15428     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15429     MachineMemOperand *MMO =
15430       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15431                                (*MMOI)->getSize(),
15432                                (*MMOI)->getBaseAlignment(),
15433                                (*MMOI)->getTBAAInfo(),
15434                                (*MMOI)->getRanges());
15435     MIB.addMemOperand(MMO);
15436   };
15437   MachineInstr *LowMI = MIB;
15438
15439   // Hi
15440   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15441   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15442     if (i == X86::AddrDisp) {
15443       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15444     } else {
15445       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15446       if (NewMO.isReg())
15447         NewMO.setIsKill(false);
15448       MIB.addOperand(NewMO);
15449     }
15450   }
15451   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15452
15453   thisMBB->addSuccessor(mainMBB);
15454
15455   // mainMBB:
15456   MachineBasicBlock *origMainMBB = mainMBB;
15457
15458   // Add PHIs.
15459   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15460                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15461   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15462                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15463
15464   unsigned Opc = MI->getOpcode();
15465   switch (Opc) {
15466   default:
15467     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15468   case X86::ATOMAND6432:
15469   case X86::ATOMOR6432:
15470   case X86::ATOMXOR6432:
15471   case X86::ATOMADD6432:
15472   case X86::ATOMSUB6432: {
15473     unsigned HiOpc;
15474     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15475     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15476       .addReg(SrcLoReg);
15477     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15478       .addReg(SrcHiReg);
15479     break;
15480   }
15481   case X86::ATOMNAND6432: {
15482     unsigned HiOpc, NOTOpc;
15483     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15484     unsigned TmpL = MRI.createVirtualRegister(RC);
15485     unsigned TmpH = MRI.createVirtualRegister(RC);
15486     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15487       .addReg(t4L);
15488     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15489       .addReg(t4H);
15490     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15491     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15492     break;
15493   }
15494   case X86::ATOMMAX6432:
15495   case X86::ATOMMIN6432:
15496   case X86::ATOMUMAX6432:
15497   case X86::ATOMUMIN6432: {
15498     unsigned HiOpc;
15499     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15500     unsigned cL = MRI.createVirtualRegister(RC8);
15501     unsigned cH = MRI.createVirtualRegister(RC8);
15502     unsigned cL32 = MRI.createVirtualRegister(RC);
15503     unsigned cH32 = MRI.createVirtualRegister(RC);
15504     unsigned cc = MRI.createVirtualRegister(RC);
15505     // cl := cmp src_lo, lo
15506     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15507       .addReg(SrcLoReg).addReg(t4L);
15508     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15509     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15510     // ch := cmp src_hi, hi
15511     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15512       .addReg(SrcHiReg).addReg(t4H);
15513     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15514     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15515     // cc := if (src_hi == hi) ? cl : ch;
15516     if (Subtarget->hasCMov()) {
15517       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15518         .addReg(cH32).addReg(cL32);
15519     } else {
15520       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15521               .addReg(cH32).addReg(cL32)
15522               .addImm(X86::COND_E);
15523       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15524     }
15525     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15526     if (Subtarget->hasCMov()) {
15527       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15528         .addReg(SrcLoReg).addReg(t4L);
15529       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15530         .addReg(SrcHiReg).addReg(t4H);
15531     } else {
15532       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15533               .addReg(SrcLoReg).addReg(t4L)
15534               .addImm(X86::COND_NE);
15535       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15536       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15537       // 2nd CMOV lowering.
15538       mainMBB->addLiveIn(X86::EFLAGS);
15539       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15540               .addReg(SrcHiReg).addReg(t4H)
15541               .addImm(X86::COND_NE);
15542       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15543       // Replace the original PHI node as mainMBB is changed after CMOV
15544       // lowering.
15545       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15546         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15547       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15548         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15549       PhiL->eraseFromParent();
15550       PhiH->eraseFromParent();
15551     }
15552     break;
15553   }
15554   case X86::ATOMSWAP6432: {
15555     unsigned HiOpc;
15556     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15557     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15558     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15559     break;
15560   }
15561   }
15562
15563   // Copy EDX:EAX back from HiReg:LoReg
15564   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15565   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15566   // Copy ECX:EBX from t1H:t1L
15567   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15568   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15569
15570   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15571   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15572     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15573     if (NewMO.isReg())
15574       NewMO.setIsKill(false);
15575     MIB.addOperand(NewMO);
15576   }
15577   MIB.setMemRefs(MMOBegin, MMOEnd);
15578
15579   // Copy EDX:EAX back to t3H:t3L
15580   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15581   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15582
15583   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15584
15585   mainMBB->addSuccessor(origMainMBB);
15586   mainMBB->addSuccessor(sinkMBB);
15587
15588   // sinkMBB:
15589   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15590           TII->get(TargetOpcode::COPY), DstLoReg)
15591     .addReg(t3L);
15592   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15593           TII->get(TargetOpcode::COPY), DstHiReg)
15594     .addReg(t3H);
15595
15596   MI->eraseFromParent();
15597   return sinkMBB;
15598 }
15599
15600 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15601 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15602 // in the .td file.
15603 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15604                                        const TargetInstrInfo *TII) {
15605   unsigned Opc;
15606   switch (MI->getOpcode()) {
15607   default: llvm_unreachable("illegal opcode!");
15608   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15609   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15610   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15611   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15612   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15613   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15614   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15615   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15616   }
15617
15618   DebugLoc dl = MI->getDebugLoc();
15619   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15620
15621   unsigned NumArgs = MI->getNumOperands();
15622   for (unsigned i = 1; i < NumArgs; ++i) {
15623     MachineOperand &Op = MI->getOperand(i);
15624     if (!(Op.isReg() && Op.isImplicit()))
15625       MIB.addOperand(Op);
15626   }
15627   if (MI->hasOneMemOperand())
15628     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15629
15630   BuildMI(*BB, MI, dl,
15631     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15632     .addReg(X86::XMM0);
15633
15634   MI->eraseFromParent();
15635   return BB;
15636 }
15637
15638 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15639 // defs in an instruction pattern
15640 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15641                                        const TargetInstrInfo *TII) {
15642   unsigned Opc;
15643   switch (MI->getOpcode()) {
15644   default: llvm_unreachable("illegal opcode!");
15645   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15646   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15647   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15648   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15649   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15650   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15651   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15652   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15653   }
15654
15655   DebugLoc dl = MI->getDebugLoc();
15656   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15657
15658   unsigned NumArgs = MI->getNumOperands(); // remove the results
15659   for (unsigned i = 1; i < NumArgs; ++i) {
15660     MachineOperand &Op = MI->getOperand(i);
15661     if (!(Op.isReg() && Op.isImplicit()))
15662       MIB.addOperand(Op);
15663   }
15664   if (MI->hasOneMemOperand())
15665     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15666
15667   BuildMI(*BB, MI, dl,
15668     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15669     .addReg(X86::ECX);
15670
15671   MI->eraseFromParent();
15672   return BB;
15673 }
15674
15675 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15676                                        const TargetInstrInfo *TII,
15677                                        const X86Subtarget* Subtarget) {
15678   DebugLoc dl = MI->getDebugLoc();
15679
15680   // Address into RAX/EAX, other two args into ECX, EDX.
15681   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15682   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15683   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15684   for (int i = 0; i < X86::AddrNumOperands; ++i)
15685     MIB.addOperand(MI->getOperand(i));
15686
15687   unsigned ValOps = X86::AddrNumOperands;
15688   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15689     .addReg(MI->getOperand(ValOps).getReg());
15690   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15691     .addReg(MI->getOperand(ValOps+1).getReg());
15692
15693   // The instruction doesn't actually take any operands though.
15694   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15695
15696   MI->eraseFromParent(); // The pseudo is gone now.
15697   return BB;
15698 }
15699
15700 MachineBasicBlock *
15701 X86TargetLowering::EmitVAARG64WithCustomInserter(
15702                    MachineInstr *MI,
15703                    MachineBasicBlock *MBB) const {
15704   // Emit va_arg instruction on X86-64.
15705
15706   // Operands to this pseudo-instruction:
15707   // 0  ) Output        : destination address (reg)
15708   // 1-5) Input         : va_list address (addr, i64mem)
15709   // 6  ) ArgSize       : Size (in bytes) of vararg type
15710   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15711   // 8  ) Align         : Alignment of type
15712   // 9  ) EFLAGS (implicit-def)
15713
15714   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15715   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15716
15717   unsigned DestReg = MI->getOperand(0).getReg();
15718   MachineOperand &Base = MI->getOperand(1);
15719   MachineOperand &Scale = MI->getOperand(2);
15720   MachineOperand &Index = MI->getOperand(3);
15721   MachineOperand &Disp = MI->getOperand(4);
15722   MachineOperand &Segment = MI->getOperand(5);
15723   unsigned ArgSize = MI->getOperand(6).getImm();
15724   unsigned ArgMode = MI->getOperand(7).getImm();
15725   unsigned Align = MI->getOperand(8).getImm();
15726
15727   // Memory Reference
15728   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15729   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15730   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15731
15732   // Machine Information
15733   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15734   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15735   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15736   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15737   DebugLoc DL = MI->getDebugLoc();
15738
15739   // struct va_list {
15740   //   i32   gp_offset
15741   //   i32   fp_offset
15742   //   i64   overflow_area (address)
15743   //   i64   reg_save_area (address)
15744   // }
15745   // sizeof(va_list) = 24
15746   // alignment(va_list) = 8
15747
15748   unsigned TotalNumIntRegs = 6;
15749   unsigned TotalNumXMMRegs = 8;
15750   bool UseGPOffset = (ArgMode == 1);
15751   bool UseFPOffset = (ArgMode == 2);
15752   unsigned MaxOffset = TotalNumIntRegs * 8 +
15753                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15754
15755   /* Align ArgSize to a multiple of 8 */
15756   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15757   bool NeedsAlign = (Align > 8);
15758
15759   MachineBasicBlock *thisMBB = MBB;
15760   MachineBasicBlock *overflowMBB;
15761   MachineBasicBlock *offsetMBB;
15762   MachineBasicBlock *endMBB;
15763
15764   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15765   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15766   unsigned OffsetReg = 0;
15767
15768   if (!UseGPOffset && !UseFPOffset) {
15769     // If we only pull from the overflow region, we don't create a branch.
15770     // We don't need to alter control flow.
15771     OffsetDestReg = 0; // unused
15772     OverflowDestReg = DestReg;
15773
15774     offsetMBB = nullptr;
15775     overflowMBB = thisMBB;
15776     endMBB = thisMBB;
15777   } else {
15778     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15779     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15780     // If not, pull from overflow_area. (branch to overflowMBB)
15781     //
15782     //       thisMBB
15783     //         |     .
15784     //         |        .
15785     //     offsetMBB   overflowMBB
15786     //         |        .
15787     //         |     .
15788     //        endMBB
15789
15790     // Registers for the PHI in endMBB
15791     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15792     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15793
15794     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15795     MachineFunction *MF = MBB->getParent();
15796     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15797     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15798     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15799
15800     MachineFunction::iterator MBBIter = MBB;
15801     ++MBBIter;
15802
15803     // Insert the new basic blocks
15804     MF->insert(MBBIter, offsetMBB);
15805     MF->insert(MBBIter, overflowMBB);
15806     MF->insert(MBBIter, endMBB);
15807
15808     // Transfer the remainder of MBB and its successor edges to endMBB.
15809     endMBB->splice(endMBB->begin(), thisMBB,
15810                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15811     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15812
15813     // Make offsetMBB and overflowMBB successors of thisMBB
15814     thisMBB->addSuccessor(offsetMBB);
15815     thisMBB->addSuccessor(overflowMBB);
15816
15817     // endMBB is a successor of both offsetMBB and overflowMBB
15818     offsetMBB->addSuccessor(endMBB);
15819     overflowMBB->addSuccessor(endMBB);
15820
15821     // Load the offset value into a register
15822     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15823     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15824       .addOperand(Base)
15825       .addOperand(Scale)
15826       .addOperand(Index)
15827       .addDisp(Disp, UseFPOffset ? 4 : 0)
15828       .addOperand(Segment)
15829       .setMemRefs(MMOBegin, MMOEnd);
15830
15831     // Check if there is enough room left to pull this argument.
15832     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15833       .addReg(OffsetReg)
15834       .addImm(MaxOffset + 8 - ArgSizeA8);
15835
15836     // Branch to "overflowMBB" if offset >= max
15837     // Fall through to "offsetMBB" otherwise
15838     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15839       .addMBB(overflowMBB);
15840   }
15841
15842   // In offsetMBB, emit code to use the reg_save_area.
15843   if (offsetMBB) {
15844     assert(OffsetReg != 0);
15845
15846     // Read the reg_save_area address.
15847     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15848     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15849       .addOperand(Base)
15850       .addOperand(Scale)
15851       .addOperand(Index)
15852       .addDisp(Disp, 16)
15853       .addOperand(Segment)
15854       .setMemRefs(MMOBegin, MMOEnd);
15855
15856     // Zero-extend the offset
15857     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15858       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15859         .addImm(0)
15860         .addReg(OffsetReg)
15861         .addImm(X86::sub_32bit);
15862
15863     // Add the offset to the reg_save_area to get the final address.
15864     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15865       .addReg(OffsetReg64)
15866       .addReg(RegSaveReg);
15867
15868     // Compute the offset for the next argument
15869     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15870     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15871       .addReg(OffsetReg)
15872       .addImm(UseFPOffset ? 16 : 8);
15873
15874     // Store it back into the va_list.
15875     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15876       .addOperand(Base)
15877       .addOperand(Scale)
15878       .addOperand(Index)
15879       .addDisp(Disp, UseFPOffset ? 4 : 0)
15880       .addOperand(Segment)
15881       .addReg(NextOffsetReg)
15882       .setMemRefs(MMOBegin, MMOEnd);
15883
15884     // Jump to endMBB
15885     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15886       .addMBB(endMBB);
15887   }
15888
15889   //
15890   // Emit code to use overflow area
15891   //
15892
15893   // Load the overflow_area address into a register.
15894   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15895   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15896     .addOperand(Base)
15897     .addOperand(Scale)
15898     .addOperand(Index)
15899     .addDisp(Disp, 8)
15900     .addOperand(Segment)
15901     .setMemRefs(MMOBegin, MMOEnd);
15902
15903   // If we need to align it, do so. Otherwise, just copy the address
15904   // to OverflowDestReg.
15905   if (NeedsAlign) {
15906     // Align the overflow address
15907     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15908     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15909
15910     // aligned_addr = (addr + (align-1)) & ~(align-1)
15911     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15912       .addReg(OverflowAddrReg)
15913       .addImm(Align-1);
15914
15915     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15916       .addReg(TmpReg)
15917       .addImm(~(uint64_t)(Align-1));
15918   } else {
15919     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15920       .addReg(OverflowAddrReg);
15921   }
15922
15923   // Compute the next overflow address after this argument.
15924   // (the overflow address should be kept 8-byte aligned)
15925   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15926   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15927     .addReg(OverflowDestReg)
15928     .addImm(ArgSizeA8);
15929
15930   // Store the new overflow address.
15931   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15932     .addOperand(Base)
15933     .addOperand(Scale)
15934     .addOperand(Index)
15935     .addDisp(Disp, 8)
15936     .addOperand(Segment)
15937     .addReg(NextAddrReg)
15938     .setMemRefs(MMOBegin, MMOEnd);
15939
15940   // If we branched, emit the PHI to the front of endMBB.
15941   if (offsetMBB) {
15942     BuildMI(*endMBB, endMBB->begin(), DL,
15943             TII->get(X86::PHI), DestReg)
15944       .addReg(OffsetDestReg).addMBB(offsetMBB)
15945       .addReg(OverflowDestReg).addMBB(overflowMBB);
15946   }
15947
15948   // Erase the pseudo instruction
15949   MI->eraseFromParent();
15950
15951   return endMBB;
15952 }
15953
15954 MachineBasicBlock *
15955 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15956                                                  MachineInstr *MI,
15957                                                  MachineBasicBlock *MBB) const {
15958   // Emit code to save XMM registers to the stack. The ABI says that the
15959   // number of registers to save is given in %al, so it's theoretically
15960   // possible to do an indirect jump trick to avoid saving all of them,
15961   // however this code takes a simpler approach and just executes all
15962   // of the stores if %al is non-zero. It's less code, and it's probably
15963   // easier on the hardware branch predictor, and stores aren't all that
15964   // expensive anyway.
15965
15966   // Create the new basic blocks. One block contains all the XMM stores,
15967   // and one block is the final destination regardless of whether any
15968   // stores were performed.
15969   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15970   MachineFunction *F = MBB->getParent();
15971   MachineFunction::iterator MBBIter = MBB;
15972   ++MBBIter;
15973   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15974   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15975   F->insert(MBBIter, XMMSaveMBB);
15976   F->insert(MBBIter, EndMBB);
15977
15978   // Transfer the remainder of MBB and its successor edges to EndMBB.
15979   EndMBB->splice(EndMBB->begin(), MBB,
15980                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15981   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15982
15983   // The original block will now fall through to the XMM save block.
15984   MBB->addSuccessor(XMMSaveMBB);
15985   // The XMMSaveMBB will fall through to the end block.
15986   XMMSaveMBB->addSuccessor(EndMBB);
15987
15988   // Now add the instructions.
15989   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15990   DebugLoc DL = MI->getDebugLoc();
15991
15992   unsigned CountReg = MI->getOperand(0).getReg();
15993   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15994   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15995
15996   if (!Subtarget->isTargetWin64()) {
15997     // If %al is 0, branch around the XMM save block.
15998     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15999     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16000     MBB->addSuccessor(EndMBB);
16001   }
16002
16003   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16004   // that was just emitted, but clearly shouldn't be "saved".
16005   assert((MI->getNumOperands() <= 3 ||
16006           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16007           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16008          && "Expected last argument to be EFLAGS");
16009   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16010   // In the XMM save block, save all the XMM argument registers.
16011   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16012     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16013     MachineMemOperand *MMO =
16014       F->getMachineMemOperand(
16015           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16016         MachineMemOperand::MOStore,
16017         /*Size=*/16, /*Align=*/16);
16018     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16019       .addFrameIndex(RegSaveFrameIndex)
16020       .addImm(/*Scale=*/1)
16021       .addReg(/*IndexReg=*/0)
16022       .addImm(/*Disp=*/Offset)
16023       .addReg(/*Segment=*/0)
16024       .addReg(MI->getOperand(i).getReg())
16025       .addMemOperand(MMO);
16026   }
16027
16028   MI->eraseFromParent();   // The pseudo instruction is gone now.
16029
16030   return EndMBB;
16031 }
16032
16033 // The EFLAGS operand of SelectItr might be missing a kill marker
16034 // because there were multiple uses of EFLAGS, and ISel didn't know
16035 // which to mark. Figure out whether SelectItr should have had a
16036 // kill marker, and set it if it should. Returns the correct kill
16037 // marker value.
16038 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16039                                      MachineBasicBlock* BB,
16040                                      const TargetRegisterInfo* TRI) {
16041   // Scan forward through BB for a use/def of EFLAGS.
16042   MachineBasicBlock::iterator miI(std::next(SelectItr));
16043   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16044     const MachineInstr& mi = *miI;
16045     if (mi.readsRegister(X86::EFLAGS))
16046       return false;
16047     if (mi.definesRegister(X86::EFLAGS))
16048       break; // Should have kill-flag - update below.
16049   }
16050
16051   // If we hit the end of the block, check whether EFLAGS is live into a
16052   // successor.
16053   if (miI == BB->end()) {
16054     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16055                                           sEnd = BB->succ_end();
16056          sItr != sEnd; ++sItr) {
16057       MachineBasicBlock* succ = *sItr;
16058       if (succ->isLiveIn(X86::EFLAGS))
16059         return false;
16060     }
16061   }
16062
16063   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16064   // out. SelectMI should have a kill flag on EFLAGS.
16065   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16066   return true;
16067 }
16068
16069 MachineBasicBlock *
16070 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16071                                      MachineBasicBlock *BB) const {
16072   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16073   DebugLoc DL = MI->getDebugLoc();
16074
16075   // To "insert" a SELECT_CC instruction, we actually have to insert the
16076   // diamond control-flow pattern.  The incoming instruction knows the
16077   // destination vreg to set, the condition code register to branch on, the
16078   // true/false values to select between, and a branch opcode to use.
16079   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16080   MachineFunction::iterator It = BB;
16081   ++It;
16082
16083   //  thisMBB:
16084   //  ...
16085   //   TrueVal = ...
16086   //   cmpTY ccX, r1, r2
16087   //   bCC copy1MBB
16088   //   fallthrough --> copy0MBB
16089   MachineBasicBlock *thisMBB = BB;
16090   MachineFunction *F = BB->getParent();
16091   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16092   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16093   F->insert(It, copy0MBB);
16094   F->insert(It, sinkMBB);
16095
16096   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16097   // live into the sink and copy blocks.
16098   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16099   if (!MI->killsRegister(X86::EFLAGS) &&
16100       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16101     copy0MBB->addLiveIn(X86::EFLAGS);
16102     sinkMBB->addLiveIn(X86::EFLAGS);
16103   }
16104
16105   // Transfer the remainder of BB and its successor edges to sinkMBB.
16106   sinkMBB->splice(sinkMBB->begin(), BB,
16107                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16108   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16109
16110   // Add the true and fallthrough blocks as its successors.
16111   BB->addSuccessor(copy0MBB);
16112   BB->addSuccessor(sinkMBB);
16113
16114   // Create the conditional branch instruction.
16115   unsigned Opc =
16116     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16117   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16118
16119   //  copy0MBB:
16120   //   %FalseValue = ...
16121   //   # fallthrough to sinkMBB
16122   copy0MBB->addSuccessor(sinkMBB);
16123
16124   //  sinkMBB:
16125   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16126   //  ...
16127   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16128           TII->get(X86::PHI), MI->getOperand(0).getReg())
16129     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16130     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16131
16132   MI->eraseFromParent();   // The pseudo instruction is gone now.
16133   return sinkMBB;
16134 }
16135
16136 MachineBasicBlock *
16137 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16138                                         bool Is64Bit) const {
16139   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16140   DebugLoc DL = MI->getDebugLoc();
16141   MachineFunction *MF = BB->getParent();
16142   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16143
16144   assert(MF->shouldSplitStack());
16145
16146   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16147   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16148
16149   // BB:
16150   //  ... [Till the alloca]
16151   // If stacklet is not large enough, jump to mallocMBB
16152   //
16153   // bumpMBB:
16154   //  Allocate by subtracting from RSP
16155   //  Jump to continueMBB
16156   //
16157   // mallocMBB:
16158   //  Allocate by call to runtime
16159   //
16160   // continueMBB:
16161   //  ...
16162   //  [rest of original BB]
16163   //
16164
16165   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16166   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16167   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16168
16169   MachineRegisterInfo &MRI = MF->getRegInfo();
16170   const TargetRegisterClass *AddrRegClass =
16171     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16172
16173   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16174     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16175     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16176     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16177     sizeVReg = MI->getOperand(1).getReg(),
16178     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16179
16180   MachineFunction::iterator MBBIter = BB;
16181   ++MBBIter;
16182
16183   MF->insert(MBBIter, bumpMBB);
16184   MF->insert(MBBIter, mallocMBB);
16185   MF->insert(MBBIter, continueMBB);
16186
16187   continueMBB->splice(continueMBB->begin(), BB,
16188                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16189   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16190
16191   // Add code to the main basic block to check if the stack limit has been hit,
16192   // and if so, jump to mallocMBB otherwise to bumpMBB.
16193   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16194   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16195     .addReg(tmpSPVReg).addReg(sizeVReg);
16196   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16197     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16198     .addReg(SPLimitVReg);
16199   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16200
16201   // bumpMBB simply decreases the stack pointer, since we know the current
16202   // stacklet has enough space.
16203   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16204     .addReg(SPLimitVReg);
16205   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16206     .addReg(SPLimitVReg);
16207   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16208
16209   // Calls into a routine in libgcc to allocate more space from the heap.
16210   const uint32_t *RegMask =
16211     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16212   if (Is64Bit) {
16213     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16214       .addReg(sizeVReg);
16215     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16216       .addExternalSymbol("__morestack_allocate_stack_space")
16217       .addRegMask(RegMask)
16218       .addReg(X86::RDI, RegState::Implicit)
16219       .addReg(X86::RAX, RegState::ImplicitDefine);
16220   } else {
16221     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16222       .addImm(12);
16223     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16224     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16225       .addExternalSymbol("__morestack_allocate_stack_space")
16226       .addRegMask(RegMask)
16227       .addReg(X86::EAX, RegState::ImplicitDefine);
16228   }
16229
16230   if (!Is64Bit)
16231     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16232       .addImm(16);
16233
16234   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16235     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16236   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16237
16238   // Set up the CFG correctly.
16239   BB->addSuccessor(bumpMBB);
16240   BB->addSuccessor(mallocMBB);
16241   mallocMBB->addSuccessor(continueMBB);
16242   bumpMBB->addSuccessor(continueMBB);
16243
16244   // Take care of the PHI nodes.
16245   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16246           MI->getOperand(0).getReg())
16247     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16248     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16249
16250   // Delete the original pseudo instruction.
16251   MI->eraseFromParent();
16252
16253   // And we're done.
16254   return continueMBB;
16255 }
16256
16257 MachineBasicBlock *
16258 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16259                                           MachineBasicBlock *BB) const {
16260   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16261   DebugLoc DL = MI->getDebugLoc();
16262
16263   assert(!Subtarget->isTargetMacho());
16264
16265   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16266   // non-trivial part is impdef of ESP.
16267
16268   if (Subtarget->isTargetWin64()) {
16269     if (Subtarget->isTargetCygMing()) {
16270       // ___chkstk(Mingw64):
16271       // Clobbers R10, R11, RAX and EFLAGS.
16272       // Updates RSP.
16273       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16274         .addExternalSymbol("___chkstk")
16275         .addReg(X86::RAX, RegState::Implicit)
16276         .addReg(X86::RSP, RegState::Implicit)
16277         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16278         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16279         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16280     } else {
16281       // __chkstk(MSVCRT): does not update stack pointer.
16282       // Clobbers R10, R11 and EFLAGS.
16283       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16284         .addExternalSymbol("__chkstk")
16285         .addReg(X86::RAX, RegState::Implicit)
16286         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16287       // RAX has the offset to be subtracted from RSP.
16288       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16289         .addReg(X86::RSP)
16290         .addReg(X86::RAX);
16291     }
16292   } else {
16293     const char *StackProbeSymbol =
16294       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16295
16296     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16297       .addExternalSymbol(StackProbeSymbol)
16298       .addReg(X86::EAX, RegState::Implicit)
16299       .addReg(X86::ESP, RegState::Implicit)
16300       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16301       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16302       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16303   }
16304
16305   MI->eraseFromParent();   // The pseudo instruction is gone now.
16306   return BB;
16307 }
16308
16309 MachineBasicBlock *
16310 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16311                                       MachineBasicBlock *BB) const {
16312   // This is pretty easy.  We're taking the value that we received from
16313   // our load from the relocation, sticking it in either RDI (x86-64)
16314   // or EAX and doing an indirect call.  The return value will then
16315   // be in the normal return register.
16316   const X86InstrInfo *TII
16317     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16318   DebugLoc DL = MI->getDebugLoc();
16319   MachineFunction *F = BB->getParent();
16320
16321   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16322   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16323
16324   // Get a register mask for the lowered call.
16325   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16326   // proper register mask.
16327   const uint32_t *RegMask =
16328     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16329   if (Subtarget->is64Bit()) {
16330     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16331                                       TII->get(X86::MOV64rm), X86::RDI)
16332     .addReg(X86::RIP)
16333     .addImm(0).addReg(0)
16334     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16335                       MI->getOperand(3).getTargetFlags())
16336     .addReg(0);
16337     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16338     addDirectMem(MIB, X86::RDI);
16339     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16340   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16341     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16342                                       TII->get(X86::MOV32rm), X86::EAX)
16343     .addReg(0)
16344     .addImm(0).addReg(0)
16345     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16346                       MI->getOperand(3).getTargetFlags())
16347     .addReg(0);
16348     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16349     addDirectMem(MIB, X86::EAX);
16350     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16351   } else {
16352     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16353                                       TII->get(X86::MOV32rm), X86::EAX)
16354     .addReg(TII->getGlobalBaseReg(F))
16355     .addImm(0).addReg(0)
16356     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16357                       MI->getOperand(3).getTargetFlags())
16358     .addReg(0);
16359     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16360     addDirectMem(MIB, X86::EAX);
16361     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16362   }
16363
16364   MI->eraseFromParent(); // The pseudo instruction is gone now.
16365   return BB;
16366 }
16367
16368 MachineBasicBlock *
16369 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16370                                     MachineBasicBlock *MBB) const {
16371   DebugLoc DL = MI->getDebugLoc();
16372   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16373
16374   MachineFunction *MF = MBB->getParent();
16375   MachineRegisterInfo &MRI = MF->getRegInfo();
16376
16377   const BasicBlock *BB = MBB->getBasicBlock();
16378   MachineFunction::iterator I = MBB;
16379   ++I;
16380
16381   // Memory Reference
16382   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16383   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16384
16385   unsigned DstReg;
16386   unsigned MemOpndSlot = 0;
16387
16388   unsigned CurOp = 0;
16389
16390   DstReg = MI->getOperand(CurOp++).getReg();
16391   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16392   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16393   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16394   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16395
16396   MemOpndSlot = CurOp;
16397
16398   MVT PVT = getPointerTy();
16399   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16400          "Invalid Pointer Size!");
16401
16402   // For v = setjmp(buf), we generate
16403   //
16404   // thisMBB:
16405   //  buf[LabelOffset] = restoreMBB
16406   //  SjLjSetup restoreMBB
16407   //
16408   // mainMBB:
16409   //  v_main = 0
16410   //
16411   // sinkMBB:
16412   //  v = phi(main, restore)
16413   //
16414   // restoreMBB:
16415   //  v_restore = 1
16416
16417   MachineBasicBlock *thisMBB = MBB;
16418   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16419   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16420   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16421   MF->insert(I, mainMBB);
16422   MF->insert(I, sinkMBB);
16423   MF->push_back(restoreMBB);
16424
16425   MachineInstrBuilder MIB;
16426
16427   // Transfer the remainder of BB and its successor edges to sinkMBB.
16428   sinkMBB->splice(sinkMBB->begin(), MBB,
16429                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16430   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16431
16432   // thisMBB:
16433   unsigned PtrStoreOpc = 0;
16434   unsigned LabelReg = 0;
16435   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16436   Reloc::Model RM = getTargetMachine().getRelocationModel();
16437   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16438                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16439
16440   // Prepare IP either in reg or imm.
16441   if (!UseImmLabel) {
16442     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16443     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16444     LabelReg = MRI.createVirtualRegister(PtrRC);
16445     if (Subtarget->is64Bit()) {
16446       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16447               .addReg(X86::RIP)
16448               .addImm(0)
16449               .addReg(0)
16450               .addMBB(restoreMBB)
16451               .addReg(0);
16452     } else {
16453       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16454       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16455               .addReg(XII->getGlobalBaseReg(MF))
16456               .addImm(0)
16457               .addReg(0)
16458               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16459               .addReg(0);
16460     }
16461   } else
16462     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16463   // Store IP
16464   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16465   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16466     if (i == X86::AddrDisp)
16467       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16468     else
16469       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16470   }
16471   if (!UseImmLabel)
16472     MIB.addReg(LabelReg);
16473   else
16474     MIB.addMBB(restoreMBB);
16475   MIB.setMemRefs(MMOBegin, MMOEnd);
16476   // Setup
16477   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16478           .addMBB(restoreMBB);
16479
16480   const X86RegisterInfo *RegInfo =
16481     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16482   MIB.addRegMask(RegInfo->getNoPreservedMask());
16483   thisMBB->addSuccessor(mainMBB);
16484   thisMBB->addSuccessor(restoreMBB);
16485
16486   // mainMBB:
16487   //  EAX = 0
16488   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16489   mainMBB->addSuccessor(sinkMBB);
16490
16491   // sinkMBB:
16492   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16493           TII->get(X86::PHI), DstReg)
16494     .addReg(mainDstReg).addMBB(mainMBB)
16495     .addReg(restoreDstReg).addMBB(restoreMBB);
16496
16497   // restoreMBB:
16498   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16499   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16500   restoreMBB->addSuccessor(sinkMBB);
16501
16502   MI->eraseFromParent();
16503   return sinkMBB;
16504 }
16505
16506 MachineBasicBlock *
16507 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16508                                      MachineBasicBlock *MBB) const {
16509   DebugLoc DL = MI->getDebugLoc();
16510   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16511
16512   MachineFunction *MF = MBB->getParent();
16513   MachineRegisterInfo &MRI = MF->getRegInfo();
16514
16515   // Memory Reference
16516   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16517   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16518
16519   MVT PVT = getPointerTy();
16520   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16521          "Invalid Pointer Size!");
16522
16523   const TargetRegisterClass *RC =
16524     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16525   unsigned Tmp = MRI.createVirtualRegister(RC);
16526   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16527   const X86RegisterInfo *RegInfo =
16528     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16529   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16530   unsigned SP = RegInfo->getStackRegister();
16531
16532   MachineInstrBuilder MIB;
16533
16534   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16535   const int64_t SPOffset = 2 * PVT.getStoreSize();
16536
16537   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16538   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16539
16540   // Reload FP
16541   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16542   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16543     MIB.addOperand(MI->getOperand(i));
16544   MIB.setMemRefs(MMOBegin, MMOEnd);
16545   // Reload IP
16546   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16547   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16548     if (i == X86::AddrDisp)
16549       MIB.addDisp(MI->getOperand(i), LabelOffset);
16550     else
16551       MIB.addOperand(MI->getOperand(i));
16552   }
16553   MIB.setMemRefs(MMOBegin, MMOEnd);
16554   // Reload SP
16555   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16556   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16557     if (i == X86::AddrDisp)
16558       MIB.addDisp(MI->getOperand(i), SPOffset);
16559     else
16560       MIB.addOperand(MI->getOperand(i));
16561   }
16562   MIB.setMemRefs(MMOBegin, MMOEnd);
16563   // Jump
16564   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16565
16566   MI->eraseFromParent();
16567   return MBB;
16568 }
16569
16570 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16571 // accumulator loops. Writing back to the accumulator allows the coalescer
16572 // to remove extra copies in the loop.   
16573 MachineBasicBlock *
16574 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16575                                  MachineBasicBlock *MBB) const {
16576   MachineOperand &AddendOp = MI->getOperand(3);
16577
16578   // Bail out early if the addend isn't a register - we can't switch these.
16579   if (!AddendOp.isReg())
16580     return MBB;
16581
16582   MachineFunction &MF = *MBB->getParent();
16583   MachineRegisterInfo &MRI = MF.getRegInfo();
16584
16585   // Check whether the addend is defined by a PHI:
16586   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16587   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16588   if (!AddendDef.isPHI())
16589     return MBB;
16590
16591   // Look for the following pattern:
16592   // loop:
16593   //   %addend = phi [%entry, 0], [%loop, %result]
16594   //   ...
16595   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16596
16597   // Replace with:
16598   //   loop:
16599   //   %addend = phi [%entry, 0], [%loop, %result]
16600   //   ...
16601   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16602
16603   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16604     assert(AddendDef.getOperand(i).isReg());
16605     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16606     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16607     if (&PHISrcInst == MI) {
16608       // Found a matching instruction.
16609       unsigned NewFMAOpc = 0;
16610       switch (MI->getOpcode()) {
16611         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16612         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16613         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16614         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16615         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16616         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16617         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16618         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16619         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16620         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16621         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16622         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16623         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16624         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16625         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16626         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16627         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16628         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16629         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16630         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16631         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16632         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16633         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16634         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16635         default: llvm_unreachable("Unrecognized FMA variant.");
16636       }
16637
16638       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16639       MachineInstrBuilder MIB =
16640         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16641         .addOperand(MI->getOperand(0))
16642         .addOperand(MI->getOperand(3))
16643         .addOperand(MI->getOperand(2))
16644         .addOperand(MI->getOperand(1));
16645       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16646       MI->eraseFromParent();
16647     }
16648   }
16649
16650   return MBB;
16651 }
16652
16653 MachineBasicBlock *
16654 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16655                                                MachineBasicBlock *BB) const {
16656   switch (MI->getOpcode()) {
16657   default: llvm_unreachable("Unexpected instr type to insert");
16658   case X86::TAILJMPd64:
16659   case X86::TAILJMPr64:
16660   case X86::TAILJMPm64:
16661     llvm_unreachable("TAILJMP64 would not be touched here.");
16662   case X86::TCRETURNdi64:
16663   case X86::TCRETURNri64:
16664   case X86::TCRETURNmi64:
16665     return BB;
16666   case X86::WIN_ALLOCA:
16667     return EmitLoweredWinAlloca(MI, BB);
16668   case X86::SEG_ALLOCA_32:
16669     return EmitLoweredSegAlloca(MI, BB, false);
16670   case X86::SEG_ALLOCA_64:
16671     return EmitLoweredSegAlloca(MI, BB, true);
16672   case X86::TLSCall_32:
16673   case X86::TLSCall_64:
16674     return EmitLoweredTLSCall(MI, BB);
16675   case X86::CMOV_GR8:
16676   case X86::CMOV_FR32:
16677   case X86::CMOV_FR64:
16678   case X86::CMOV_V4F32:
16679   case X86::CMOV_V2F64:
16680   case X86::CMOV_V2I64:
16681   case X86::CMOV_V8F32:
16682   case X86::CMOV_V4F64:
16683   case X86::CMOV_V4I64:
16684   case X86::CMOV_V16F32:
16685   case X86::CMOV_V8F64:
16686   case X86::CMOV_V8I64:
16687   case X86::CMOV_GR16:
16688   case X86::CMOV_GR32:
16689   case X86::CMOV_RFP32:
16690   case X86::CMOV_RFP64:
16691   case X86::CMOV_RFP80:
16692     return EmitLoweredSelect(MI, BB);
16693
16694   case X86::FP32_TO_INT16_IN_MEM:
16695   case X86::FP32_TO_INT32_IN_MEM:
16696   case X86::FP32_TO_INT64_IN_MEM:
16697   case X86::FP64_TO_INT16_IN_MEM:
16698   case X86::FP64_TO_INT32_IN_MEM:
16699   case X86::FP64_TO_INT64_IN_MEM:
16700   case X86::FP80_TO_INT16_IN_MEM:
16701   case X86::FP80_TO_INT32_IN_MEM:
16702   case X86::FP80_TO_INT64_IN_MEM: {
16703     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16704     DebugLoc DL = MI->getDebugLoc();
16705
16706     // Change the floating point control register to use "round towards zero"
16707     // mode when truncating to an integer value.
16708     MachineFunction *F = BB->getParent();
16709     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16710     addFrameReference(BuildMI(*BB, MI, DL,
16711                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16712
16713     // Load the old value of the high byte of the control word...
16714     unsigned OldCW =
16715       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16716     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16717                       CWFrameIdx);
16718
16719     // Set the high part to be round to zero...
16720     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16721       .addImm(0xC7F);
16722
16723     // Reload the modified control word now...
16724     addFrameReference(BuildMI(*BB, MI, DL,
16725                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16726
16727     // Restore the memory image of control word to original value
16728     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16729       .addReg(OldCW);
16730
16731     // Get the X86 opcode to use.
16732     unsigned Opc;
16733     switch (MI->getOpcode()) {
16734     default: llvm_unreachable("illegal opcode!");
16735     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16736     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16737     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16738     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16739     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16740     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16741     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16742     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16743     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16744     }
16745
16746     X86AddressMode AM;
16747     MachineOperand &Op = MI->getOperand(0);
16748     if (Op.isReg()) {
16749       AM.BaseType = X86AddressMode::RegBase;
16750       AM.Base.Reg = Op.getReg();
16751     } else {
16752       AM.BaseType = X86AddressMode::FrameIndexBase;
16753       AM.Base.FrameIndex = Op.getIndex();
16754     }
16755     Op = MI->getOperand(1);
16756     if (Op.isImm())
16757       AM.Scale = Op.getImm();
16758     Op = MI->getOperand(2);
16759     if (Op.isImm())
16760       AM.IndexReg = Op.getImm();
16761     Op = MI->getOperand(3);
16762     if (Op.isGlobal()) {
16763       AM.GV = Op.getGlobal();
16764     } else {
16765       AM.Disp = Op.getImm();
16766     }
16767     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16768                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16769
16770     // Reload the original control word now.
16771     addFrameReference(BuildMI(*BB, MI, DL,
16772                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16773
16774     MI->eraseFromParent();   // The pseudo instruction is gone now.
16775     return BB;
16776   }
16777     // String/text processing lowering.
16778   case X86::PCMPISTRM128REG:
16779   case X86::VPCMPISTRM128REG:
16780   case X86::PCMPISTRM128MEM:
16781   case X86::VPCMPISTRM128MEM:
16782   case X86::PCMPESTRM128REG:
16783   case X86::VPCMPESTRM128REG:
16784   case X86::PCMPESTRM128MEM:
16785   case X86::VPCMPESTRM128MEM:
16786     assert(Subtarget->hasSSE42() &&
16787            "Target must have SSE4.2 or AVX features enabled");
16788     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16789
16790   // String/text processing lowering.
16791   case X86::PCMPISTRIREG:
16792   case X86::VPCMPISTRIREG:
16793   case X86::PCMPISTRIMEM:
16794   case X86::VPCMPISTRIMEM:
16795   case X86::PCMPESTRIREG:
16796   case X86::VPCMPESTRIREG:
16797   case X86::PCMPESTRIMEM:
16798   case X86::VPCMPESTRIMEM:
16799     assert(Subtarget->hasSSE42() &&
16800            "Target must have SSE4.2 or AVX features enabled");
16801     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16802
16803   // Thread synchronization.
16804   case X86::MONITOR:
16805     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16806
16807   // xbegin
16808   case X86::XBEGIN:
16809     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16810
16811   // Atomic Lowering.
16812   case X86::ATOMAND8:
16813   case X86::ATOMAND16:
16814   case X86::ATOMAND32:
16815   case X86::ATOMAND64:
16816     // Fall through
16817   case X86::ATOMOR8:
16818   case X86::ATOMOR16:
16819   case X86::ATOMOR32:
16820   case X86::ATOMOR64:
16821     // Fall through
16822   case X86::ATOMXOR16:
16823   case X86::ATOMXOR8:
16824   case X86::ATOMXOR32:
16825   case X86::ATOMXOR64:
16826     // Fall through
16827   case X86::ATOMNAND8:
16828   case X86::ATOMNAND16:
16829   case X86::ATOMNAND32:
16830   case X86::ATOMNAND64:
16831     // Fall through
16832   case X86::ATOMMAX8:
16833   case X86::ATOMMAX16:
16834   case X86::ATOMMAX32:
16835   case X86::ATOMMAX64:
16836     // Fall through
16837   case X86::ATOMMIN8:
16838   case X86::ATOMMIN16:
16839   case X86::ATOMMIN32:
16840   case X86::ATOMMIN64:
16841     // Fall through
16842   case X86::ATOMUMAX8:
16843   case X86::ATOMUMAX16:
16844   case X86::ATOMUMAX32:
16845   case X86::ATOMUMAX64:
16846     // Fall through
16847   case X86::ATOMUMIN8:
16848   case X86::ATOMUMIN16:
16849   case X86::ATOMUMIN32:
16850   case X86::ATOMUMIN64:
16851     return EmitAtomicLoadArith(MI, BB);
16852
16853   // This group does 64-bit operations on a 32-bit host.
16854   case X86::ATOMAND6432:
16855   case X86::ATOMOR6432:
16856   case X86::ATOMXOR6432:
16857   case X86::ATOMNAND6432:
16858   case X86::ATOMADD6432:
16859   case X86::ATOMSUB6432:
16860   case X86::ATOMMAX6432:
16861   case X86::ATOMMIN6432:
16862   case X86::ATOMUMAX6432:
16863   case X86::ATOMUMIN6432:
16864   case X86::ATOMSWAP6432:
16865     return EmitAtomicLoadArith6432(MI, BB);
16866
16867   case X86::VASTART_SAVE_XMM_REGS:
16868     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16869
16870   case X86::VAARG_64:
16871     return EmitVAARG64WithCustomInserter(MI, BB);
16872
16873   case X86::EH_SjLj_SetJmp32:
16874   case X86::EH_SjLj_SetJmp64:
16875     return emitEHSjLjSetJmp(MI, BB);
16876
16877   case X86::EH_SjLj_LongJmp32:
16878   case X86::EH_SjLj_LongJmp64:
16879     return emitEHSjLjLongJmp(MI, BB);
16880
16881   case TargetOpcode::STACKMAP:
16882   case TargetOpcode::PATCHPOINT:
16883     return emitPatchPoint(MI, BB);
16884
16885   case X86::VFMADDPDr213r:
16886   case X86::VFMADDPSr213r:
16887   case X86::VFMADDSDr213r:
16888   case X86::VFMADDSSr213r:
16889   case X86::VFMSUBPDr213r:
16890   case X86::VFMSUBPSr213r:
16891   case X86::VFMSUBSDr213r:
16892   case X86::VFMSUBSSr213r:
16893   case X86::VFNMADDPDr213r:
16894   case X86::VFNMADDPSr213r:
16895   case X86::VFNMADDSDr213r:
16896   case X86::VFNMADDSSr213r:
16897   case X86::VFNMSUBPDr213r:
16898   case X86::VFNMSUBPSr213r:
16899   case X86::VFNMSUBSDr213r:
16900   case X86::VFNMSUBSSr213r:
16901   case X86::VFMADDPDr213rY:
16902   case X86::VFMADDPSr213rY:
16903   case X86::VFMSUBPDr213rY:
16904   case X86::VFMSUBPSr213rY:
16905   case X86::VFNMADDPDr213rY:
16906   case X86::VFNMADDPSr213rY:
16907   case X86::VFNMSUBPDr213rY:
16908   case X86::VFNMSUBPSr213rY:
16909     return emitFMA3Instr(MI, BB);
16910   }
16911 }
16912
16913 //===----------------------------------------------------------------------===//
16914 //                           X86 Optimization Hooks
16915 //===----------------------------------------------------------------------===//
16916
16917 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16918                                                        APInt &KnownZero,
16919                                                        APInt &KnownOne,
16920                                                        const SelectionDAG &DAG,
16921                                                        unsigned Depth) const {
16922   unsigned BitWidth = KnownZero.getBitWidth();
16923   unsigned Opc = Op.getOpcode();
16924   assert((Opc >= ISD::BUILTIN_OP_END ||
16925           Opc == ISD::INTRINSIC_WO_CHAIN ||
16926           Opc == ISD::INTRINSIC_W_CHAIN ||
16927           Opc == ISD::INTRINSIC_VOID) &&
16928          "Should use MaskedValueIsZero if you don't know whether Op"
16929          " is a target node!");
16930
16931   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16932   switch (Opc) {
16933   default: break;
16934   case X86ISD::ADD:
16935   case X86ISD::SUB:
16936   case X86ISD::ADC:
16937   case X86ISD::SBB:
16938   case X86ISD::SMUL:
16939   case X86ISD::UMUL:
16940   case X86ISD::INC:
16941   case X86ISD::DEC:
16942   case X86ISD::OR:
16943   case X86ISD::XOR:
16944   case X86ISD::AND:
16945     // These nodes' second result is a boolean.
16946     if (Op.getResNo() == 0)
16947       break;
16948     // Fallthrough
16949   case X86ISD::SETCC:
16950     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16951     break;
16952   case ISD::INTRINSIC_WO_CHAIN: {
16953     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16954     unsigned NumLoBits = 0;
16955     switch (IntId) {
16956     default: break;
16957     case Intrinsic::x86_sse_movmsk_ps:
16958     case Intrinsic::x86_avx_movmsk_ps_256:
16959     case Intrinsic::x86_sse2_movmsk_pd:
16960     case Intrinsic::x86_avx_movmsk_pd_256:
16961     case Intrinsic::x86_mmx_pmovmskb:
16962     case Intrinsic::x86_sse2_pmovmskb_128:
16963     case Intrinsic::x86_avx2_pmovmskb: {
16964       // High bits of movmskp{s|d}, pmovmskb are known zero.
16965       switch (IntId) {
16966         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16967         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16968         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16969         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16970         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16971         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16972         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16973         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16974       }
16975       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16976       break;
16977     }
16978     }
16979     break;
16980   }
16981   }
16982 }
16983
16984 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16985   SDValue Op,
16986   const SelectionDAG &,
16987   unsigned Depth) const {
16988   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16989   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16990     return Op.getValueType().getScalarType().getSizeInBits();
16991
16992   // Fallback case.
16993   return 1;
16994 }
16995
16996 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16997 /// node is a GlobalAddress + offset.
16998 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16999                                        const GlobalValue* &GA,
17000                                        int64_t &Offset) const {
17001   if (N->getOpcode() == X86ISD::Wrapper) {
17002     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17003       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17004       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17005       return true;
17006     }
17007   }
17008   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17009 }
17010
17011 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17012 /// same as extracting the high 128-bit part of 256-bit vector and then
17013 /// inserting the result into the low part of a new 256-bit vector
17014 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17015   EVT VT = SVOp->getValueType(0);
17016   unsigned NumElems = VT.getVectorNumElements();
17017
17018   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17019   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17020     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17021         SVOp->getMaskElt(j) >= 0)
17022       return false;
17023
17024   return true;
17025 }
17026
17027 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17028 /// same as extracting the low 128-bit part of 256-bit vector and then
17029 /// inserting the result into the high part of a new 256-bit vector
17030 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17031   EVT VT = SVOp->getValueType(0);
17032   unsigned NumElems = VT.getVectorNumElements();
17033
17034   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17035   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17036     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17037         SVOp->getMaskElt(j) >= 0)
17038       return false;
17039
17040   return true;
17041 }
17042
17043 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17044 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17045                                         TargetLowering::DAGCombinerInfo &DCI,
17046                                         const X86Subtarget* Subtarget) {
17047   SDLoc dl(N);
17048   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17049   SDValue V1 = SVOp->getOperand(0);
17050   SDValue V2 = SVOp->getOperand(1);
17051   EVT VT = SVOp->getValueType(0);
17052   unsigned NumElems = VT.getVectorNumElements();
17053
17054   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17055       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17056     //
17057     //                   0,0,0,...
17058     //                      |
17059     //    V      UNDEF    BUILD_VECTOR    UNDEF
17060     //     \      /           \           /
17061     //  CONCAT_VECTOR         CONCAT_VECTOR
17062     //         \                  /
17063     //          \                /
17064     //          RESULT: V + zero extended
17065     //
17066     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17067         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17068         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17069       return SDValue();
17070
17071     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17072       return SDValue();
17073
17074     // To match the shuffle mask, the first half of the mask should
17075     // be exactly the first vector, and all the rest a splat with the
17076     // first element of the second one.
17077     for (unsigned i = 0; i != NumElems/2; ++i)
17078       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17079           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17080         return SDValue();
17081
17082     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17083     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17084       if (Ld->hasNUsesOfValue(1, 0)) {
17085         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17086         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17087         SDValue ResNode =
17088           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17089                                   Ld->getMemoryVT(),
17090                                   Ld->getPointerInfo(),
17091                                   Ld->getAlignment(),
17092                                   false/*isVolatile*/, true/*ReadMem*/,
17093                                   false/*WriteMem*/);
17094
17095         // Make sure the newly-created LOAD is in the same position as Ld in
17096         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17097         // and update uses of Ld's output chain to use the TokenFactor.
17098         if (Ld->hasAnyUseOfValue(1)) {
17099           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17100                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17101           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17102           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17103                                  SDValue(ResNode.getNode(), 1));
17104         }
17105
17106         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17107       }
17108     }
17109
17110     // Emit a zeroed vector and insert the desired subvector on its
17111     // first half.
17112     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17113     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17114     return DCI.CombineTo(N, InsV);
17115   }
17116
17117   //===--------------------------------------------------------------------===//
17118   // Combine some shuffles into subvector extracts and inserts:
17119   //
17120
17121   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17122   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17123     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17124     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17125     return DCI.CombineTo(N, InsV);
17126   }
17127
17128   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17129   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17130     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17131     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17132     return DCI.CombineTo(N, InsV);
17133   }
17134
17135   return SDValue();
17136 }
17137
17138 /// PerformShuffleCombine - Performs several different shuffle combines.
17139 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17140                                      TargetLowering::DAGCombinerInfo &DCI,
17141                                      const X86Subtarget *Subtarget) {
17142   SDLoc dl(N);
17143   EVT VT = N->getValueType(0);
17144
17145   // Don't create instructions with illegal types after legalize types has run.
17146   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17147   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17148     return SDValue();
17149
17150   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17151   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17152       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17153     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17154
17155   // Only handle 128 wide vector from here on.
17156   if (!VT.is128BitVector())
17157     return SDValue();
17158
17159   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17160   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17161   // consecutive, non-overlapping, and in the right order.
17162   SmallVector<SDValue, 16> Elts;
17163   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17164     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17165
17166   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17167 }
17168
17169 /// PerformTruncateCombine - Converts truncate operation to
17170 /// a sequence of vector shuffle operations.
17171 /// It is possible when we truncate 256-bit vector to 128-bit vector
17172 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17173                                       TargetLowering::DAGCombinerInfo &DCI,
17174                                       const X86Subtarget *Subtarget)  {
17175   return SDValue();
17176 }
17177
17178 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17179 /// specific shuffle of a load can be folded into a single element load.
17180 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17181 /// shuffles have been customed lowered so we need to handle those here.
17182 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17183                                          TargetLowering::DAGCombinerInfo &DCI) {
17184   if (DCI.isBeforeLegalizeOps())
17185     return SDValue();
17186
17187   SDValue InVec = N->getOperand(0);
17188   SDValue EltNo = N->getOperand(1);
17189
17190   if (!isa<ConstantSDNode>(EltNo))
17191     return SDValue();
17192
17193   EVT VT = InVec.getValueType();
17194
17195   bool HasShuffleIntoBitcast = false;
17196   if (InVec.getOpcode() == ISD::BITCAST) {
17197     // Don't duplicate a load with other uses.
17198     if (!InVec.hasOneUse())
17199       return SDValue();
17200     EVT BCVT = InVec.getOperand(0).getValueType();
17201     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17202       return SDValue();
17203     InVec = InVec.getOperand(0);
17204     HasShuffleIntoBitcast = true;
17205   }
17206
17207   if (!isTargetShuffle(InVec.getOpcode()))
17208     return SDValue();
17209
17210   // Don't duplicate a load with other uses.
17211   if (!InVec.hasOneUse())
17212     return SDValue();
17213
17214   SmallVector<int, 16> ShuffleMask;
17215   bool UnaryShuffle;
17216   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17217                             UnaryShuffle))
17218     return SDValue();
17219
17220   // Select the input vector, guarding against out of range extract vector.
17221   unsigned NumElems = VT.getVectorNumElements();
17222   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17223   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17224   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17225                                          : InVec.getOperand(1);
17226
17227   // If inputs to shuffle are the same for both ops, then allow 2 uses
17228   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17229
17230   if (LdNode.getOpcode() == ISD::BITCAST) {
17231     // Don't duplicate a load with other uses.
17232     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17233       return SDValue();
17234
17235     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17236     LdNode = LdNode.getOperand(0);
17237   }
17238
17239   if (!ISD::isNormalLoad(LdNode.getNode()))
17240     return SDValue();
17241
17242   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17243
17244   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17245     return SDValue();
17246
17247   if (HasShuffleIntoBitcast) {
17248     // If there's a bitcast before the shuffle, check if the load type and
17249     // alignment is valid.
17250     unsigned Align = LN0->getAlignment();
17251     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17252     unsigned NewAlign = TLI.getDataLayout()->
17253       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17254
17255     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17256       return SDValue();
17257   }
17258
17259   // All checks match so transform back to vector_shuffle so that DAG combiner
17260   // can finish the job
17261   SDLoc dl(N);
17262
17263   // Create shuffle node taking into account the case that its a unary shuffle
17264   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17265   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17266                                  InVec.getOperand(0), Shuffle,
17267                                  &ShuffleMask[0]);
17268   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17269   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17270                      EltNo);
17271 }
17272
17273 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17274 /// generation and convert it from being a bunch of shuffles and extracts
17275 /// to a simple store and scalar loads to extract the elements.
17276 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17277                                          TargetLowering::DAGCombinerInfo &DCI) {
17278   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17279   if (NewOp.getNode())
17280     return NewOp;
17281
17282   SDValue InputVector = N->getOperand(0);
17283
17284   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17285   // from mmx to v2i32 has a single usage.
17286   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17287       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17288       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17289     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17290                        N->getValueType(0),
17291                        InputVector.getNode()->getOperand(0));
17292
17293   // Only operate on vectors of 4 elements, where the alternative shuffling
17294   // gets to be more expensive.
17295   if (InputVector.getValueType() != MVT::v4i32)
17296     return SDValue();
17297
17298   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17299   // single use which is a sign-extend or zero-extend, and all elements are
17300   // used.
17301   SmallVector<SDNode *, 4> Uses;
17302   unsigned ExtractedElements = 0;
17303   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17304        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17305     if (UI.getUse().getResNo() != InputVector.getResNo())
17306       return SDValue();
17307
17308     SDNode *Extract = *UI;
17309     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17310       return SDValue();
17311
17312     if (Extract->getValueType(0) != MVT::i32)
17313       return SDValue();
17314     if (!Extract->hasOneUse())
17315       return SDValue();
17316     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17317         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17318       return SDValue();
17319     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17320       return SDValue();
17321
17322     // Record which element was extracted.
17323     ExtractedElements |=
17324       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17325
17326     Uses.push_back(Extract);
17327   }
17328
17329   // If not all the elements were used, this may not be worthwhile.
17330   if (ExtractedElements != 15)
17331     return SDValue();
17332
17333   // Ok, we've now decided to do the transformation.
17334   SDLoc dl(InputVector);
17335
17336   // Store the value to a temporary stack slot.
17337   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17338   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17339                             MachinePointerInfo(), false, false, 0);
17340
17341   // Replace each use (extract) with a load of the appropriate element.
17342   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17343        UE = Uses.end(); UI != UE; ++UI) {
17344     SDNode *Extract = *UI;
17345
17346     // cOMpute the element's address.
17347     SDValue Idx = Extract->getOperand(1);
17348     unsigned EltSize =
17349         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17350     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17351     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17352     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17353
17354     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17355                                      StackPtr, OffsetVal);
17356
17357     // Load the scalar.
17358     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17359                                      ScalarAddr, MachinePointerInfo(),
17360                                      false, false, false, 0);
17361
17362     // Replace the exact with the load.
17363     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17364   }
17365
17366   // The replacement was made in place; don't return anything.
17367   return SDValue();
17368 }
17369
17370 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17371 static std::pair<unsigned, bool>
17372 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17373                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17374   if (!VT.isVector())
17375     return std::make_pair(0, false);
17376
17377   bool NeedSplit = false;
17378   switch (VT.getSimpleVT().SimpleTy) {
17379   default: return std::make_pair(0, false);
17380   case MVT::v32i8:
17381   case MVT::v16i16:
17382   case MVT::v8i32:
17383     if (!Subtarget->hasAVX2())
17384       NeedSplit = true;
17385     if (!Subtarget->hasAVX())
17386       return std::make_pair(0, false);
17387     break;
17388   case MVT::v16i8:
17389   case MVT::v8i16:
17390   case MVT::v4i32:
17391     if (!Subtarget->hasSSE2())
17392       return std::make_pair(0, false);
17393   }
17394
17395   // SSE2 has only a small subset of the operations.
17396   bool hasUnsigned = Subtarget->hasSSE41() ||
17397                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17398   bool hasSigned = Subtarget->hasSSE41() ||
17399                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17400
17401   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17402
17403   unsigned Opc = 0;
17404   // Check for x CC y ? x : y.
17405   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17406       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17407     switch (CC) {
17408     default: break;
17409     case ISD::SETULT:
17410     case ISD::SETULE:
17411       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17412     case ISD::SETUGT:
17413     case ISD::SETUGE:
17414       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17415     case ISD::SETLT:
17416     case ISD::SETLE:
17417       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17418     case ISD::SETGT:
17419     case ISD::SETGE:
17420       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17421     }
17422   // Check for x CC y ? y : x -- a min/max with reversed arms.
17423   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17424              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17425     switch (CC) {
17426     default: break;
17427     case ISD::SETULT:
17428     case ISD::SETULE:
17429       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17430     case ISD::SETUGT:
17431     case ISD::SETUGE:
17432       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17433     case ISD::SETLT:
17434     case ISD::SETLE:
17435       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17436     case ISD::SETGT:
17437     case ISD::SETGE:
17438       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17439     }
17440   }
17441
17442   return std::make_pair(Opc, NeedSplit);
17443 }
17444
17445 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17446 /// nodes.
17447 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17448                                     TargetLowering::DAGCombinerInfo &DCI,
17449                                     const X86Subtarget *Subtarget) {
17450   SDLoc DL(N);
17451   SDValue Cond = N->getOperand(0);
17452   // Get the LHS/RHS of the select.
17453   SDValue LHS = N->getOperand(1);
17454   SDValue RHS = N->getOperand(2);
17455   EVT VT = LHS.getValueType();
17456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17457
17458   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17459   // instructions match the semantics of the common C idiom x<y?x:y but not
17460   // x<=y?x:y, because of how they handle negative zero (which can be
17461   // ignored in unsafe-math mode).
17462   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17463       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17464       (Subtarget->hasSSE2() ||
17465        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17466     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17467
17468     unsigned Opcode = 0;
17469     // Check for x CC y ? x : y.
17470     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17471         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17472       switch (CC) {
17473       default: break;
17474       case ISD::SETULT:
17475         // Converting this to a min would handle NaNs incorrectly, and swapping
17476         // the operands would cause it to handle comparisons between positive
17477         // and negative zero incorrectly.
17478         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17479           if (!DAG.getTarget().Options.UnsafeFPMath &&
17480               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17481             break;
17482           std::swap(LHS, RHS);
17483         }
17484         Opcode = X86ISD::FMIN;
17485         break;
17486       case ISD::SETOLE:
17487         // Converting this to a min would handle comparisons between positive
17488         // and negative zero incorrectly.
17489         if (!DAG.getTarget().Options.UnsafeFPMath &&
17490             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17491           break;
17492         Opcode = X86ISD::FMIN;
17493         break;
17494       case ISD::SETULE:
17495         // Converting this to a min would handle both negative zeros and NaNs
17496         // incorrectly, but we can swap the operands to fix both.
17497         std::swap(LHS, RHS);
17498       case ISD::SETOLT:
17499       case ISD::SETLT:
17500       case ISD::SETLE:
17501         Opcode = X86ISD::FMIN;
17502         break;
17503
17504       case ISD::SETOGE:
17505         // Converting this to a max would handle comparisons between positive
17506         // and negative zero incorrectly.
17507         if (!DAG.getTarget().Options.UnsafeFPMath &&
17508             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17509           break;
17510         Opcode = X86ISD::FMAX;
17511         break;
17512       case ISD::SETUGT:
17513         // Converting this to a max would handle NaNs incorrectly, and swapping
17514         // the operands would cause it to handle comparisons between positive
17515         // and negative zero incorrectly.
17516         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17517           if (!DAG.getTarget().Options.UnsafeFPMath &&
17518               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17519             break;
17520           std::swap(LHS, RHS);
17521         }
17522         Opcode = X86ISD::FMAX;
17523         break;
17524       case ISD::SETUGE:
17525         // Converting this to a max would handle both negative zeros and NaNs
17526         // incorrectly, but we can swap the operands to fix both.
17527         std::swap(LHS, RHS);
17528       case ISD::SETOGT:
17529       case ISD::SETGT:
17530       case ISD::SETGE:
17531         Opcode = X86ISD::FMAX;
17532         break;
17533       }
17534     // Check for x CC y ? y : x -- a min/max with reversed arms.
17535     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17536                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17537       switch (CC) {
17538       default: break;
17539       case ISD::SETOGE:
17540         // Converting this to a min would handle comparisons between positive
17541         // and negative zero incorrectly, and swapping the operands would
17542         // cause it to handle NaNs incorrectly.
17543         if (!DAG.getTarget().Options.UnsafeFPMath &&
17544             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17545           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17546             break;
17547           std::swap(LHS, RHS);
17548         }
17549         Opcode = X86ISD::FMIN;
17550         break;
17551       case ISD::SETUGT:
17552         // Converting this to a min would handle NaNs incorrectly.
17553         if (!DAG.getTarget().Options.UnsafeFPMath &&
17554             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17555           break;
17556         Opcode = X86ISD::FMIN;
17557         break;
17558       case ISD::SETUGE:
17559         // Converting this to a min would handle both negative zeros and NaNs
17560         // incorrectly, but we can swap the operands to fix both.
17561         std::swap(LHS, RHS);
17562       case ISD::SETOGT:
17563       case ISD::SETGT:
17564       case ISD::SETGE:
17565         Opcode = X86ISD::FMIN;
17566         break;
17567
17568       case ISD::SETULT:
17569         // Converting this to a max would handle NaNs incorrectly.
17570         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17571           break;
17572         Opcode = X86ISD::FMAX;
17573         break;
17574       case ISD::SETOLE:
17575         // Converting this to a max would handle comparisons between positive
17576         // and negative zero incorrectly, and swapping the operands would
17577         // cause it to handle NaNs incorrectly.
17578         if (!DAG.getTarget().Options.UnsafeFPMath &&
17579             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17580           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17581             break;
17582           std::swap(LHS, RHS);
17583         }
17584         Opcode = X86ISD::FMAX;
17585         break;
17586       case ISD::SETULE:
17587         // Converting this to a max would handle both negative zeros and NaNs
17588         // incorrectly, but we can swap the operands to fix both.
17589         std::swap(LHS, RHS);
17590       case ISD::SETOLT:
17591       case ISD::SETLT:
17592       case ISD::SETLE:
17593         Opcode = X86ISD::FMAX;
17594         break;
17595       }
17596     }
17597
17598     if (Opcode)
17599       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17600   }
17601
17602   EVT CondVT = Cond.getValueType();
17603   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17604       CondVT.getVectorElementType() == MVT::i1) {
17605     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17606     // lowering on AVX-512. In this case we convert it to
17607     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17608     // The same situation for all 128 and 256-bit vectors of i8 and i16
17609     EVT OpVT = LHS.getValueType();
17610     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17611         (OpVT.getVectorElementType() == MVT::i8 ||
17612          OpVT.getVectorElementType() == MVT::i16)) {
17613       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17614       DCI.AddToWorklist(Cond.getNode());
17615       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17616     }
17617   }
17618   // If this is a select between two integer constants, try to do some
17619   // optimizations.
17620   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17621     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17622       // Don't do this for crazy integer types.
17623       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17624         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17625         // so that TrueC (the true value) is larger than FalseC.
17626         bool NeedsCondInvert = false;
17627
17628         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17629             // Efficiently invertible.
17630             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17631              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17632               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17633           NeedsCondInvert = true;
17634           std::swap(TrueC, FalseC);
17635         }
17636
17637         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17638         if (FalseC->getAPIntValue() == 0 &&
17639             TrueC->getAPIntValue().isPowerOf2()) {
17640           if (NeedsCondInvert) // Invert the condition if needed.
17641             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17642                                DAG.getConstant(1, Cond.getValueType()));
17643
17644           // Zero extend the condition if needed.
17645           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17646
17647           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17648           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17649                              DAG.getConstant(ShAmt, MVT::i8));
17650         }
17651
17652         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17653         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17654           if (NeedsCondInvert) // Invert the condition if needed.
17655             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17656                                DAG.getConstant(1, Cond.getValueType()));
17657
17658           // Zero extend the condition if needed.
17659           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17660                              FalseC->getValueType(0), Cond);
17661           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17662                              SDValue(FalseC, 0));
17663         }
17664
17665         // Optimize cases that will turn into an LEA instruction.  This requires
17666         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17667         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17668           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17669           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17670
17671           bool isFastMultiplier = false;
17672           if (Diff < 10) {
17673             switch ((unsigned char)Diff) {
17674               default: break;
17675               case 1:  // result = add base, cond
17676               case 2:  // result = lea base(    , cond*2)
17677               case 3:  // result = lea base(cond, cond*2)
17678               case 4:  // result = lea base(    , cond*4)
17679               case 5:  // result = lea base(cond, cond*4)
17680               case 8:  // result = lea base(    , cond*8)
17681               case 9:  // result = lea base(cond, cond*8)
17682                 isFastMultiplier = true;
17683                 break;
17684             }
17685           }
17686
17687           if (isFastMultiplier) {
17688             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17689             if (NeedsCondInvert) // Invert the condition if needed.
17690               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17691                                  DAG.getConstant(1, Cond.getValueType()));
17692
17693             // Zero extend the condition if needed.
17694             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17695                                Cond);
17696             // Scale the condition by the difference.
17697             if (Diff != 1)
17698               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17699                                  DAG.getConstant(Diff, Cond.getValueType()));
17700
17701             // Add the base if non-zero.
17702             if (FalseC->getAPIntValue() != 0)
17703               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17704                                  SDValue(FalseC, 0));
17705             return Cond;
17706           }
17707         }
17708       }
17709   }
17710
17711   // Canonicalize max and min:
17712   // (x > y) ? x : y -> (x >= y) ? x : y
17713   // (x < y) ? x : y -> (x <= y) ? x : y
17714   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17715   // the need for an extra compare
17716   // against zero. e.g.
17717   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17718   // subl   %esi, %edi
17719   // testl  %edi, %edi
17720   // movl   $0, %eax
17721   // cmovgl %edi, %eax
17722   // =>
17723   // xorl   %eax, %eax
17724   // subl   %esi, $edi
17725   // cmovsl %eax, %edi
17726   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17727       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17728       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17729     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17730     switch (CC) {
17731     default: break;
17732     case ISD::SETLT:
17733     case ISD::SETGT: {
17734       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17735       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17736                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17737       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17738     }
17739     }
17740   }
17741
17742   // Early exit check
17743   if (!TLI.isTypeLegal(VT))
17744     return SDValue();
17745
17746   // Match VSELECTs into subs with unsigned saturation.
17747   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17748       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17749       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17750        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17751     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17752
17753     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17754     // left side invert the predicate to simplify logic below.
17755     SDValue Other;
17756     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17757       Other = RHS;
17758       CC = ISD::getSetCCInverse(CC, true);
17759     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17760       Other = LHS;
17761     }
17762
17763     if (Other.getNode() && Other->getNumOperands() == 2 &&
17764         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17765       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17766       SDValue CondRHS = Cond->getOperand(1);
17767
17768       // Look for a general sub with unsigned saturation first.
17769       // x >= y ? x-y : 0 --> subus x, y
17770       // x >  y ? x-y : 0 --> subus x, y
17771       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17772           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17773         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17774
17775       // If the RHS is a constant we have to reverse the const canonicalization.
17776       // x > C-1 ? x+-C : 0 --> subus x, C
17777       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17778           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17779         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17780         if (CondRHS.getConstantOperandVal(0) == -A-1)
17781           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17782                              DAG.getConstant(-A, VT));
17783       }
17784
17785       // Another special case: If C was a sign bit, the sub has been
17786       // canonicalized into a xor.
17787       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17788       //        it's safe to decanonicalize the xor?
17789       // x s< 0 ? x^C : 0 --> subus x, C
17790       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17791           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17792           isSplatVector(OpRHS.getNode())) {
17793         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17794         if (A.isSignBit())
17795           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17796       }
17797     }
17798   }
17799
17800   // Try to match a min/max vector operation.
17801   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17802     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17803     unsigned Opc = ret.first;
17804     bool NeedSplit = ret.second;
17805
17806     if (Opc && NeedSplit) {
17807       unsigned NumElems = VT.getVectorNumElements();
17808       // Extract the LHS vectors
17809       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17810       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17811
17812       // Extract the RHS vectors
17813       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17814       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17815
17816       // Create min/max for each subvector
17817       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17818       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17819
17820       // Merge the result
17821       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17822     } else if (Opc)
17823       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17824   }
17825
17826   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17827   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17828       // Check if SETCC has already been promoted
17829       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17830       // Check that condition value type matches vselect operand type
17831       CondVT == VT) { 
17832
17833     assert(Cond.getValueType().isVector() &&
17834            "vector select expects a vector selector!");
17835
17836     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17837     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17838
17839     if (!TValIsAllOnes && !FValIsAllZeros) {
17840       // Try invert the condition if true value is not all 1s and false value
17841       // is not all 0s.
17842       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17843       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17844
17845       if (TValIsAllZeros || FValIsAllOnes) {
17846         SDValue CC = Cond.getOperand(2);
17847         ISD::CondCode NewCC =
17848           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17849                                Cond.getOperand(0).getValueType().isInteger());
17850         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17851         std::swap(LHS, RHS);
17852         TValIsAllOnes = FValIsAllOnes;
17853         FValIsAllZeros = TValIsAllZeros;
17854       }
17855     }
17856
17857     if (TValIsAllOnes || FValIsAllZeros) {
17858       SDValue Ret;
17859
17860       if (TValIsAllOnes && FValIsAllZeros)
17861         Ret = Cond;
17862       else if (TValIsAllOnes)
17863         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17864                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17865       else if (FValIsAllZeros)
17866         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17867                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17868
17869       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17870     }
17871   }
17872
17873   // Try to fold this VSELECT into a MOVSS/MOVSD
17874   if (N->getOpcode() == ISD::VSELECT &&
17875       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17876     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17877         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17878       bool CanFold = false;
17879       unsigned NumElems = Cond.getNumOperands();
17880       SDValue A = LHS;
17881       SDValue B = RHS;
17882       
17883       if (isZero(Cond.getOperand(0))) {
17884         CanFold = true;
17885
17886         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17887         // fold (vselect <0,-1> -> (movsd A, B)
17888         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17889           CanFold = isAllOnes(Cond.getOperand(i));
17890       } else if (isAllOnes(Cond.getOperand(0))) {
17891         CanFold = true;
17892         std::swap(A, B);
17893
17894         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17895         // fold (vselect <-1,0> -> (movsd B, A)
17896         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17897           CanFold = isZero(Cond.getOperand(i));
17898       }
17899
17900       if (CanFold) {
17901         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17902           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17903         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17904       }
17905
17906       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17907         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17908         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17909         //                             (v2i64 (bitcast B)))))
17910         //
17911         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17912         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17913         //                             (v2f64 (bitcast B)))))
17914         //
17915         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17916         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17917         //                             (v2i64 (bitcast A)))))
17918         //
17919         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17920         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17921         //                             (v2f64 (bitcast A)))))
17922
17923         CanFold = (isZero(Cond.getOperand(0)) &&
17924                    isZero(Cond.getOperand(1)) &&
17925                    isAllOnes(Cond.getOperand(2)) &&
17926                    isAllOnes(Cond.getOperand(3)));
17927
17928         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17929             isAllOnes(Cond.getOperand(1)) &&
17930             isZero(Cond.getOperand(2)) &&
17931             isZero(Cond.getOperand(3))) {
17932           CanFold = true;
17933           std::swap(LHS, RHS);
17934         }
17935
17936         if (CanFold) {
17937           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17938           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17939           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17940           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17941                                                 NewB, DAG);
17942           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17943         }
17944       }
17945     }
17946   }
17947
17948   // If we know that this node is legal then we know that it is going to be
17949   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17950   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17951   // to simplify previous instructions.
17952   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17953       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17954     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17955
17956     // Don't optimize vector selects that map to mask-registers.
17957     if (BitWidth == 1)
17958       return SDValue();
17959
17960     // Check all uses of that condition operand to check whether it will be
17961     // consumed by non-BLEND instructions, which may depend on all bits are set
17962     // properly.
17963     for (SDNode::use_iterator I = Cond->use_begin(),
17964                               E = Cond->use_end(); I != E; ++I)
17965       if (I->getOpcode() != ISD::VSELECT)
17966         // TODO: Add other opcodes eventually lowered into BLEND.
17967         return SDValue();
17968
17969     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17970     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17971
17972     APInt KnownZero, KnownOne;
17973     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17974                                           DCI.isBeforeLegalizeOps());
17975     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17976         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17977       DCI.CommitTargetLoweringOpt(TLO);
17978   }
17979
17980   return SDValue();
17981 }
17982
17983 // Check whether a boolean test is testing a boolean value generated by
17984 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17985 // code.
17986 //
17987 // Simplify the following patterns:
17988 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17989 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17990 // to (Op EFLAGS Cond)
17991 //
17992 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17993 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17994 // to (Op EFLAGS !Cond)
17995 //
17996 // where Op could be BRCOND or CMOV.
17997 //
17998 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17999   // Quit if not CMP and SUB with its value result used.
18000   if (Cmp.getOpcode() != X86ISD::CMP &&
18001       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18002       return SDValue();
18003
18004   // Quit if not used as a boolean value.
18005   if (CC != X86::COND_E && CC != X86::COND_NE)
18006     return SDValue();
18007
18008   // Check CMP operands. One of them should be 0 or 1 and the other should be
18009   // an SetCC or extended from it.
18010   SDValue Op1 = Cmp.getOperand(0);
18011   SDValue Op2 = Cmp.getOperand(1);
18012
18013   SDValue SetCC;
18014   const ConstantSDNode* C = nullptr;
18015   bool needOppositeCond = (CC == X86::COND_E);
18016   bool checkAgainstTrue = false; // Is it a comparison against 1?
18017
18018   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18019     SetCC = Op2;
18020   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18021     SetCC = Op1;
18022   else // Quit if all operands are not constants.
18023     return SDValue();
18024
18025   if (C->getZExtValue() == 1) {
18026     needOppositeCond = !needOppositeCond;
18027     checkAgainstTrue = true;
18028   } else if (C->getZExtValue() != 0)
18029     // Quit if the constant is neither 0 or 1.
18030     return SDValue();
18031
18032   bool truncatedToBoolWithAnd = false;
18033   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18034   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18035          SetCC.getOpcode() == ISD::TRUNCATE ||
18036          SetCC.getOpcode() == ISD::AND) {
18037     if (SetCC.getOpcode() == ISD::AND) {
18038       int OpIdx = -1;
18039       ConstantSDNode *CS;
18040       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18041           CS->getZExtValue() == 1)
18042         OpIdx = 1;
18043       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18044           CS->getZExtValue() == 1)
18045         OpIdx = 0;
18046       if (OpIdx == -1)
18047         break;
18048       SetCC = SetCC.getOperand(OpIdx);
18049       truncatedToBoolWithAnd = true;
18050     } else
18051       SetCC = SetCC.getOperand(0);
18052   }
18053
18054   switch (SetCC.getOpcode()) {
18055   case X86ISD::SETCC_CARRY:
18056     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18057     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18058     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18059     // truncated to i1 using 'and'.
18060     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18061       break;
18062     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18063            "Invalid use of SETCC_CARRY!");
18064     // FALL THROUGH
18065   case X86ISD::SETCC:
18066     // Set the condition code or opposite one if necessary.
18067     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18068     if (needOppositeCond)
18069       CC = X86::GetOppositeBranchCondition(CC);
18070     return SetCC.getOperand(1);
18071   case X86ISD::CMOV: {
18072     // Check whether false/true value has canonical one, i.e. 0 or 1.
18073     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18074     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18075     // Quit if true value is not a constant.
18076     if (!TVal)
18077       return SDValue();
18078     // Quit if false value is not a constant.
18079     if (!FVal) {
18080       SDValue Op = SetCC.getOperand(0);
18081       // Skip 'zext' or 'trunc' node.
18082       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18083           Op.getOpcode() == ISD::TRUNCATE)
18084         Op = Op.getOperand(0);
18085       // A special case for rdrand/rdseed, where 0 is set if false cond is
18086       // found.
18087       if ((Op.getOpcode() != X86ISD::RDRAND &&
18088            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18089         return SDValue();
18090     }
18091     // Quit if false value is not the constant 0 or 1.
18092     bool FValIsFalse = true;
18093     if (FVal && FVal->getZExtValue() != 0) {
18094       if (FVal->getZExtValue() != 1)
18095         return SDValue();
18096       // If FVal is 1, opposite cond is needed.
18097       needOppositeCond = !needOppositeCond;
18098       FValIsFalse = false;
18099     }
18100     // Quit if TVal is not the constant opposite of FVal.
18101     if (FValIsFalse && TVal->getZExtValue() != 1)
18102       return SDValue();
18103     if (!FValIsFalse && TVal->getZExtValue() != 0)
18104       return SDValue();
18105     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18106     if (needOppositeCond)
18107       CC = X86::GetOppositeBranchCondition(CC);
18108     return SetCC.getOperand(3);
18109   }
18110   }
18111
18112   return SDValue();
18113 }
18114
18115 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18116 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18117                                   TargetLowering::DAGCombinerInfo &DCI,
18118                                   const X86Subtarget *Subtarget) {
18119   SDLoc DL(N);
18120
18121   // If the flag operand isn't dead, don't touch this CMOV.
18122   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18123     return SDValue();
18124
18125   SDValue FalseOp = N->getOperand(0);
18126   SDValue TrueOp = N->getOperand(1);
18127   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18128   SDValue Cond = N->getOperand(3);
18129
18130   if (CC == X86::COND_E || CC == X86::COND_NE) {
18131     switch (Cond.getOpcode()) {
18132     default: break;
18133     case X86ISD::BSR:
18134     case X86ISD::BSF:
18135       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18136       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18137         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18138     }
18139   }
18140
18141   SDValue Flags;
18142
18143   Flags = checkBoolTestSetCCCombine(Cond, CC);
18144   if (Flags.getNode() &&
18145       // Extra check as FCMOV only supports a subset of X86 cond.
18146       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18147     SDValue Ops[] = { FalseOp, TrueOp,
18148                       DAG.getConstant(CC, MVT::i8), Flags };
18149     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18150   }
18151
18152   // If this is a select between two integer constants, try to do some
18153   // optimizations.  Note that the operands are ordered the opposite of SELECT
18154   // operands.
18155   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18156     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18157       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18158       // larger than FalseC (the false value).
18159       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18160         CC = X86::GetOppositeBranchCondition(CC);
18161         std::swap(TrueC, FalseC);
18162         std::swap(TrueOp, FalseOp);
18163       }
18164
18165       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18166       // This is efficient for any integer data type (including i8/i16) and
18167       // shift amount.
18168       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18169         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18170                            DAG.getConstant(CC, MVT::i8), Cond);
18171
18172         // Zero extend the condition if needed.
18173         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18174
18175         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18176         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18177                            DAG.getConstant(ShAmt, MVT::i8));
18178         if (N->getNumValues() == 2)  // Dead flag value?
18179           return DCI.CombineTo(N, Cond, SDValue());
18180         return Cond;
18181       }
18182
18183       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18184       // for any integer data type, including i8/i16.
18185       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18186         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18187                            DAG.getConstant(CC, MVT::i8), Cond);
18188
18189         // Zero extend the condition if needed.
18190         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18191                            FalseC->getValueType(0), Cond);
18192         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18193                            SDValue(FalseC, 0));
18194
18195         if (N->getNumValues() == 2)  // Dead flag value?
18196           return DCI.CombineTo(N, Cond, SDValue());
18197         return Cond;
18198       }
18199
18200       // Optimize cases that will turn into an LEA instruction.  This requires
18201       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18202       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18203         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18204         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18205
18206         bool isFastMultiplier = false;
18207         if (Diff < 10) {
18208           switch ((unsigned char)Diff) {
18209           default: break;
18210           case 1:  // result = add base, cond
18211           case 2:  // result = lea base(    , cond*2)
18212           case 3:  // result = lea base(cond, cond*2)
18213           case 4:  // result = lea base(    , cond*4)
18214           case 5:  // result = lea base(cond, cond*4)
18215           case 8:  // result = lea base(    , cond*8)
18216           case 9:  // result = lea base(cond, cond*8)
18217             isFastMultiplier = true;
18218             break;
18219           }
18220         }
18221
18222         if (isFastMultiplier) {
18223           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18224           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18225                              DAG.getConstant(CC, MVT::i8), Cond);
18226           // Zero extend the condition if needed.
18227           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18228                              Cond);
18229           // Scale the condition by the difference.
18230           if (Diff != 1)
18231             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18232                                DAG.getConstant(Diff, Cond.getValueType()));
18233
18234           // Add the base if non-zero.
18235           if (FalseC->getAPIntValue() != 0)
18236             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18237                                SDValue(FalseC, 0));
18238           if (N->getNumValues() == 2)  // Dead flag value?
18239             return DCI.CombineTo(N, Cond, SDValue());
18240           return Cond;
18241         }
18242       }
18243     }
18244   }
18245
18246   // Handle these cases:
18247   //   (select (x != c), e, c) -> select (x != c), e, x),
18248   //   (select (x == c), c, e) -> select (x == c), x, e)
18249   // where the c is an integer constant, and the "select" is the combination
18250   // of CMOV and CMP.
18251   //
18252   // The rationale for this change is that the conditional-move from a constant
18253   // needs two instructions, however, conditional-move from a register needs
18254   // only one instruction.
18255   //
18256   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18257   //  some instruction-combining opportunities. This opt needs to be
18258   //  postponed as late as possible.
18259   //
18260   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18261     // the DCI.xxxx conditions are provided to postpone the optimization as
18262     // late as possible.
18263
18264     ConstantSDNode *CmpAgainst = nullptr;
18265     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18266         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18267         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18268
18269       if (CC == X86::COND_NE &&
18270           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18271         CC = X86::GetOppositeBranchCondition(CC);
18272         std::swap(TrueOp, FalseOp);
18273       }
18274
18275       if (CC == X86::COND_E &&
18276           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18277         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18278                           DAG.getConstant(CC, MVT::i8), Cond };
18279         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18280       }
18281     }
18282   }
18283
18284   return SDValue();
18285 }
18286
18287 /// PerformMulCombine - Optimize a single multiply with constant into two
18288 /// in order to implement it with two cheaper instructions, e.g.
18289 /// LEA + SHL, LEA + LEA.
18290 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18291                                  TargetLowering::DAGCombinerInfo &DCI) {
18292   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18293     return SDValue();
18294
18295   EVT VT = N->getValueType(0);
18296   if (VT != MVT::i64)
18297     return SDValue();
18298
18299   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18300   if (!C)
18301     return SDValue();
18302   uint64_t MulAmt = C->getZExtValue();
18303   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18304     return SDValue();
18305
18306   uint64_t MulAmt1 = 0;
18307   uint64_t MulAmt2 = 0;
18308   if ((MulAmt % 9) == 0) {
18309     MulAmt1 = 9;
18310     MulAmt2 = MulAmt / 9;
18311   } else if ((MulAmt % 5) == 0) {
18312     MulAmt1 = 5;
18313     MulAmt2 = MulAmt / 5;
18314   } else if ((MulAmt % 3) == 0) {
18315     MulAmt1 = 3;
18316     MulAmt2 = MulAmt / 3;
18317   }
18318   if (MulAmt2 &&
18319       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18320     SDLoc DL(N);
18321
18322     if (isPowerOf2_64(MulAmt2) &&
18323         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18324       // If second multiplifer is pow2, issue it first. We want the multiply by
18325       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18326       // is an add.
18327       std::swap(MulAmt1, MulAmt2);
18328
18329     SDValue NewMul;
18330     if (isPowerOf2_64(MulAmt1))
18331       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18332                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18333     else
18334       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18335                            DAG.getConstant(MulAmt1, VT));
18336
18337     if (isPowerOf2_64(MulAmt2))
18338       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18339                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18340     else
18341       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18342                            DAG.getConstant(MulAmt2, VT));
18343
18344     // Do not add new nodes to DAG combiner worklist.
18345     DCI.CombineTo(N, NewMul, false);
18346   }
18347   return SDValue();
18348 }
18349
18350 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18351   SDValue N0 = N->getOperand(0);
18352   SDValue N1 = N->getOperand(1);
18353   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18354   EVT VT = N0.getValueType();
18355
18356   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18357   // since the result of setcc_c is all zero's or all ones.
18358   if (VT.isInteger() && !VT.isVector() &&
18359       N1C && N0.getOpcode() == ISD::AND &&
18360       N0.getOperand(1).getOpcode() == ISD::Constant) {
18361     SDValue N00 = N0.getOperand(0);
18362     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18363         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18364           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18365          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18366       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18367       APInt ShAmt = N1C->getAPIntValue();
18368       Mask = Mask.shl(ShAmt);
18369       if (Mask != 0)
18370         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18371                            N00, DAG.getConstant(Mask, VT));
18372     }
18373   }
18374
18375   // Hardware support for vector shifts is sparse which makes us scalarize the
18376   // vector operations in many cases. Also, on sandybridge ADD is faster than
18377   // shl.
18378   // (shl V, 1) -> add V,V
18379   if (isSplatVector(N1.getNode())) {
18380     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18381     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18382     // We shift all of the values by one. In many cases we do not have
18383     // hardware support for this operation. This is better expressed as an ADD
18384     // of two values.
18385     if (N1C && (1 == N1C->getZExtValue())) {
18386       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18387     }
18388   }
18389
18390   return SDValue();
18391 }
18392
18393 /// \brief Returns a vector of 0s if the node in input is a vector logical
18394 /// shift by a constant amount which is known to be bigger than or equal
18395 /// to the vector element size in bits.
18396 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18397                                       const X86Subtarget *Subtarget) {
18398   EVT VT = N->getValueType(0);
18399
18400   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18401       (!Subtarget->hasInt256() ||
18402        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18403     return SDValue();
18404
18405   SDValue Amt = N->getOperand(1);
18406   SDLoc DL(N);
18407   if (isSplatVector(Amt.getNode())) {
18408     SDValue SclrAmt = Amt->getOperand(0);
18409     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18410       APInt ShiftAmt = C->getAPIntValue();
18411       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18412
18413       // SSE2/AVX2 logical shifts always return a vector of 0s
18414       // if the shift amount is bigger than or equal to
18415       // the element size. The constant shift amount will be
18416       // encoded as a 8-bit immediate.
18417       if (ShiftAmt.trunc(8).uge(MaxAmount))
18418         return getZeroVector(VT, Subtarget, DAG, DL);
18419     }
18420   }
18421
18422   return SDValue();
18423 }
18424
18425 /// PerformShiftCombine - Combine shifts.
18426 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18427                                    TargetLowering::DAGCombinerInfo &DCI,
18428                                    const X86Subtarget *Subtarget) {
18429   if (N->getOpcode() == ISD::SHL) {
18430     SDValue V = PerformSHLCombine(N, DAG);
18431     if (V.getNode()) return V;
18432   }
18433
18434   if (N->getOpcode() != ISD::SRA) {
18435     // Try to fold this logical shift into a zero vector.
18436     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18437     if (V.getNode()) return V;
18438   }
18439
18440   return SDValue();
18441 }
18442
18443 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18444 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18445 // and friends.  Likewise for OR -> CMPNEQSS.
18446 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18447                             TargetLowering::DAGCombinerInfo &DCI,
18448                             const X86Subtarget *Subtarget) {
18449   unsigned opcode;
18450
18451   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18452   // we're requiring SSE2 for both.
18453   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18454     SDValue N0 = N->getOperand(0);
18455     SDValue N1 = N->getOperand(1);
18456     SDValue CMP0 = N0->getOperand(1);
18457     SDValue CMP1 = N1->getOperand(1);
18458     SDLoc DL(N);
18459
18460     // The SETCCs should both refer to the same CMP.
18461     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18462       return SDValue();
18463
18464     SDValue CMP00 = CMP0->getOperand(0);
18465     SDValue CMP01 = CMP0->getOperand(1);
18466     EVT     VT    = CMP00.getValueType();
18467
18468     if (VT == MVT::f32 || VT == MVT::f64) {
18469       bool ExpectingFlags = false;
18470       // Check for any users that want flags:
18471       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18472            !ExpectingFlags && UI != UE; ++UI)
18473         switch (UI->getOpcode()) {
18474         default:
18475         case ISD::BR_CC:
18476         case ISD::BRCOND:
18477         case ISD::SELECT:
18478           ExpectingFlags = true;
18479           break;
18480         case ISD::CopyToReg:
18481         case ISD::SIGN_EXTEND:
18482         case ISD::ZERO_EXTEND:
18483         case ISD::ANY_EXTEND:
18484           break;
18485         }
18486
18487       if (!ExpectingFlags) {
18488         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18489         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18490
18491         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18492           X86::CondCode tmp = cc0;
18493           cc0 = cc1;
18494           cc1 = tmp;
18495         }
18496
18497         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18498             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18499           // FIXME: need symbolic constants for these magic numbers.
18500           // See X86ATTInstPrinter.cpp:printSSECC().
18501           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18502           if (Subtarget->hasAVX512()) {
18503             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18504                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18505             if (N->getValueType(0) != MVT::i1)
18506               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18507                                  FSetCC);
18508             return FSetCC;
18509           }
18510           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18511                                               CMP00.getValueType(), CMP00, CMP01,
18512                                               DAG.getConstant(x86cc, MVT::i8));
18513
18514           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18515           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18516
18517           if (is64BitFP && !Subtarget->is64Bit()) {
18518             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18519             // 64-bit integer, since that's not a legal type. Since
18520             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18521             // bits, but can do this little dance to extract the lowest 32 bits
18522             // and work with those going forward.
18523             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18524                                            OnesOrZeroesF);
18525             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18526                                            Vector64);
18527             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18528                                         Vector32, DAG.getIntPtrConstant(0));
18529             IntVT = MVT::i32;
18530           }
18531
18532           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18533           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18534                                       DAG.getConstant(1, IntVT));
18535           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18536           return OneBitOfTruth;
18537         }
18538       }
18539     }
18540   }
18541   return SDValue();
18542 }
18543
18544 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18545 /// so it can be folded inside ANDNP.
18546 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18547   EVT VT = N->getValueType(0);
18548
18549   // Match direct AllOnes for 128 and 256-bit vectors
18550   if (ISD::isBuildVectorAllOnes(N))
18551     return true;
18552
18553   // Look through a bit convert.
18554   if (N->getOpcode() == ISD::BITCAST)
18555     N = N->getOperand(0).getNode();
18556
18557   // Sometimes the operand may come from a insert_subvector building a 256-bit
18558   // allones vector
18559   if (VT.is256BitVector() &&
18560       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18561     SDValue V1 = N->getOperand(0);
18562     SDValue V2 = N->getOperand(1);
18563
18564     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18565         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18566         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18567         ISD::isBuildVectorAllOnes(V2.getNode()))
18568       return true;
18569   }
18570
18571   return false;
18572 }
18573
18574 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18575 // register. In most cases we actually compare or select YMM-sized registers
18576 // and mixing the two types creates horrible code. This method optimizes
18577 // some of the transition sequences.
18578 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18579                                  TargetLowering::DAGCombinerInfo &DCI,
18580                                  const X86Subtarget *Subtarget) {
18581   EVT VT = N->getValueType(0);
18582   if (!VT.is256BitVector())
18583     return SDValue();
18584
18585   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18586           N->getOpcode() == ISD::ZERO_EXTEND ||
18587           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18588
18589   SDValue Narrow = N->getOperand(0);
18590   EVT NarrowVT = Narrow->getValueType(0);
18591   if (!NarrowVT.is128BitVector())
18592     return SDValue();
18593
18594   if (Narrow->getOpcode() != ISD::XOR &&
18595       Narrow->getOpcode() != ISD::AND &&
18596       Narrow->getOpcode() != ISD::OR)
18597     return SDValue();
18598
18599   SDValue N0  = Narrow->getOperand(0);
18600   SDValue N1  = Narrow->getOperand(1);
18601   SDLoc DL(Narrow);
18602
18603   // The Left side has to be a trunc.
18604   if (N0.getOpcode() != ISD::TRUNCATE)
18605     return SDValue();
18606
18607   // The type of the truncated inputs.
18608   EVT WideVT = N0->getOperand(0)->getValueType(0);
18609   if (WideVT != VT)
18610     return SDValue();
18611
18612   // The right side has to be a 'trunc' or a constant vector.
18613   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18614   bool RHSConst = (isSplatVector(N1.getNode()) &&
18615                    isa<ConstantSDNode>(N1->getOperand(0)));
18616   if (!RHSTrunc && !RHSConst)
18617     return SDValue();
18618
18619   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18620
18621   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18622     return SDValue();
18623
18624   // Set N0 and N1 to hold the inputs to the new wide operation.
18625   N0 = N0->getOperand(0);
18626   if (RHSConst) {
18627     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18628                      N1->getOperand(0));
18629     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18630     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18631   } else if (RHSTrunc) {
18632     N1 = N1->getOperand(0);
18633   }
18634
18635   // Generate the wide operation.
18636   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18637   unsigned Opcode = N->getOpcode();
18638   switch (Opcode) {
18639   case ISD::ANY_EXTEND:
18640     return Op;
18641   case ISD::ZERO_EXTEND: {
18642     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18643     APInt Mask = APInt::getAllOnesValue(InBits);
18644     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18645     return DAG.getNode(ISD::AND, DL, VT,
18646                        Op, DAG.getConstant(Mask, VT));
18647   }
18648   case ISD::SIGN_EXTEND:
18649     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18650                        Op, DAG.getValueType(NarrowVT));
18651   default:
18652     llvm_unreachable("Unexpected opcode");
18653   }
18654 }
18655
18656 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18657                                  TargetLowering::DAGCombinerInfo &DCI,
18658                                  const X86Subtarget *Subtarget) {
18659   EVT VT = N->getValueType(0);
18660   if (DCI.isBeforeLegalizeOps())
18661     return SDValue();
18662
18663   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18664   if (R.getNode())
18665     return R;
18666
18667   // Create BEXTR instructions
18668   // BEXTR is ((X >> imm) & (2**size-1))
18669   if (VT == MVT::i32 || VT == MVT::i64) {
18670     SDValue N0 = N->getOperand(0);
18671     SDValue N1 = N->getOperand(1);
18672     SDLoc DL(N);
18673
18674     // Check for BEXTR.
18675     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18676         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18677       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18678       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18679       if (MaskNode && ShiftNode) {
18680         uint64_t Mask = MaskNode->getZExtValue();
18681         uint64_t Shift = ShiftNode->getZExtValue();
18682         if (isMask_64(Mask)) {
18683           uint64_t MaskSize = CountPopulation_64(Mask);
18684           if (Shift + MaskSize <= VT.getSizeInBits())
18685             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18686                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18687         }
18688       }
18689     } // BEXTR
18690
18691     return SDValue();
18692   }
18693
18694   // Want to form ANDNP nodes:
18695   // 1) In the hopes of then easily combining them with OR and AND nodes
18696   //    to form PBLEND/PSIGN.
18697   // 2) To match ANDN packed intrinsics
18698   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18699     return SDValue();
18700
18701   SDValue N0 = N->getOperand(0);
18702   SDValue N1 = N->getOperand(1);
18703   SDLoc DL(N);
18704
18705   // Check LHS for vnot
18706   if (N0.getOpcode() == ISD::XOR &&
18707       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18708       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18709     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18710
18711   // Check RHS for vnot
18712   if (N1.getOpcode() == ISD::XOR &&
18713       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18714       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18715     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18716
18717   return SDValue();
18718 }
18719
18720 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18721                                 TargetLowering::DAGCombinerInfo &DCI,
18722                                 const X86Subtarget *Subtarget) {
18723   if (DCI.isBeforeLegalizeOps())
18724     return SDValue();
18725
18726   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18727   if (R.getNode())
18728     return R;
18729
18730   SDValue N0 = N->getOperand(0);
18731   SDValue N1 = N->getOperand(1);
18732   EVT VT = N->getValueType(0);
18733
18734   // look for psign/blend
18735   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18736     if (!Subtarget->hasSSSE3() ||
18737         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18738       return SDValue();
18739
18740     // Canonicalize pandn to RHS
18741     if (N0.getOpcode() == X86ISD::ANDNP)
18742       std::swap(N0, N1);
18743     // or (and (m, y), (pandn m, x))
18744     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18745       SDValue Mask = N1.getOperand(0);
18746       SDValue X    = N1.getOperand(1);
18747       SDValue Y;
18748       if (N0.getOperand(0) == Mask)
18749         Y = N0.getOperand(1);
18750       if (N0.getOperand(1) == Mask)
18751         Y = N0.getOperand(0);
18752
18753       // Check to see if the mask appeared in both the AND and ANDNP and
18754       if (!Y.getNode())
18755         return SDValue();
18756
18757       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18758       // Look through mask bitcast.
18759       if (Mask.getOpcode() == ISD::BITCAST)
18760         Mask = Mask.getOperand(0);
18761       if (X.getOpcode() == ISD::BITCAST)
18762         X = X.getOperand(0);
18763       if (Y.getOpcode() == ISD::BITCAST)
18764         Y = Y.getOperand(0);
18765
18766       EVT MaskVT = Mask.getValueType();
18767
18768       // Validate that the Mask operand is a vector sra node.
18769       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18770       // there is no psrai.b
18771       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18772       unsigned SraAmt = ~0;
18773       if (Mask.getOpcode() == ISD::SRA) {
18774         SDValue Amt = Mask.getOperand(1);
18775         if (isSplatVector(Amt.getNode())) {
18776           SDValue SclrAmt = Amt->getOperand(0);
18777           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18778             SraAmt = C->getZExtValue();
18779         }
18780       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18781         SDValue SraC = Mask.getOperand(1);
18782         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18783       }
18784       if ((SraAmt + 1) != EltBits)
18785         return SDValue();
18786
18787       SDLoc DL(N);
18788
18789       // Now we know we at least have a plendvb with the mask val.  See if
18790       // we can form a psignb/w/d.
18791       // psign = x.type == y.type == mask.type && y = sub(0, x);
18792       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18793           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18794           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18795         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18796                "Unsupported VT for PSIGN");
18797         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18798         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18799       }
18800       // PBLENDVB only available on SSE 4.1
18801       if (!Subtarget->hasSSE41())
18802         return SDValue();
18803
18804       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18805
18806       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18807       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18808       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18809       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18810       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18811     }
18812   }
18813
18814   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18815     return SDValue();
18816
18817   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18818   MachineFunction &MF = DAG.getMachineFunction();
18819   bool OptForSize = MF.getFunction()->getAttributes().
18820     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18821
18822   // SHLD/SHRD instructions have lower register pressure, but on some
18823   // platforms they have higher latency than the equivalent
18824   // series of shifts/or that would otherwise be generated.
18825   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18826   // have higher latencies and we are not optimizing for size.
18827   if (!OptForSize && Subtarget->isSHLDSlow())
18828     return SDValue();
18829
18830   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18831     std::swap(N0, N1);
18832   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18833     return SDValue();
18834   if (!N0.hasOneUse() || !N1.hasOneUse())
18835     return SDValue();
18836
18837   SDValue ShAmt0 = N0.getOperand(1);
18838   if (ShAmt0.getValueType() != MVT::i8)
18839     return SDValue();
18840   SDValue ShAmt1 = N1.getOperand(1);
18841   if (ShAmt1.getValueType() != MVT::i8)
18842     return SDValue();
18843   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18844     ShAmt0 = ShAmt0.getOperand(0);
18845   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18846     ShAmt1 = ShAmt1.getOperand(0);
18847
18848   SDLoc DL(N);
18849   unsigned Opc = X86ISD::SHLD;
18850   SDValue Op0 = N0.getOperand(0);
18851   SDValue Op1 = N1.getOperand(0);
18852   if (ShAmt0.getOpcode() == ISD::SUB) {
18853     Opc = X86ISD::SHRD;
18854     std::swap(Op0, Op1);
18855     std::swap(ShAmt0, ShAmt1);
18856   }
18857
18858   unsigned Bits = VT.getSizeInBits();
18859   if (ShAmt1.getOpcode() == ISD::SUB) {
18860     SDValue Sum = ShAmt1.getOperand(0);
18861     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18862       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18863       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18864         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18865       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18866         return DAG.getNode(Opc, DL, VT,
18867                            Op0, Op1,
18868                            DAG.getNode(ISD::TRUNCATE, DL,
18869                                        MVT::i8, ShAmt0));
18870     }
18871   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18872     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18873     if (ShAmt0C &&
18874         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18875       return DAG.getNode(Opc, DL, VT,
18876                          N0.getOperand(0), N1.getOperand(0),
18877                          DAG.getNode(ISD::TRUNCATE, DL,
18878                                        MVT::i8, ShAmt0));
18879   }
18880
18881   return SDValue();
18882 }
18883
18884 // Generate NEG and CMOV for integer abs.
18885 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18886   EVT VT = N->getValueType(0);
18887
18888   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18889   // 8-bit integer abs to NEG and CMOV.
18890   if (VT.isInteger() && VT.getSizeInBits() == 8)
18891     return SDValue();
18892
18893   SDValue N0 = N->getOperand(0);
18894   SDValue N1 = N->getOperand(1);
18895   SDLoc DL(N);
18896
18897   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18898   // and change it to SUB and CMOV.
18899   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18900       N0.getOpcode() == ISD::ADD &&
18901       N0.getOperand(1) == N1 &&
18902       N1.getOpcode() == ISD::SRA &&
18903       N1.getOperand(0) == N0.getOperand(0))
18904     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18905       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18906         // Generate SUB & CMOV.
18907         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18908                                   DAG.getConstant(0, VT), N0.getOperand(0));
18909
18910         SDValue Ops[] = { N0.getOperand(0), Neg,
18911                           DAG.getConstant(X86::COND_GE, MVT::i8),
18912                           SDValue(Neg.getNode(), 1) };
18913         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18914       }
18915   return SDValue();
18916 }
18917
18918 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18919 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18920                                  TargetLowering::DAGCombinerInfo &DCI,
18921                                  const X86Subtarget *Subtarget) {
18922   if (DCI.isBeforeLegalizeOps())
18923     return SDValue();
18924
18925   if (Subtarget->hasCMov()) {
18926     SDValue RV = performIntegerAbsCombine(N, DAG);
18927     if (RV.getNode())
18928       return RV;
18929   }
18930
18931   return SDValue();
18932 }
18933
18934 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18935 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18936                                   TargetLowering::DAGCombinerInfo &DCI,
18937                                   const X86Subtarget *Subtarget) {
18938   LoadSDNode *Ld = cast<LoadSDNode>(N);
18939   EVT RegVT = Ld->getValueType(0);
18940   EVT MemVT = Ld->getMemoryVT();
18941   SDLoc dl(Ld);
18942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18943   unsigned RegSz = RegVT.getSizeInBits();
18944
18945   // On Sandybridge unaligned 256bit loads are inefficient.
18946   ISD::LoadExtType Ext = Ld->getExtensionType();
18947   unsigned Alignment = Ld->getAlignment();
18948   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18949   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18950       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18951     unsigned NumElems = RegVT.getVectorNumElements();
18952     if (NumElems < 2)
18953       return SDValue();
18954
18955     SDValue Ptr = Ld->getBasePtr();
18956     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18957
18958     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18959                                   NumElems/2);
18960     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18961                                 Ld->getPointerInfo(), Ld->isVolatile(),
18962                                 Ld->isNonTemporal(), Ld->isInvariant(),
18963                                 Alignment);
18964     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18965     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18966                                 Ld->getPointerInfo(), Ld->isVolatile(),
18967                                 Ld->isNonTemporal(), Ld->isInvariant(),
18968                                 std::min(16U, Alignment));
18969     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18970                              Load1.getValue(1),
18971                              Load2.getValue(1));
18972
18973     SDValue NewVec = DAG.getUNDEF(RegVT);
18974     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18975     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18976     return DCI.CombineTo(N, NewVec, TF, true);
18977   }
18978
18979   // If this is a vector EXT Load then attempt to optimize it using a
18980   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18981   // expansion is still better than scalar code.
18982   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18983   // emit a shuffle and a arithmetic shift.
18984   // TODO: It is possible to support ZExt by zeroing the undef values
18985   // during the shuffle phase or after the shuffle.
18986   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18987       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18988     assert(MemVT != RegVT && "Cannot extend to the same type");
18989     assert(MemVT.isVector() && "Must load a vector from memory");
18990
18991     unsigned NumElems = RegVT.getVectorNumElements();
18992     unsigned MemSz = MemVT.getSizeInBits();
18993     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18994
18995     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18996       return SDValue();
18997
18998     // All sizes must be a power of two.
18999     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19000       return SDValue();
19001
19002     // Attempt to load the original value using scalar loads.
19003     // Find the largest scalar type that divides the total loaded size.
19004     MVT SclrLoadTy = MVT::i8;
19005     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19006          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19007       MVT Tp = (MVT::SimpleValueType)tp;
19008       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19009         SclrLoadTy = Tp;
19010       }
19011     }
19012
19013     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19014     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19015         (64 <= MemSz))
19016       SclrLoadTy = MVT::f64;
19017
19018     // Calculate the number of scalar loads that we need to perform
19019     // in order to load our vector from memory.
19020     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19021     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19022       return SDValue();
19023
19024     unsigned loadRegZize = RegSz;
19025     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19026       loadRegZize /= 2;
19027
19028     // Represent our vector as a sequence of elements which are the
19029     // largest scalar that we can load.
19030     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19031       loadRegZize/SclrLoadTy.getSizeInBits());
19032
19033     // Represent the data using the same element type that is stored in
19034     // memory. In practice, we ''widen'' MemVT.
19035     EVT WideVecVT =
19036           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19037                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19038
19039     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19040       "Invalid vector type");
19041
19042     // We can't shuffle using an illegal type.
19043     if (!TLI.isTypeLegal(WideVecVT))
19044       return SDValue();
19045
19046     SmallVector<SDValue, 8> Chains;
19047     SDValue Ptr = Ld->getBasePtr();
19048     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19049                                         TLI.getPointerTy());
19050     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19051
19052     for (unsigned i = 0; i < NumLoads; ++i) {
19053       // Perform a single load.
19054       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19055                                        Ptr, Ld->getPointerInfo(),
19056                                        Ld->isVolatile(), Ld->isNonTemporal(),
19057                                        Ld->isInvariant(), Ld->getAlignment());
19058       Chains.push_back(ScalarLoad.getValue(1));
19059       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19060       // another round of DAGCombining.
19061       if (i == 0)
19062         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19063       else
19064         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19065                           ScalarLoad, DAG.getIntPtrConstant(i));
19066
19067       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19068     }
19069
19070     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19071
19072     // Bitcast the loaded value to a vector of the original element type, in
19073     // the size of the target vector type.
19074     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19075     unsigned SizeRatio = RegSz/MemSz;
19076
19077     if (Ext == ISD::SEXTLOAD) {
19078       // If we have SSE4.1 we can directly emit a VSEXT node.
19079       if (Subtarget->hasSSE41()) {
19080         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19081         return DCI.CombineTo(N, Sext, TF, true);
19082       }
19083
19084       // Otherwise we'll shuffle the small elements in the high bits of the
19085       // larger type and perform an arithmetic shift. If the shift is not legal
19086       // it's better to scalarize.
19087       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19088         return SDValue();
19089
19090       // Redistribute the loaded elements into the different locations.
19091       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19092       for (unsigned i = 0; i != NumElems; ++i)
19093         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19094
19095       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19096                                            DAG.getUNDEF(WideVecVT),
19097                                            &ShuffleVec[0]);
19098
19099       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19100
19101       // Build the arithmetic shift.
19102       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19103                      MemVT.getVectorElementType().getSizeInBits();
19104       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19105                           DAG.getConstant(Amt, RegVT));
19106
19107       return DCI.CombineTo(N, Shuff, TF, true);
19108     }
19109
19110     // Redistribute the loaded elements into the different locations.
19111     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19112     for (unsigned i = 0; i != NumElems; ++i)
19113       ShuffleVec[i*SizeRatio] = i;
19114
19115     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19116                                          DAG.getUNDEF(WideVecVT),
19117                                          &ShuffleVec[0]);
19118
19119     // Bitcast to the requested type.
19120     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19121     // Replace the original load with the new sequence
19122     // and return the new chain.
19123     return DCI.CombineTo(N, Shuff, TF, true);
19124   }
19125
19126   return SDValue();
19127 }
19128
19129 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19130 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19131                                    const X86Subtarget *Subtarget) {
19132   StoreSDNode *St = cast<StoreSDNode>(N);
19133   EVT VT = St->getValue().getValueType();
19134   EVT StVT = St->getMemoryVT();
19135   SDLoc dl(St);
19136   SDValue StoredVal = St->getOperand(1);
19137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19138
19139   // If we are saving a concatenation of two XMM registers, perform two stores.
19140   // On Sandy Bridge, 256-bit memory operations are executed by two
19141   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19142   // memory  operation.
19143   unsigned Alignment = St->getAlignment();
19144   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19145   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19146       StVT == VT && !IsAligned) {
19147     unsigned NumElems = VT.getVectorNumElements();
19148     if (NumElems < 2)
19149       return SDValue();
19150
19151     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19152     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19153
19154     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19155     SDValue Ptr0 = St->getBasePtr();
19156     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19157
19158     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19159                                 St->getPointerInfo(), St->isVolatile(),
19160                                 St->isNonTemporal(), Alignment);
19161     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19162                                 St->getPointerInfo(), St->isVolatile(),
19163                                 St->isNonTemporal(),
19164                                 std::min(16U, Alignment));
19165     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19166   }
19167
19168   // Optimize trunc store (of multiple scalars) to shuffle and store.
19169   // First, pack all of the elements in one place. Next, store to memory
19170   // in fewer chunks.
19171   if (St->isTruncatingStore() && VT.isVector()) {
19172     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19173     unsigned NumElems = VT.getVectorNumElements();
19174     assert(StVT != VT && "Cannot truncate to the same type");
19175     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19176     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19177
19178     // From, To sizes and ElemCount must be pow of two
19179     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19180     // We are going to use the original vector elt for storing.
19181     // Accumulated smaller vector elements must be a multiple of the store size.
19182     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19183
19184     unsigned SizeRatio  = FromSz / ToSz;
19185
19186     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19187
19188     // Create a type on which we perform the shuffle
19189     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19190             StVT.getScalarType(), NumElems*SizeRatio);
19191
19192     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19193
19194     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19195     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19196     for (unsigned i = 0; i != NumElems; ++i)
19197       ShuffleVec[i] = i * SizeRatio;
19198
19199     // Can't shuffle using an illegal type.
19200     if (!TLI.isTypeLegal(WideVecVT))
19201       return SDValue();
19202
19203     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19204                                          DAG.getUNDEF(WideVecVT),
19205                                          &ShuffleVec[0]);
19206     // At this point all of the data is stored at the bottom of the
19207     // register. We now need to save it to mem.
19208
19209     // Find the largest store unit
19210     MVT StoreType = MVT::i8;
19211     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19212          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19213       MVT Tp = (MVT::SimpleValueType)tp;
19214       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19215         StoreType = Tp;
19216     }
19217
19218     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19219     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19220         (64 <= NumElems * ToSz))
19221       StoreType = MVT::f64;
19222
19223     // Bitcast the original vector into a vector of store-size units
19224     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19225             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19226     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19227     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19228     SmallVector<SDValue, 8> Chains;
19229     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19230                                         TLI.getPointerTy());
19231     SDValue Ptr = St->getBasePtr();
19232
19233     // Perform one or more big stores into memory.
19234     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19235       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19236                                    StoreType, ShuffWide,
19237                                    DAG.getIntPtrConstant(i));
19238       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19239                                 St->getPointerInfo(), St->isVolatile(),
19240                                 St->isNonTemporal(), St->getAlignment());
19241       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19242       Chains.push_back(Ch);
19243     }
19244
19245     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19246   }
19247
19248   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19249   // the FP state in cases where an emms may be missing.
19250   // A preferable solution to the general problem is to figure out the right
19251   // places to insert EMMS.  This qualifies as a quick hack.
19252
19253   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19254   if (VT.getSizeInBits() != 64)
19255     return SDValue();
19256
19257   const Function *F = DAG.getMachineFunction().getFunction();
19258   bool NoImplicitFloatOps = F->getAttributes().
19259     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19260   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19261                      && Subtarget->hasSSE2();
19262   if ((VT.isVector() ||
19263        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19264       isa<LoadSDNode>(St->getValue()) &&
19265       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19266       St->getChain().hasOneUse() && !St->isVolatile()) {
19267     SDNode* LdVal = St->getValue().getNode();
19268     LoadSDNode *Ld = nullptr;
19269     int TokenFactorIndex = -1;
19270     SmallVector<SDValue, 8> Ops;
19271     SDNode* ChainVal = St->getChain().getNode();
19272     // Must be a store of a load.  We currently handle two cases:  the load
19273     // is a direct child, and it's under an intervening TokenFactor.  It is
19274     // possible to dig deeper under nested TokenFactors.
19275     if (ChainVal == LdVal)
19276       Ld = cast<LoadSDNode>(St->getChain());
19277     else if (St->getValue().hasOneUse() &&
19278              ChainVal->getOpcode() == ISD::TokenFactor) {
19279       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19280         if (ChainVal->getOperand(i).getNode() == LdVal) {
19281           TokenFactorIndex = i;
19282           Ld = cast<LoadSDNode>(St->getValue());
19283         } else
19284           Ops.push_back(ChainVal->getOperand(i));
19285       }
19286     }
19287
19288     if (!Ld || !ISD::isNormalLoad(Ld))
19289       return SDValue();
19290
19291     // If this is not the MMX case, i.e. we are just turning i64 load/store
19292     // into f64 load/store, avoid the transformation if there are multiple
19293     // uses of the loaded value.
19294     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19295       return SDValue();
19296
19297     SDLoc LdDL(Ld);
19298     SDLoc StDL(N);
19299     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19300     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19301     // pair instead.
19302     if (Subtarget->is64Bit() || F64IsLegal) {
19303       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19304       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19305                                   Ld->getPointerInfo(), Ld->isVolatile(),
19306                                   Ld->isNonTemporal(), Ld->isInvariant(),
19307                                   Ld->getAlignment());
19308       SDValue NewChain = NewLd.getValue(1);
19309       if (TokenFactorIndex != -1) {
19310         Ops.push_back(NewChain);
19311         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19312       }
19313       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19314                           St->getPointerInfo(),
19315                           St->isVolatile(), St->isNonTemporal(),
19316                           St->getAlignment());
19317     }
19318
19319     // Otherwise, lower to two pairs of 32-bit loads / stores.
19320     SDValue LoAddr = Ld->getBasePtr();
19321     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19322                                  DAG.getConstant(4, MVT::i32));
19323
19324     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19325                                Ld->getPointerInfo(),
19326                                Ld->isVolatile(), Ld->isNonTemporal(),
19327                                Ld->isInvariant(), Ld->getAlignment());
19328     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19329                                Ld->getPointerInfo().getWithOffset(4),
19330                                Ld->isVolatile(), Ld->isNonTemporal(),
19331                                Ld->isInvariant(),
19332                                MinAlign(Ld->getAlignment(), 4));
19333
19334     SDValue NewChain = LoLd.getValue(1);
19335     if (TokenFactorIndex != -1) {
19336       Ops.push_back(LoLd);
19337       Ops.push_back(HiLd);
19338       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19339     }
19340
19341     LoAddr = St->getBasePtr();
19342     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19343                          DAG.getConstant(4, MVT::i32));
19344
19345     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19346                                 St->getPointerInfo(),
19347                                 St->isVolatile(), St->isNonTemporal(),
19348                                 St->getAlignment());
19349     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19350                                 St->getPointerInfo().getWithOffset(4),
19351                                 St->isVolatile(),
19352                                 St->isNonTemporal(),
19353                                 MinAlign(St->getAlignment(), 4));
19354     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19355   }
19356   return SDValue();
19357 }
19358
19359 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19360 /// and return the operands for the horizontal operation in LHS and RHS.  A
19361 /// horizontal operation performs the binary operation on successive elements
19362 /// of its first operand, then on successive elements of its second operand,
19363 /// returning the resulting values in a vector.  For example, if
19364 ///   A = < float a0, float a1, float a2, float a3 >
19365 /// and
19366 ///   B = < float b0, float b1, float b2, float b3 >
19367 /// then the result of doing a horizontal operation on A and B is
19368 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19369 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19370 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19371 /// set to A, RHS to B, and the routine returns 'true'.
19372 /// Note that the binary operation should have the property that if one of the
19373 /// operands is UNDEF then the result is UNDEF.
19374 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19375   // Look for the following pattern: if
19376   //   A = < float a0, float a1, float a2, float a3 >
19377   //   B = < float b0, float b1, float b2, float b3 >
19378   // and
19379   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19380   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19381   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19382   // which is A horizontal-op B.
19383
19384   // At least one of the operands should be a vector shuffle.
19385   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19386       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19387     return false;
19388
19389   MVT VT = LHS.getSimpleValueType();
19390
19391   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19392          "Unsupported vector type for horizontal add/sub");
19393
19394   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19395   // operate independently on 128-bit lanes.
19396   unsigned NumElts = VT.getVectorNumElements();
19397   unsigned NumLanes = VT.getSizeInBits()/128;
19398   unsigned NumLaneElts = NumElts / NumLanes;
19399   assert((NumLaneElts % 2 == 0) &&
19400          "Vector type should have an even number of elements in each lane");
19401   unsigned HalfLaneElts = NumLaneElts/2;
19402
19403   // View LHS in the form
19404   //   LHS = VECTOR_SHUFFLE A, B, LMask
19405   // If LHS is not a shuffle then pretend it is the shuffle
19406   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19407   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19408   // type VT.
19409   SDValue A, B;
19410   SmallVector<int, 16> LMask(NumElts);
19411   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19412     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19413       A = LHS.getOperand(0);
19414     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19415       B = LHS.getOperand(1);
19416     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19417     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19418   } else {
19419     if (LHS.getOpcode() != ISD::UNDEF)
19420       A = LHS;
19421     for (unsigned i = 0; i != NumElts; ++i)
19422       LMask[i] = i;
19423   }
19424
19425   // Likewise, view RHS in the form
19426   //   RHS = VECTOR_SHUFFLE C, D, RMask
19427   SDValue C, D;
19428   SmallVector<int, 16> RMask(NumElts);
19429   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19430     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19431       C = RHS.getOperand(0);
19432     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19433       D = RHS.getOperand(1);
19434     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19435     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19436   } else {
19437     if (RHS.getOpcode() != ISD::UNDEF)
19438       C = RHS;
19439     for (unsigned i = 0; i != NumElts; ++i)
19440       RMask[i] = i;
19441   }
19442
19443   // Check that the shuffles are both shuffling the same vectors.
19444   if (!(A == C && B == D) && !(A == D && B == C))
19445     return false;
19446
19447   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19448   if (!A.getNode() && !B.getNode())
19449     return false;
19450
19451   // If A and B occur in reverse order in RHS, then "swap" them (which means
19452   // rewriting the mask).
19453   if (A != C)
19454     CommuteVectorShuffleMask(RMask, NumElts);
19455
19456   // At this point LHS and RHS are equivalent to
19457   //   LHS = VECTOR_SHUFFLE A, B, LMask
19458   //   RHS = VECTOR_SHUFFLE A, B, RMask
19459   // Check that the masks correspond to performing a horizontal operation.
19460   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19461     for (unsigned i = 0; i != NumLaneElts; ++i) {
19462       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19463
19464       // Ignore any UNDEF components.
19465       if (LIdx < 0 || RIdx < 0 ||
19466           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19467           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19468         continue;
19469
19470       // Check that successive elements are being operated on.  If not, this is
19471       // not a horizontal operation.
19472       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19473       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19474       if (!(LIdx == Index && RIdx == Index + 1) &&
19475           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19476         return false;
19477     }
19478   }
19479
19480   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19481   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19482   return true;
19483 }
19484
19485 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19486 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19487                                   const X86Subtarget *Subtarget) {
19488   EVT VT = N->getValueType(0);
19489   SDValue LHS = N->getOperand(0);
19490   SDValue RHS = N->getOperand(1);
19491
19492   // Try to synthesize horizontal adds from adds of shuffles.
19493   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19494        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19495       isHorizontalBinOp(LHS, RHS, true))
19496     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19497   return SDValue();
19498 }
19499
19500 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19501 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19502                                   const X86Subtarget *Subtarget) {
19503   EVT VT = N->getValueType(0);
19504   SDValue LHS = N->getOperand(0);
19505   SDValue RHS = N->getOperand(1);
19506
19507   // Try to synthesize horizontal subs from subs of shuffles.
19508   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19509        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19510       isHorizontalBinOp(LHS, RHS, false))
19511     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19512   return SDValue();
19513 }
19514
19515 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19516 /// X86ISD::FXOR nodes.
19517 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19518   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19519   // F[X]OR(0.0, x) -> x
19520   // F[X]OR(x, 0.0) -> x
19521   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19522     if (C->getValueAPF().isPosZero())
19523       return N->getOperand(1);
19524   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19525     if (C->getValueAPF().isPosZero())
19526       return N->getOperand(0);
19527   return SDValue();
19528 }
19529
19530 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19531 /// X86ISD::FMAX nodes.
19532 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19533   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19534
19535   // Only perform optimizations if UnsafeMath is used.
19536   if (!DAG.getTarget().Options.UnsafeFPMath)
19537     return SDValue();
19538
19539   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19540   // into FMINC and FMAXC, which are Commutative operations.
19541   unsigned NewOp = 0;
19542   switch (N->getOpcode()) {
19543     default: llvm_unreachable("unknown opcode");
19544     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19545     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19546   }
19547
19548   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19549                      N->getOperand(0), N->getOperand(1));
19550 }
19551
19552 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19553 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19554   // FAND(0.0, x) -> 0.0
19555   // FAND(x, 0.0) -> 0.0
19556   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19557     if (C->getValueAPF().isPosZero())
19558       return N->getOperand(0);
19559   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19560     if (C->getValueAPF().isPosZero())
19561       return N->getOperand(1);
19562   return SDValue();
19563 }
19564
19565 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19566 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19567   // FANDN(x, 0.0) -> 0.0
19568   // FANDN(0.0, x) -> x
19569   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19570     if (C->getValueAPF().isPosZero())
19571       return N->getOperand(1);
19572   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19573     if (C->getValueAPF().isPosZero())
19574       return N->getOperand(1);
19575   return SDValue();
19576 }
19577
19578 static SDValue PerformBTCombine(SDNode *N,
19579                                 SelectionDAG &DAG,
19580                                 TargetLowering::DAGCombinerInfo &DCI) {
19581   // BT ignores high bits in the bit index operand.
19582   SDValue Op1 = N->getOperand(1);
19583   if (Op1.hasOneUse()) {
19584     unsigned BitWidth = Op1.getValueSizeInBits();
19585     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19586     APInt KnownZero, KnownOne;
19587     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19588                                           !DCI.isBeforeLegalizeOps());
19589     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19590     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19591         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19592       DCI.CommitTargetLoweringOpt(TLO);
19593   }
19594   return SDValue();
19595 }
19596
19597 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19598   SDValue Op = N->getOperand(0);
19599   if (Op.getOpcode() == ISD::BITCAST)
19600     Op = Op.getOperand(0);
19601   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19602   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19603       VT.getVectorElementType().getSizeInBits() ==
19604       OpVT.getVectorElementType().getSizeInBits()) {
19605     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19606   }
19607   return SDValue();
19608 }
19609
19610 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19611                                                const X86Subtarget *Subtarget) {
19612   EVT VT = N->getValueType(0);
19613   if (!VT.isVector())
19614     return SDValue();
19615
19616   SDValue N0 = N->getOperand(0);
19617   SDValue N1 = N->getOperand(1);
19618   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19619   SDLoc dl(N);
19620
19621   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19622   // both SSE and AVX2 since there is no sign-extended shift right
19623   // operation on a vector with 64-bit elements.
19624   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19625   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19626   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19627       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19628     SDValue N00 = N0.getOperand(0);
19629
19630     // EXTLOAD has a better solution on AVX2,
19631     // it may be replaced with X86ISD::VSEXT node.
19632     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19633       if (!ISD::isNormalLoad(N00.getNode()))
19634         return SDValue();
19635
19636     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19637         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19638                                   N00, N1);
19639       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19640     }
19641   }
19642   return SDValue();
19643 }
19644
19645 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19646                                   TargetLowering::DAGCombinerInfo &DCI,
19647                                   const X86Subtarget *Subtarget) {
19648   if (!DCI.isBeforeLegalizeOps())
19649     return SDValue();
19650
19651   if (!Subtarget->hasFp256())
19652     return SDValue();
19653
19654   EVT VT = N->getValueType(0);
19655   if (VT.isVector() && VT.getSizeInBits() == 256) {
19656     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19657     if (R.getNode())
19658       return R;
19659   }
19660
19661   return SDValue();
19662 }
19663
19664 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19665                                  const X86Subtarget* Subtarget) {
19666   SDLoc dl(N);
19667   EVT VT = N->getValueType(0);
19668
19669   // Let legalize expand this if it isn't a legal type yet.
19670   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19671     return SDValue();
19672
19673   EVT ScalarVT = VT.getScalarType();
19674   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19675       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19676     return SDValue();
19677
19678   SDValue A = N->getOperand(0);
19679   SDValue B = N->getOperand(1);
19680   SDValue C = N->getOperand(2);
19681
19682   bool NegA = (A.getOpcode() == ISD::FNEG);
19683   bool NegB = (B.getOpcode() == ISD::FNEG);
19684   bool NegC = (C.getOpcode() == ISD::FNEG);
19685
19686   // Negative multiplication when NegA xor NegB
19687   bool NegMul = (NegA != NegB);
19688   if (NegA)
19689     A = A.getOperand(0);
19690   if (NegB)
19691     B = B.getOperand(0);
19692   if (NegC)
19693     C = C.getOperand(0);
19694
19695   unsigned Opcode;
19696   if (!NegMul)
19697     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19698   else
19699     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19700
19701   return DAG.getNode(Opcode, dl, VT, A, B, C);
19702 }
19703
19704 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19705                                   TargetLowering::DAGCombinerInfo &DCI,
19706                                   const X86Subtarget *Subtarget) {
19707   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19708   //           (and (i32 x86isd::setcc_carry), 1)
19709   // This eliminates the zext. This transformation is necessary because
19710   // ISD::SETCC is always legalized to i8.
19711   SDLoc dl(N);
19712   SDValue N0 = N->getOperand(0);
19713   EVT VT = N->getValueType(0);
19714
19715   if (N0.getOpcode() == ISD::AND &&
19716       N0.hasOneUse() &&
19717       N0.getOperand(0).hasOneUse()) {
19718     SDValue N00 = N0.getOperand(0);
19719     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19720       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19721       if (!C || C->getZExtValue() != 1)
19722         return SDValue();
19723       return DAG.getNode(ISD::AND, dl, VT,
19724                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19725                                      N00.getOperand(0), N00.getOperand(1)),
19726                          DAG.getConstant(1, VT));
19727     }
19728   }
19729
19730   if (N0.getOpcode() == ISD::TRUNCATE &&
19731       N0.hasOneUse() &&
19732       N0.getOperand(0).hasOneUse()) {
19733     SDValue N00 = N0.getOperand(0);
19734     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19735       return DAG.getNode(ISD::AND, dl, VT,
19736                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19737                                      N00.getOperand(0), N00.getOperand(1)),
19738                          DAG.getConstant(1, VT));
19739     }
19740   }
19741   if (VT.is256BitVector()) {
19742     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19743     if (R.getNode())
19744       return R;
19745   }
19746
19747   return SDValue();
19748 }
19749
19750 // Optimize x == -y --> x+y == 0
19751 //          x != -y --> x+y != 0
19752 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19753                                       const X86Subtarget* Subtarget) {
19754   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19755   SDValue LHS = N->getOperand(0);
19756   SDValue RHS = N->getOperand(1);
19757   EVT VT = N->getValueType(0);
19758   SDLoc DL(N);
19759
19760   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19761     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19762       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19763         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19764                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19765         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19766                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19767       }
19768   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19769     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19770       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19771         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19772                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19773         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19774                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19775       }
19776
19777   if (VT.getScalarType() == MVT::i1) {
19778     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19779       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19780     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19781     if (!IsSEXT0 && !IsVZero0)
19782       return SDValue();
19783     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19784       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19785     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19786
19787     if (!IsSEXT1 && !IsVZero1)
19788       return SDValue();
19789
19790     if (IsSEXT0 && IsVZero1) {
19791       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19792       if (CC == ISD::SETEQ)
19793         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19794       return LHS.getOperand(0);
19795     }
19796     if (IsSEXT1 && IsVZero0) {
19797       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19798       if (CC == ISD::SETEQ)
19799         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19800       return RHS.getOperand(0);
19801     }
19802   }
19803
19804   return SDValue();
19805 }
19806
19807 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19808 // as "sbb reg,reg", since it can be extended without zext and produces
19809 // an all-ones bit which is more useful than 0/1 in some cases.
19810 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19811                                MVT VT) {
19812   if (VT == MVT::i8)
19813     return DAG.getNode(ISD::AND, DL, VT,
19814                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19815                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19816                        DAG.getConstant(1, VT));
19817   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19818   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19819                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19820                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19821 }
19822
19823 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19824 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19825                                    TargetLowering::DAGCombinerInfo &DCI,
19826                                    const X86Subtarget *Subtarget) {
19827   SDLoc DL(N);
19828   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19829   SDValue EFLAGS = N->getOperand(1);
19830
19831   if (CC == X86::COND_A) {
19832     // Try to convert COND_A into COND_B in an attempt to facilitate
19833     // materializing "setb reg".
19834     //
19835     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19836     // cannot take an immediate as its first operand.
19837     //
19838     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19839         EFLAGS.getValueType().isInteger() &&
19840         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19841       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19842                                    EFLAGS.getNode()->getVTList(),
19843                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19844       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19845       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19846     }
19847   }
19848
19849   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19850   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19851   // cases.
19852   if (CC == X86::COND_B)
19853     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19854
19855   SDValue Flags;
19856
19857   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19858   if (Flags.getNode()) {
19859     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19860     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19861   }
19862
19863   return SDValue();
19864 }
19865
19866 // Optimize branch condition evaluation.
19867 //
19868 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19869                                     TargetLowering::DAGCombinerInfo &DCI,
19870                                     const X86Subtarget *Subtarget) {
19871   SDLoc DL(N);
19872   SDValue Chain = N->getOperand(0);
19873   SDValue Dest = N->getOperand(1);
19874   SDValue EFLAGS = N->getOperand(3);
19875   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19876
19877   SDValue Flags;
19878
19879   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19880   if (Flags.getNode()) {
19881     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19882     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19883                        Flags);
19884   }
19885
19886   return SDValue();
19887 }
19888
19889 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19890                                         const X86TargetLowering *XTLI) {
19891   SDValue Op0 = N->getOperand(0);
19892   EVT InVT = Op0->getValueType(0);
19893
19894   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19895   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19896     SDLoc dl(N);
19897     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19898     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19899     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19900   }
19901
19902   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19903   // a 32-bit target where SSE doesn't support i64->FP operations.
19904   if (Op0.getOpcode() == ISD::LOAD) {
19905     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19906     EVT VT = Ld->getValueType(0);
19907     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19908         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19909         !XTLI->getSubtarget()->is64Bit() &&
19910         VT == MVT::i64) {
19911       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19912                                           Ld->getChain(), Op0, DAG);
19913       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19914       return FILDChain;
19915     }
19916   }
19917   return SDValue();
19918 }
19919
19920 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19921 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19922                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19923   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19924   // the result is either zero or one (depending on the input carry bit).
19925   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19926   if (X86::isZeroNode(N->getOperand(0)) &&
19927       X86::isZeroNode(N->getOperand(1)) &&
19928       // We don't have a good way to replace an EFLAGS use, so only do this when
19929       // dead right now.
19930       SDValue(N, 1).use_empty()) {
19931     SDLoc DL(N);
19932     EVT VT = N->getValueType(0);
19933     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19934     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19935                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19936                                            DAG.getConstant(X86::COND_B,MVT::i8),
19937                                            N->getOperand(2)),
19938                                DAG.getConstant(1, VT));
19939     return DCI.CombineTo(N, Res1, CarryOut);
19940   }
19941
19942   return SDValue();
19943 }
19944
19945 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19946 //      (add Y, (setne X, 0)) -> sbb -1, Y
19947 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19948 //      (sub (setne X, 0), Y) -> adc -1, Y
19949 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19950   SDLoc DL(N);
19951
19952   // Look through ZExts.
19953   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19954   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19955     return SDValue();
19956
19957   SDValue SetCC = Ext.getOperand(0);
19958   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19959     return SDValue();
19960
19961   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19962   if (CC != X86::COND_E && CC != X86::COND_NE)
19963     return SDValue();
19964
19965   SDValue Cmp = SetCC.getOperand(1);
19966   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19967       !X86::isZeroNode(Cmp.getOperand(1)) ||
19968       !Cmp.getOperand(0).getValueType().isInteger())
19969     return SDValue();
19970
19971   SDValue CmpOp0 = Cmp.getOperand(0);
19972   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19973                                DAG.getConstant(1, CmpOp0.getValueType()));
19974
19975   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19976   if (CC == X86::COND_NE)
19977     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19978                        DL, OtherVal.getValueType(), OtherVal,
19979                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19980   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19981                      DL, OtherVal.getValueType(), OtherVal,
19982                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19983 }
19984
19985 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19986 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19987                                  const X86Subtarget *Subtarget) {
19988   EVT VT = N->getValueType(0);
19989   SDValue Op0 = N->getOperand(0);
19990   SDValue Op1 = N->getOperand(1);
19991
19992   // Try to synthesize horizontal adds from adds of shuffles.
19993   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19994        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19995       isHorizontalBinOp(Op0, Op1, true))
19996     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19997
19998   return OptimizeConditionalInDecrement(N, DAG);
19999 }
20000
20001 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20002                                  const X86Subtarget *Subtarget) {
20003   SDValue Op0 = N->getOperand(0);
20004   SDValue Op1 = N->getOperand(1);
20005
20006   // X86 can't encode an immediate LHS of a sub. See if we can push the
20007   // negation into a preceding instruction.
20008   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20009     // If the RHS of the sub is a XOR with one use and a constant, invert the
20010     // immediate. Then add one to the LHS of the sub so we can turn
20011     // X-Y -> X+~Y+1, saving one register.
20012     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20013         isa<ConstantSDNode>(Op1.getOperand(1))) {
20014       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20015       EVT VT = Op0.getValueType();
20016       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20017                                    Op1.getOperand(0),
20018                                    DAG.getConstant(~XorC, VT));
20019       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20020                          DAG.getConstant(C->getAPIntValue()+1, VT));
20021     }
20022   }
20023
20024   // Try to synthesize horizontal adds from adds of shuffles.
20025   EVT VT = N->getValueType(0);
20026   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20027        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20028       isHorizontalBinOp(Op0, Op1, true))
20029     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20030
20031   return OptimizeConditionalInDecrement(N, DAG);
20032 }
20033
20034 /// performVZEXTCombine - Performs build vector combines
20035 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20036                                         TargetLowering::DAGCombinerInfo &DCI,
20037                                         const X86Subtarget *Subtarget) {
20038   // (vzext (bitcast (vzext (x)) -> (vzext x)
20039   SDValue In = N->getOperand(0);
20040   while (In.getOpcode() == ISD::BITCAST)
20041     In = In.getOperand(0);
20042
20043   if (In.getOpcode() != X86ISD::VZEXT)
20044     return SDValue();
20045
20046   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20047                      In.getOperand(0));
20048 }
20049
20050 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20051                                              DAGCombinerInfo &DCI) const {
20052   SelectionDAG &DAG = DCI.DAG;
20053   switch (N->getOpcode()) {
20054   default: break;
20055   case ISD::EXTRACT_VECTOR_ELT:
20056     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20057   case ISD::VSELECT:
20058   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20059   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20060   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20061   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20062   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20063   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20064   case ISD::SHL:
20065   case ISD::SRA:
20066   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20067   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20068   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20069   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20070   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20071   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20072   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20073   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20074   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20075   case X86ISD::FXOR:
20076   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20077   case X86ISD::FMIN:
20078   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20079   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20080   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20081   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20082   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20083   case ISD::ANY_EXTEND:
20084   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20085   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20086   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20087   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20088   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20089   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20090   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20091   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20092   case X86ISD::SHUFP:       // Handle all target specific shuffles
20093   case X86ISD::PALIGNR:
20094   case X86ISD::UNPCKH:
20095   case X86ISD::UNPCKL:
20096   case X86ISD::MOVHLPS:
20097   case X86ISD::MOVLHPS:
20098   case X86ISD::PSHUFD:
20099   case X86ISD::PSHUFHW:
20100   case X86ISD::PSHUFLW:
20101   case X86ISD::MOVSS:
20102   case X86ISD::MOVSD:
20103   case X86ISD::VPERMILP:
20104   case X86ISD::VPERM2X128:
20105   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20106   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20107   }
20108
20109   return SDValue();
20110 }
20111
20112 /// isTypeDesirableForOp - Return true if the target has native support for
20113 /// the specified value type and it is 'desirable' to use the type for the
20114 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20115 /// instruction encodings are longer and some i16 instructions are slow.
20116 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20117   if (!isTypeLegal(VT))
20118     return false;
20119   if (VT != MVT::i16)
20120     return true;
20121
20122   switch (Opc) {
20123   default:
20124     return true;
20125   case ISD::LOAD:
20126   case ISD::SIGN_EXTEND:
20127   case ISD::ZERO_EXTEND:
20128   case ISD::ANY_EXTEND:
20129   case ISD::SHL:
20130   case ISD::SRL:
20131   case ISD::SUB:
20132   case ISD::ADD:
20133   case ISD::MUL:
20134   case ISD::AND:
20135   case ISD::OR:
20136   case ISD::XOR:
20137     return false;
20138   }
20139 }
20140
20141 /// IsDesirableToPromoteOp - This method query the target whether it is
20142 /// beneficial for dag combiner to promote the specified node. If true, it
20143 /// should return the desired promotion type by reference.
20144 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20145   EVT VT = Op.getValueType();
20146   if (VT != MVT::i16)
20147     return false;
20148
20149   bool Promote = false;
20150   bool Commute = false;
20151   switch (Op.getOpcode()) {
20152   default: break;
20153   case ISD::LOAD: {
20154     LoadSDNode *LD = cast<LoadSDNode>(Op);
20155     // If the non-extending load has a single use and it's not live out, then it
20156     // might be folded.
20157     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20158                                                      Op.hasOneUse()*/) {
20159       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20160              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20161         // The only case where we'd want to promote LOAD (rather then it being
20162         // promoted as an operand is when it's only use is liveout.
20163         if (UI->getOpcode() != ISD::CopyToReg)
20164           return false;
20165       }
20166     }
20167     Promote = true;
20168     break;
20169   }
20170   case ISD::SIGN_EXTEND:
20171   case ISD::ZERO_EXTEND:
20172   case ISD::ANY_EXTEND:
20173     Promote = true;
20174     break;
20175   case ISD::SHL:
20176   case ISD::SRL: {
20177     SDValue N0 = Op.getOperand(0);
20178     // Look out for (store (shl (load), x)).
20179     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20180       return false;
20181     Promote = true;
20182     break;
20183   }
20184   case ISD::ADD:
20185   case ISD::MUL:
20186   case ISD::AND:
20187   case ISD::OR:
20188   case ISD::XOR:
20189     Commute = true;
20190     // fallthrough
20191   case ISD::SUB: {
20192     SDValue N0 = Op.getOperand(0);
20193     SDValue N1 = Op.getOperand(1);
20194     if (!Commute && MayFoldLoad(N1))
20195       return false;
20196     // Avoid disabling potential load folding opportunities.
20197     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20198       return false;
20199     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20200       return false;
20201     Promote = true;
20202   }
20203   }
20204
20205   PVT = MVT::i32;
20206   return Promote;
20207 }
20208
20209 //===----------------------------------------------------------------------===//
20210 //                           X86 Inline Assembly Support
20211 //===----------------------------------------------------------------------===//
20212
20213 namespace {
20214   // Helper to match a string separated by whitespace.
20215   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20216     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20217
20218     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20219       StringRef piece(*args[i]);
20220       if (!s.startswith(piece)) // Check if the piece matches.
20221         return false;
20222
20223       s = s.substr(piece.size());
20224       StringRef::size_type pos = s.find_first_not_of(" \t");
20225       if (pos == 0) // We matched a prefix.
20226         return false;
20227
20228       s = s.substr(pos);
20229     }
20230
20231     return s.empty();
20232   }
20233   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20234 }
20235
20236 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20237
20238   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20239     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20240         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20241         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20242
20243       if (AsmPieces.size() == 3)
20244         return true;
20245       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20246         return true;
20247     }
20248   }
20249   return false;
20250 }
20251
20252 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20253   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20254
20255   std::string AsmStr = IA->getAsmString();
20256
20257   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20258   if (!Ty || Ty->getBitWidth() % 16 != 0)
20259     return false;
20260
20261   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20262   SmallVector<StringRef, 4> AsmPieces;
20263   SplitString(AsmStr, AsmPieces, ";\n");
20264
20265   switch (AsmPieces.size()) {
20266   default: return false;
20267   case 1:
20268     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20269     // we will turn this bswap into something that will be lowered to logical
20270     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20271     // lower so don't worry about this.
20272     // bswap $0
20273     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20274         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20275         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20276         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20277         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20278         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20279       // No need to check constraints, nothing other than the equivalent of
20280       // "=r,0" would be valid here.
20281       return IntrinsicLowering::LowerToByteSwap(CI);
20282     }
20283
20284     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20285     if (CI->getType()->isIntegerTy(16) &&
20286         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20287         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20288          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20289       AsmPieces.clear();
20290       const std::string &ConstraintsStr = IA->getConstraintString();
20291       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20292       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20293       if (clobbersFlagRegisters(AsmPieces))
20294         return IntrinsicLowering::LowerToByteSwap(CI);
20295     }
20296     break;
20297   case 3:
20298     if (CI->getType()->isIntegerTy(32) &&
20299         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20300         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20301         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20302         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20303       AsmPieces.clear();
20304       const std::string &ConstraintsStr = IA->getConstraintString();
20305       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20306       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20307       if (clobbersFlagRegisters(AsmPieces))
20308         return IntrinsicLowering::LowerToByteSwap(CI);
20309     }
20310
20311     if (CI->getType()->isIntegerTy(64)) {
20312       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20313       if (Constraints.size() >= 2 &&
20314           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20315           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20316         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20317         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20318             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20319             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20320           return IntrinsicLowering::LowerToByteSwap(CI);
20321       }
20322     }
20323     break;
20324   }
20325   return false;
20326 }
20327
20328 /// getConstraintType - Given a constraint letter, return the type of
20329 /// constraint it is for this target.
20330 X86TargetLowering::ConstraintType
20331 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20332   if (Constraint.size() == 1) {
20333     switch (Constraint[0]) {
20334     case 'R':
20335     case 'q':
20336     case 'Q':
20337     case 'f':
20338     case 't':
20339     case 'u':
20340     case 'y':
20341     case 'x':
20342     case 'Y':
20343     case 'l':
20344       return C_RegisterClass;
20345     case 'a':
20346     case 'b':
20347     case 'c':
20348     case 'd':
20349     case 'S':
20350     case 'D':
20351     case 'A':
20352       return C_Register;
20353     case 'I':
20354     case 'J':
20355     case 'K':
20356     case 'L':
20357     case 'M':
20358     case 'N':
20359     case 'G':
20360     case 'C':
20361     case 'e':
20362     case 'Z':
20363       return C_Other;
20364     default:
20365       break;
20366     }
20367   }
20368   return TargetLowering::getConstraintType(Constraint);
20369 }
20370
20371 /// Examine constraint type and operand type and determine a weight value.
20372 /// This object must already have been set up with the operand type
20373 /// and the current alternative constraint selected.
20374 TargetLowering::ConstraintWeight
20375   X86TargetLowering::getSingleConstraintMatchWeight(
20376     AsmOperandInfo &info, const char *constraint) const {
20377   ConstraintWeight weight = CW_Invalid;
20378   Value *CallOperandVal = info.CallOperandVal;
20379     // If we don't have a value, we can't do a match,
20380     // but allow it at the lowest weight.
20381   if (!CallOperandVal)
20382     return CW_Default;
20383   Type *type = CallOperandVal->getType();
20384   // Look at the constraint type.
20385   switch (*constraint) {
20386   default:
20387     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20388   case 'R':
20389   case 'q':
20390   case 'Q':
20391   case 'a':
20392   case 'b':
20393   case 'c':
20394   case 'd':
20395   case 'S':
20396   case 'D':
20397   case 'A':
20398     if (CallOperandVal->getType()->isIntegerTy())
20399       weight = CW_SpecificReg;
20400     break;
20401   case 'f':
20402   case 't':
20403   case 'u':
20404     if (type->isFloatingPointTy())
20405       weight = CW_SpecificReg;
20406     break;
20407   case 'y':
20408     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20409       weight = CW_SpecificReg;
20410     break;
20411   case 'x':
20412   case 'Y':
20413     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20414         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20415       weight = CW_Register;
20416     break;
20417   case 'I':
20418     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20419       if (C->getZExtValue() <= 31)
20420         weight = CW_Constant;
20421     }
20422     break;
20423   case 'J':
20424     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20425       if (C->getZExtValue() <= 63)
20426         weight = CW_Constant;
20427     }
20428     break;
20429   case 'K':
20430     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20431       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20432         weight = CW_Constant;
20433     }
20434     break;
20435   case 'L':
20436     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20437       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20438         weight = CW_Constant;
20439     }
20440     break;
20441   case 'M':
20442     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20443       if (C->getZExtValue() <= 3)
20444         weight = CW_Constant;
20445     }
20446     break;
20447   case 'N':
20448     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20449       if (C->getZExtValue() <= 0xff)
20450         weight = CW_Constant;
20451     }
20452     break;
20453   case 'G':
20454   case 'C':
20455     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20456       weight = CW_Constant;
20457     }
20458     break;
20459   case 'e':
20460     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20461       if ((C->getSExtValue() >= -0x80000000LL) &&
20462           (C->getSExtValue() <= 0x7fffffffLL))
20463         weight = CW_Constant;
20464     }
20465     break;
20466   case 'Z':
20467     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20468       if (C->getZExtValue() <= 0xffffffff)
20469         weight = CW_Constant;
20470     }
20471     break;
20472   }
20473   return weight;
20474 }
20475
20476 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20477 /// with another that has more specific requirements based on the type of the
20478 /// corresponding operand.
20479 const char *X86TargetLowering::
20480 LowerXConstraint(EVT ConstraintVT) const {
20481   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20482   // 'f' like normal targets.
20483   if (ConstraintVT.isFloatingPoint()) {
20484     if (Subtarget->hasSSE2())
20485       return "Y";
20486     if (Subtarget->hasSSE1())
20487       return "x";
20488   }
20489
20490   return TargetLowering::LowerXConstraint(ConstraintVT);
20491 }
20492
20493 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20494 /// vector.  If it is invalid, don't add anything to Ops.
20495 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20496                                                      std::string &Constraint,
20497                                                      std::vector<SDValue>&Ops,
20498                                                      SelectionDAG &DAG) const {
20499   SDValue Result;
20500
20501   // Only support length 1 constraints for now.
20502   if (Constraint.length() > 1) return;
20503
20504   char ConstraintLetter = Constraint[0];
20505   switch (ConstraintLetter) {
20506   default: break;
20507   case 'I':
20508     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20509       if (C->getZExtValue() <= 31) {
20510         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20511         break;
20512       }
20513     }
20514     return;
20515   case 'J':
20516     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20517       if (C->getZExtValue() <= 63) {
20518         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20519         break;
20520       }
20521     }
20522     return;
20523   case 'K':
20524     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20525       if (isInt<8>(C->getSExtValue())) {
20526         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20527         break;
20528       }
20529     }
20530     return;
20531   case 'N':
20532     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20533       if (C->getZExtValue() <= 255) {
20534         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20535         break;
20536       }
20537     }
20538     return;
20539   case 'e': {
20540     // 32-bit signed value
20541     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20542       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20543                                            C->getSExtValue())) {
20544         // Widen to 64 bits here to get it sign extended.
20545         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20546         break;
20547       }
20548     // FIXME gcc accepts some relocatable values here too, but only in certain
20549     // memory models; it's complicated.
20550     }
20551     return;
20552   }
20553   case 'Z': {
20554     // 32-bit unsigned value
20555     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20556       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20557                                            C->getZExtValue())) {
20558         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20559         break;
20560       }
20561     }
20562     // FIXME gcc accepts some relocatable values here too, but only in certain
20563     // memory models; it's complicated.
20564     return;
20565   }
20566   case 'i': {
20567     // Literal immediates are always ok.
20568     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20569       // Widen to 64 bits here to get it sign extended.
20570       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20571       break;
20572     }
20573
20574     // In any sort of PIC mode addresses need to be computed at runtime by
20575     // adding in a register or some sort of table lookup.  These can't
20576     // be used as immediates.
20577     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20578       return;
20579
20580     // If we are in non-pic codegen mode, we allow the address of a global (with
20581     // an optional displacement) to be used with 'i'.
20582     GlobalAddressSDNode *GA = nullptr;
20583     int64_t Offset = 0;
20584
20585     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20586     while (1) {
20587       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20588         Offset += GA->getOffset();
20589         break;
20590       } else if (Op.getOpcode() == ISD::ADD) {
20591         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20592           Offset += C->getZExtValue();
20593           Op = Op.getOperand(0);
20594           continue;
20595         }
20596       } else if (Op.getOpcode() == ISD::SUB) {
20597         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20598           Offset += -C->getZExtValue();
20599           Op = Op.getOperand(0);
20600           continue;
20601         }
20602       }
20603
20604       // Otherwise, this isn't something we can handle, reject it.
20605       return;
20606     }
20607
20608     const GlobalValue *GV = GA->getGlobal();
20609     // If we require an extra load to get this address, as in PIC mode, we
20610     // can't accept it.
20611     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20612                                                         getTargetMachine())))
20613       return;
20614
20615     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20616                                         GA->getValueType(0), Offset);
20617     break;
20618   }
20619   }
20620
20621   if (Result.getNode()) {
20622     Ops.push_back(Result);
20623     return;
20624   }
20625   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20626 }
20627
20628 std::pair<unsigned, const TargetRegisterClass*>
20629 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20630                                                 MVT VT) const {
20631   // First, see if this is a constraint that directly corresponds to an LLVM
20632   // register class.
20633   if (Constraint.size() == 1) {
20634     // GCC Constraint Letters
20635     switch (Constraint[0]) {
20636     default: break;
20637       // TODO: Slight differences here in allocation order and leaving
20638       // RIP in the class. Do they matter any more here than they do
20639       // in the normal allocation?
20640     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20641       if (Subtarget->is64Bit()) {
20642         if (VT == MVT::i32 || VT == MVT::f32)
20643           return std::make_pair(0U, &X86::GR32RegClass);
20644         if (VT == MVT::i16)
20645           return std::make_pair(0U, &X86::GR16RegClass);
20646         if (VT == MVT::i8 || VT == MVT::i1)
20647           return std::make_pair(0U, &X86::GR8RegClass);
20648         if (VT == MVT::i64 || VT == MVT::f64)
20649           return std::make_pair(0U, &X86::GR64RegClass);
20650         break;
20651       }
20652       // 32-bit fallthrough
20653     case 'Q':   // Q_REGS
20654       if (VT == MVT::i32 || VT == MVT::f32)
20655         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20656       if (VT == MVT::i16)
20657         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20658       if (VT == MVT::i8 || VT == MVT::i1)
20659         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20660       if (VT == MVT::i64)
20661         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20662       break;
20663     case 'r':   // GENERAL_REGS
20664     case 'l':   // INDEX_REGS
20665       if (VT == MVT::i8 || VT == MVT::i1)
20666         return std::make_pair(0U, &X86::GR8RegClass);
20667       if (VT == MVT::i16)
20668         return std::make_pair(0U, &X86::GR16RegClass);
20669       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20670         return std::make_pair(0U, &X86::GR32RegClass);
20671       return std::make_pair(0U, &X86::GR64RegClass);
20672     case 'R':   // LEGACY_REGS
20673       if (VT == MVT::i8 || VT == MVT::i1)
20674         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20675       if (VT == MVT::i16)
20676         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20677       if (VT == MVT::i32 || !Subtarget->is64Bit())
20678         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20679       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20680     case 'f':  // FP Stack registers.
20681       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20682       // value to the correct fpstack register class.
20683       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20684         return std::make_pair(0U, &X86::RFP32RegClass);
20685       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20686         return std::make_pair(0U, &X86::RFP64RegClass);
20687       return std::make_pair(0U, &X86::RFP80RegClass);
20688     case 'y':   // MMX_REGS if MMX allowed.
20689       if (!Subtarget->hasMMX()) break;
20690       return std::make_pair(0U, &X86::VR64RegClass);
20691     case 'Y':   // SSE_REGS if SSE2 allowed
20692       if (!Subtarget->hasSSE2()) break;
20693       // FALL THROUGH.
20694     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20695       if (!Subtarget->hasSSE1()) break;
20696
20697       switch (VT.SimpleTy) {
20698       default: break;
20699       // Scalar SSE types.
20700       case MVT::f32:
20701       case MVT::i32:
20702         return std::make_pair(0U, &X86::FR32RegClass);
20703       case MVT::f64:
20704       case MVT::i64:
20705         return std::make_pair(0U, &X86::FR64RegClass);
20706       // Vector types.
20707       case MVT::v16i8:
20708       case MVT::v8i16:
20709       case MVT::v4i32:
20710       case MVT::v2i64:
20711       case MVT::v4f32:
20712       case MVT::v2f64:
20713         return std::make_pair(0U, &X86::VR128RegClass);
20714       // AVX types.
20715       case MVT::v32i8:
20716       case MVT::v16i16:
20717       case MVT::v8i32:
20718       case MVT::v4i64:
20719       case MVT::v8f32:
20720       case MVT::v4f64:
20721         return std::make_pair(0U, &X86::VR256RegClass);
20722       case MVT::v8f64:
20723       case MVT::v16f32:
20724       case MVT::v16i32:
20725       case MVT::v8i64:
20726         return std::make_pair(0U, &X86::VR512RegClass);
20727       }
20728       break;
20729     }
20730   }
20731
20732   // Use the default implementation in TargetLowering to convert the register
20733   // constraint into a member of a register class.
20734   std::pair<unsigned, const TargetRegisterClass*> Res;
20735   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20736
20737   // Not found as a standard register?
20738   if (!Res.second) {
20739     // Map st(0) -> st(7) -> ST0
20740     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20741         tolower(Constraint[1]) == 's' &&
20742         tolower(Constraint[2]) == 't' &&
20743         Constraint[3] == '(' &&
20744         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20745         Constraint[5] == ')' &&
20746         Constraint[6] == '}') {
20747
20748       Res.first = X86::ST0+Constraint[4]-'0';
20749       Res.second = &X86::RFP80RegClass;
20750       return Res;
20751     }
20752
20753     // GCC allows "st(0)" to be called just plain "st".
20754     if (StringRef("{st}").equals_lower(Constraint)) {
20755       Res.first = X86::ST0;
20756       Res.second = &X86::RFP80RegClass;
20757       return Res;
20758     }
20759
20760     // flags -> EFLAGS
20761     if (StringRef("{flags}").equals_lower(Constraint)) {
20762       Res.first = X86::EFLAGS;
20763       Res.second = &X86::CCRRegClass;
20764       return Res;
20765     }
20766
20767     // 'A' means EAX + EDX.
20768     if (Constraint == "A") {
20769       Res.first = X86::EAX;
20770       Res.second = &X86::GR32_ADRegClass;
20771       return Res;
20772     }
20773     return Res;
20774   }
20775
20776   // Otherwise, check to see if this is a register class of the wrong value
20777   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20778   // turn into {ax},{dx}.
20779   if (Res.second->hasType(VT))
20780     return Res;   // Correct type already, nothing to do.
20781
20782   // All of the single-register GCC register classes map their values onto
20783   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20784   // really want an 8-bit or 32-bit register, map to the appropriate register
20785   // class and return the appropriate register.
20786   if (Res.second == &X86::GR16RegClass) {
20787     if (VT == MVT::i8 || VT == MVT::i1) {
20788       unsigned DestReg = 0;
20789       switch (Res.first) {
20790       default: break;
20791       case X86::AX: DestReg = X86::AL; break;
20792       case X86::DX: DestReg = X86::DL; break;
20793       case X86::CX: DestReg = X86::CL; break;
20794       case X86::BX: DestReg = X86::BL; break;
20795       }
20796       if (DestReg) {
20797         Res.first = DestReg;
20798         Res.second = &X86::GR8RegClass;
20799       }
20800     } else if (VT == MVT::i32 || VT == MVT::f32) {
20801       unsigned DestReg = 0;
20802       switch (Res.first) {
20803       default: break;
20804       case X86::AX: DestReg = X86::EAX; break;
20805       case X86::DX: DestReg = X86::EDX; break;
20806       case X86::CX: DestReg = X86::ECX; break;
20807       case X86::BX: DestReg = X86::EBX; break;
20808       case X86::SI: DestReg = X86::ESI; break;
20809       case X86::DI: DestReg = X86::EDI; break;
20810       case X86::BP: DestReg = X86::EBP; break;
20811       case X86::SP: DestReg = X86::ESP; break;
20812       }
20813       if (DestReg) {
20814         Res.first = DestReg;
20815         Res.second = &X86::GR32RegClass;
20816       }
20817     } else if (VT == MVT::i64 || VT == MVT::f64) {
20818       unsigned DestReg = 0;
20819       switch (Res.first) {
20820       default: break;
20821       case X86::AX: DestReg = X86::RAX; break;
20822       case X86::DX: DestReg = X86::RDX; break;
20823       case X86::CX: DestReg = X86::RCX; break;
20824       case X86::BX: DestReg = X86::RBX; break;
20825       case X86::SI: DestReg = X86::RSI; break;
20826       case X86::DI: DestReg = X86::RDI; break;
20827       case X86::BP: DestReg = X86::RBP; break;
20828       case X86::SP: DestReg = X86::RSP; break;
20829       }
20830       if (DestReg) {
20831         Res.first = DestReg;
20832         Res.second = &X86::GR64RegClass;
20833       }
20834     }
20835   } else if (Res.second == &X86::FR32RegClass ||
20836              Res.second == &X86::FR64RegClass ||
20837              Res.second == &X86::VR128RegClass ||
20838              Res.second == &X86::VR256RegClass ||
20839              Res.second == &X86::FR32XRegClass ||
20840              Res.second == &X86::FR64XRegClass ||
20841              Res.second == &X86::VR128XRegClass ||
20842              Res.second == &X86::VR256XRegClass ||
20843              Res.second == &X86::VR512RegClass) {
20844     // Handle references to XMM physical registers that got mapped into the
20845     // wrong class.  This can happen with constraints like {xmm0} where the
20846     // target independent register mapper will just pick the first match it can
20847     // find, ignoring the required type.
20848
20849     if (VT == MVT::f32 || VT == MVT::i32)
20850       Res.second = &X86::FR32RegClass;
20851     else if (VT == MVT::f64 || VT == MVT::i64)
20852       Res.second = &X86::FR64RegClass;
20853     else if (X86::VR128RegClass.hasType(VT))
20854       Res.second = &X86::VR128RegClass;
20855     else if (X86::VR256RegClass.hasType(VT))
20856       Res.second = &X86::VR256RegClass;
20857     else if (X86::VR512RegClass.hasType(VT))
20858       Res.second = &X86::VR512RegClass;
20859   }
20860
20861   return Res;
20862 }
20863
20864 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20865                                             Type *Ty) const {
20866   // Scaling factors are not free at all.
20867   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20868   // will take 2 allocations in the out of order engine instead of 1
20869   // for plain addressing mode, i.e. inst (reg1).
20870   // E.g.,
20871   // vaddps (%rsi,%drx), %ymm0, %ymm1
20872   // Requires two allocations (one for the load, one for the computation)
20873   // whereas:
20874   // vaddps (%rsi), %ymm0, %ymm1
20875   // Requires just 1 allocation, i.e., freeing allocations for other operations
20876   // and having less micro operations to execute.
20877   //
20878   // For some X86 architectures, this is even worse because for instance for
20879   // stores, the complex addressing mode forces the instruction to use the
20880   // "load" ports instead of the dedicated "store" port.
20881   // E.g., on Haswell:
20882   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
20883   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
20884   if (isLegalAddressingMode(AM, Ty))
20885     // Scale represents reg2 * scale, thus account for 1
20886     // as soon as we use a second register.
20887     return AM.Scale != 0;
20888   return -1;
20889 }