[X86] Teach how to dump the name of target node RDTSCP_DAG.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 #define DEBUG_TYPE "x86-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64                                 SelectionDAG &DAG, SDLoc dl,
65                                 unsigned vectorWidth) {
66   assert((vectorWidth == 128 || vectorWidth == 256) &&
67          "Unsupported vector width");
68   EVT VT = Vec.getValueType();
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/vectorWidth;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
79   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80
81   // This is the index of the first element of the vectorWidth-bit chunk
82   // we want.
83   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84                                * ElemsPerChunk);
85
86   // If the input is a buildvector just emit a smaller one.
87   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
90                                     ElemsPerChunk));
91
92   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94                                VecIdx);
95
96   return Result;
97
98 }
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106                                    SelectionDAG &DAG, SDLoc dl) {
107   assert((Vec.getValueType().is256BitVector() ||
108           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 }
111
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114                                    SelectionDAG &DAG, SDLoc dl) {
115   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 }
118
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120                                unsigned IdxVal, SelectionDAG &DAG,
121                                SDLoc dl, unsigned vectorWidth) {
122   assert((vectorWidth == 128 || vectorWidth == 256) &&
123          "Unsupported vector width");
124   // Inserting UNDEF is Result
125   if (Vec.getOpcode() == ISD::UNDEF)
126     return Result;
127   EVT VT = Vec.getValueType();
128   EVT ElVT = VT.getVectorElementType();
129   EVT ResultVT = Result.getValueType();
130
131   // Insert the relevant vectorWidth bits.
132   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133
134   // This is the index of the first element of the vectorWidth-bit chunk
135   // we want.
136   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137                                * ElemsPerChunk);
138
139   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141                      VecIdx);
142 }
143 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference.  Idx is an index in the 128 bits
147 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150                                   unsigned IdxVal, SelectionDAG &DAG,
151                                   SDLoc dl) {
152   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 }
155
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 }
162
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168                                    unsigned NumElems, SelectionDAG &DAG,
169                                    SDLoc dl) {
170   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 }
173
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
182   if (TT.isOSBinFormatMachO()) {
183     if (TT.getArch() == Triple::x86_64)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (TT.isOSLinux())
189     return new X86LinuxTargetObjectFile();
190   if (TT.isOSBinFormatELF())
191     return new TargetLoweringObjectFileELF();
192   if (TT.isKnownWindowsMSVCEnvironment())
193     return new X86WindowsTargetObjectFile();
194   if (TT.isOSBinFormatCOFF())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 // FIXME: This should stop caching the target machine as soon as
200 // we can remove resetOperationActions et al.
201 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
202   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
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::f32,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
447   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
448   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
449   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
450   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
451   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
452   if (Subtarget->is64Bit())
453     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
454   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
455   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
456   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
457   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
458   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
459   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
460   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
461   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
462
463   // Promote the i8 variants and force them on up to i32 which has a shorter
464   // encoding.
465   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
466   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
467   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
468   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
469   if (Subtarget->hasBMI()) {
470     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
471     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
472     if (Subtarget->is64Bit())
473       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
474   } else {
475     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
476     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
477     if (Subtarget->is64Bit())
478       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
479   }
480
481   if (Subtarget->hasLZCNT()) {
482     // When promoting the i8 variants, force them to i32 for a shorter
483     // encoding.
484     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
485     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
487     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
492   } else {
493     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
494     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
495     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
496     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
497     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
498     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
499     if (Subtarget->is64Bit()) {
500       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
501       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
502     }
503   }
504
505   if (Subtarget->hasPOPCNT()) {
506     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
507   } else {
508     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
509     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
510     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
511     if (Subtarget->is64Bit())
512       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
513   }
514
515   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
516
517   if (!Subtarget->hasMOVBE())
518     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
519
520   // These should be promoted to a larger select which is supported.
521   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
522   // X86 wants to expand cmov itself.
523   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
524   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
525   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
526   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
527   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
528   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
530   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
531   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
532   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
533   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
534   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
535   if (Subtarget->is64Bit()) {
536     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
537     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
538   }
539   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
540   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
541   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
542   // support continuation, user-level threading, and etc.. As a result, no
543   // other SjLj exception interfaces are implemented and please don't build
544   // your own exception handling based on them.
545   // LLVM/Clang supports zero-cost DWARF exception handling.
546   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
547   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
548
549   // Darwin ABI issue.
550   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
551   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
552   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
553   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
554   if (Subtarget->is64Bit())
555     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
556   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
557   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
558   if (Subtarget->is64Bit()) {
559     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
560     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
561     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
562     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
563     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
564   }
565   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
566   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
567   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
568   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
569   if (Subtarget->is64Bit()) {
570     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
571     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
572     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
573   }
574
575   if (Subtarget->hasSSE1())
576     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
577
578   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
579
580   // Expand certain atomics
581   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
582     MVT VT = IntVTs[i];
583     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
585     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
586   }
587
588   if (!Subtarget->is64Bit()) {
589     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
594     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
595     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
596     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
597     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
598     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
599     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
600     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
601   }
602
603   if (Subtarget->hasCmpxchg16b()) {
604     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
605   }
606
607   // FIXME - use subtarget debug flags
608   if (!Subtarget->isTargetDarwin() &&
609       !Subtarget->isTargetELF() &&
610       !Subtarget->isTargetCygMing()) {
611     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
612   }
613
614   if (Subtarget->is64Bit()) {
615     setExceptionPointerRegister(X86::RAX);
616     setExceptionSelectorRegister(X86::RDX);
617   } else {
618     setExceptionPointerRegister(X86::EAX);
619     setExceptionSelectorRegister(X86::EDX);
620   }
621   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
622   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
623
624   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
625   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
626
627   setOperationAction(ISD::TRAP, MVT::Other, Legal);
628   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
629
630   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
631   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
632   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
633   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
634     // TargetInfo::X86_64ABIBuiltinVaList
635     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
636     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
637   } else {
638     // TargetInfo::CharPtrBuiltinVaList
639     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
640     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
641   }
642
643   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
644   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
645
646   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
647                      MVT::i64 : MVT::i32, Custom);
648
649   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
650     // f32 and f64 use SSE.
651     // Set up the FP register classes.
652     addRegisterClass(MVT::f32, &X86::FR32RegClass);
653     addRegisterClass(MVT::f64, &X86::FR64RegClass);
654
655     // Use ANDPD to simulate FABS.
656     setOperationAction(ISD::FABS , MVT::f64, Custom);
657     setOperationAction(ISD::FABS , MVT::f32, Custom);
658
659     // Use XORP to simulate FNEG.
660     setOperationAction(ISD::FNEG , MVT::f64, Custom);
661     setOperationAction(ISD::FNEG , MVT::f32, Custom);
662
663     // Use ANDPD and ORPD to simulate FCOPYSIGN.
664     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
665     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
666
667     // Lower this to FGETSIGNx86 plus an AND.
668     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
669     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
670
671     // We don't support sin/cos/fmod
672     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
673     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
674     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
675     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
676     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
677     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
678
679     // Expand FP immediates into loads from the stack, except for the special
680     // cases we handle.
681     addLegalFPImmediate(APFloat(+0.0)); // xorpd
682     addLegalFPImmediate(APFloat(+0.0f)); // xorps
683   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
684     // Use SSE for f32, x87 for f64.
685     // Set up the FP register classes.
686     addRegisterClass(MVT::f32, &X86::FR32RegClass);
687     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
688
689     // Use ANDPS to simulate FABS.
690     setOperationAction(ISD::FABS , MVT::f32, Custom);
691
692     // Use XORP to simulate FNEG.
693     setOperationAction(ISD::FNEG , MVT::f32, Custom);
694
695     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
696
697     // Use ANDPS and ORPS to simulate FCOPYSIGN.
698     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
699     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
700
701     // We don't support sin/cos/fmod
702     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
703     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
704     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
705
706     // Special cases we handle for FP constants.
707     addLegalFPImmediate(APFloat(+0.0f)); // xorps
708     addLegalFPImmediate(APFloat(+0.0)); // FLD0
709     addLegalFPImmediate(APFloat(+1.0)); // FLD1
710     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
711     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
712
713     if (!TM.Options.UnsafeFPMath) {
714       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
715       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
716       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
717     }
718   } else if (!TM.Options.UseSoftFloat) {
719     // f32 and f64 in x87.
720     // Set up the FP register classes.
721     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
722     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
723
724     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
725     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
726     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
727     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
732       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
733       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
734       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
735       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
736     }
737     addLegalFPImmediate(APFloat(+0.0)); // FLD0
738     addLegalFPImmediate(APFloat(+1.0)); // FLD1
739     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
740     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
741     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
742     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
743     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
744     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
745   }
746
747   // We don't support FMA.
748   setOperationAction(ISD::FMA, MVT::f64, Expand);
749   setOperationAction(ISD::FMA, MVT::f32, Expand);
750
751   // Long double always uses X87.
752   if (!TM.Options.UseSoftFloat) {
753     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
754     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
755     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
756     {
757       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
758       addLegalFPImmediate(TmpFlt);  // FLD0
759       TmpFlt.changeSign();
760       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
761
762       bool ignored;
763       APFloat TmpFlt2(+1.0);
764       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
765                       &ignored);
766       addLegalFPImmediate(TmpFlt2);  // FLD1
767       TmpFlt2.changeSign();
768       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
769     }
770
771     if (!TM.Options.UnsafeFPMath) {
772       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
773       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
774       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
775     }
776
777     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
778     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
779     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
780     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
781     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
782     setOperationAction(ISD::FMA, MVT::f80, Expand);
783   }
784
785   // Always use a library call for pow.
786   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
787   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
788   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
789
790   setOperationAction(ISD::FLOG, MVT::f80, Expand);
791   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
792   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
793   setOperationAction(ISD::FEXP, MVT::f80, Expand);
794   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
795
796   // First set operation action for all vector types to either promote
797   // (for widening) or expand (for scalarization). Then we will selectively
798   // turn on ones that can be effectively codegen'd.
799   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
800            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
801     MVT VT = (MVT::SimpleValueType)i;
802     setOperationAction(ISD::ADD , VT, Expand);
803     setOperationAction(ISD::SUB , VT, Expand);
804     setOperationAction(ISD::FADD, VT, Expand);
805     setOperationAction(ISD::FNEG, VT, Expand);
806     setOperationAction(ISD::FSUB, VT, Expand);
807     setOperationAction(ISD::MUL , VT, Expand);
808     setOperationAction(ISD::FMUL, VT, Expand);
809     setOperationAction(ISD::SDIV, VT, Expand);
810     setOperationAction(ISD::UDIV, VT, Expand);
811     setOperationAction(ISD::FDIV, VT, Expand);
812     setOperationAction(ISD::SREM, VT, Expand);
813     setOperationAction(ISD::UREM, VT, Expand);
814     setOperationAction(ISD::LOAD, VT, Expand);
815     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
816     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
817     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
818     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
819     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
820     setOperationAction(ISD::FABS, VT, Expand);
821     setOperationAction(ISD::FSIN, VT, Expand);
822     setOperationAction(ISD::FSINCOS, VT, Expand);
823     setOperationAction(ISD::FCOS, VT, Expand);
824     setOperationAction(ISD::FSINCOS, VT, Expand);
825     setOperationAction(ISD::FREM, VT, Expand);
826     setOperationAction(ISD::FMA,  VT, Expand);
827     setOperationAction(ISD::FPOWI, VT, Expand);
828     setOperationAction(ISD::FSQRT, VT, Expand);
829     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
830     setOperationAction(ISD::FFLOOR, VT, Expand);
831     setOperationAction(ISD::FCEIL, VT, Expand);
832     setOperationAction(ISD::FTRUNC, VT, Expand);
833     setOperationAction(ISD::FRINT, VT, Expand);
834     setOperationAction(ISD::FNEARBYINT, VT, Expand);
835     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
836     setOperationAction(ISD::MULHS, VT, Expand);
837     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
838     setOperationAction(ISD::MULHU, VT, Expand);
839     setOperationAction(ISD::SDIVREM, VT, Expand);
840     setOperationAction(ISD::UDIVREM, VT, Expand);
841     setOperationAction(ISD::FPOW, VT, Expand);
842     setOperationAction(ISD::CTPOP, VT, Expand);
843     setOperationAction(ISD::CTTZ, VT, Expand);
844     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
845     setOperationAction(ISD::CTLZ, VT, Expand);
846     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
847     setOperationAction(ISD::SHL, VT, Expand);
848     setOperationAction(ISD::SRA, VT, Expand);
849     setOperationAction(ISD::SRL, VT, Expand);
850     setOperationAction(ISD::ROTL, VT, Expand);
851     setOperationAction(ISD::ROTR, VT, Expand);
852     setOperationAction(ISD::BSWAP, VT, Expand);
853     setOperationAction(ISD::SETCC, VT, Expand);
854     setOperationAction(ISD::FLOG, VT, Expand);
855     setOperationAction(ISD::FLOG2, VT, Expand);
856     setOperationAction(ISD::FLOG10, VT, Expand);
857     setOperationAction(ISD::FEXP, VT, Expand);
858     setOperationAction(ISD::FEXP2, VT, Expand);
859     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
860     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
861     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
862     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
863     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
864     setOperationAction(ISD::TRUNCATE, VT, Expand);
865     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
866     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
867     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
868     setOperationAction(ISD::VSELECT, VT, Expand);
869     setOperationAction(ISD::SELECT_CC, VT, Expand);
870     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
871              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
872       setTruncStoreAction(VT,
873                           (MVT::SimpleValueType)InnerVT, Expand);
874     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
875     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
876     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
877   }
878
879   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
880   // with -msoft-float, disable use of MMX as well.
881   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
882     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
883     // No operations on x86mmx supported, everything uses intrinsics.
884   }
885
886   // MMX-sized vectors (other than x86mmx) are expected to be expanded
887   // into smaller operations.
888   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
889   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
890   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
891   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
892   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
893   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
894   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
895   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
896   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
897   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
898   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
899   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
900   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
901   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
902   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
903   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
904   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
905   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
906   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
907   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
908   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
909   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
910   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
911   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
912   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
913   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
914   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
915   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
916   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
917
918   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
919     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
920
921     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
922     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
923     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
924     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
925     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
926     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
927     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
928     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
929     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
930     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
931     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
932     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
933   }
934
935   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
936     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
937
938     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
939     // registers cannot be used even for integer operations.
940     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
941     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
942     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
943     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
944
945     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
946     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
947     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
948     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
949     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
950     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
951     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
952     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
953     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
954     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
955     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
956     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
957     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
958     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
959     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
960     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
961     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
962     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
963     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
964     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
965     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
966     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
967
968     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
969     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
970     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
971     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
972
973     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
974     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
975     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
976     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
977     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
978
979     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
980     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
981       MVT VT = (MVT::SimpleValueType)i;
982       // Do not attempt to custom lower non-power-of-2 vectors
983       if (!isPowerOf2_32(VT.getVectorNumElements()))
984         continue;
985       // Do not attempt to custom lower non-128-bit vectors
986       if (!VT.is128BitVector())
987         continue;
988       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
989       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
991     }
992
993     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
994     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
995     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
996     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
999
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004
1005     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1006     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1007       MVT VT = (MVT::SimpleValueType)i;
1008
1009       // Do not attempt to promote non-128-bit vectors
1010       if (!VT.is128BitVector())
1011         continue;
1012
1013       setOperationAction(ISD::AND,    VT, Promote);
1014       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1015       setOperationAction(ISD::OR,     VT, Promote);
1016       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1017       setOperationAction(ISD::XOR,    VT, Promote);
1018       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1019       setOperationAction(ISD::LOAD,   VT, Promote);
1020       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1021       setOperationAction(ISD::SELECT, VT, Promote);
1022       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1023     }
1024
1025     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1026
1027     // Custom lower v2i64 and v2f64 selects.
1028     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1029     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1030     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1031     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1032
1033     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1034     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1035
1036     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1037     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1038     // As there is no 64-bit GPR available, we need build a special custom
1039     // sequence to convert from v2i32 to v2f32.
1040     if (!Subtarget->is64Bit())
1041       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1042
1043     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1044     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1045
1046     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1047
1048     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1049     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1050     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1051   }
1052
1053   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1054     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1055     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1056     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1057     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1058     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1059     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1060     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1061     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1062     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1063     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1064
1065     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1068     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1070     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1071     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1072     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1073     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1074     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1075
1076     // FIXME: Do we need to handle scalar-to-vector here?
1077     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1078
1079     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1080     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1081     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1082     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1083     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1084     // There is no BLENDI for byte vectors. We don't need to custom lower
1085     // some vselects for now.
1086     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1087
1088     // i8 and i16 vectors are custom , because the source register and source
1089     // source memory operand types are not the same width.  f32 vectors are
1090     // custom since the immediate controlling the insert encodes additional
1091     // information.
1092     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1093     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1094     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1095     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1096
1097     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1098     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1099     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1100     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1101
1102     // FIXME: these should be Legal but thats only for the case where
1103     // the index is constant.  For now custom expand to deal with that.
1104     if (Subtarget->is64Bit()) {
1105       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1106       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1107     }
1108   }
1109
1110   if (Subtarget->hasSSE2()) {
1111     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1112     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1113
1114     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1115     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1116
1117     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1118     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1119
1120     // In the customized shift lowering, the legal cases in AVX2 will be
1121     // recognized.
1122     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1123     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1124
1125     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1126     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1127
1128     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1129   }
1130
1131   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1132     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1133     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1134     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1135     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1136     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1137     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1138
1139     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1140     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1142
1143     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1144     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1145     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1146     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1147     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1148     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1149     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1150     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1151     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1152     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1153     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1154     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1155
1156     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1157     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1158     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1159     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1160     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1161     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1162     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1163     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1164     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1165     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1166     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1167     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1168
1169     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1170     // even though v8i16 is a legal type.
1171     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1172     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1173     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1174
1175     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1176     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1177     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1178
1179     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1180     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1181
1182     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1183
1184     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1185     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1186
1187     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1188     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1189
1190     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1191     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1192
1193     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1194     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1195     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1196     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1197
1198     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1199     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1200     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1201
1202     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1203     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1204     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1205     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1206
1207     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1208     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1209     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1210     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1211     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1212     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1213     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1214     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1215     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1216     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1217     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1218     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1219
1220     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1221       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1222       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1223       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1224       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1225       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1226       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1227     }
1228
1229     if (Subtarget->hasInt256()) {
1230       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1231       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1232       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1233       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1234
1235       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1236       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1237       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1238       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1239
1240       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1241       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1242       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1243       // Don't lower v32i8 because there is no 128-bit byte mul
1244
1245       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1246       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1247       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1248       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1249
1250       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1251       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1252     } else {
1253       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1254       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1255       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1256       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1257
1258       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1259       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1260       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1261       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1262
1263       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1264       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1265       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1266       // Don't lower v32i8 because there is no 128-bit byte mul
1267     }
1268
1269     // In the customized shift lowering, the legal cases in AVX2 will be
1270     // recognized.
1271     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1272     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1273
1274     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1275     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1276
1277     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1278
1279     // Custom lower several nodes for 256-bit types.
1280     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1281              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1282       MVT VT = (MVT::SimpleValueType)i;
1283
1284       // Extract subvector is special because the value type
1285       // (result) is 128-bit but the source is 256-bit wide.
1286       if (VT.is128BitVector())
1287         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1288
1289       // Do not attempt to custom lower other non-256-bit vectors
1290       if (!VT.is256BitVector())
1291         continue;
1292
1293       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1294       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1295       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1296       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1297       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1298       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1299       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1300     }
1301
1302     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1303     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1304       MVT VT = (MVT::SimpleValueType)i;
1305
1306       // Do not attempt to promote non-256-bit vectors
1307       if (!VT.is256BitVector())
1308         continue;
1309
1310       setOperationAction(ISD::AND,    VT, Promote);
1311       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1312       setOperationAction(ISD::OR,     VT, Promote);
1313       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1314       setOperationAction(ISD::XOR,    VT, Promote);
1315       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1316       setOperationAction(ISD::LOAD,   VT, Promote);
1317       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1318       setOperationAction(ISD::SELECT, VT, Promote);
1319       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1320     }
1321   }
1322
1323   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1324     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1325     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1326     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1327     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1328
1329     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1330     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1331     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1332
1333     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1334     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1335     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1336     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1337     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1338     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1339     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1340     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1342     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1343     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1344
1345     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1348     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1349     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1350     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1351
1352     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1353     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1354     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1355     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1356     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1357     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1358     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1359     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1360
1361     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1362     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1363     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1364     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1365     if (Subtarget->is64Bit()) {
1366       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1367       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1368       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1369       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1370     }
1371     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1372     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1373     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1374     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1376     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1377     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1379     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1380     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1381
1382     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1383     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1384     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1386     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1387     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1388     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1389     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1390     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1391     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1392     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1393     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1394     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1395
1396     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1397     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1398     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1399     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1400     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1401     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1402
1403     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1404     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1405
1406     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1407
1408     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1409     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1410     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1411     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1412     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1413     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1414     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1415     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1416     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1417
1418     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1419     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1420
1421     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1422     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1423
1424     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1425
1426     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1427     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1428
1429     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1430     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1431
1432     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1433     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1434
1435     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1436     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1437     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1438     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1439     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1440     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1441
1442     // Custom lower several nodes.
1443     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1444              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1445       MVT VT = (MVT::SimpleValueType)i;
1446
1447       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1448       // Extract subvector is special because the value type
1449       // (result) is 256/128-bit but the source is 512-bit wide.
1450       if (VT.is128BitVector() || VT.is256BitVector())
1451         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1452
1453       if (VT.getVectorElementType() == MVT::i1)
1454         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1455
1456       // Do not attempt to custom lower other non-512-bit vectors
1457       if (!VT.is512BitVector())
1458         continue;
1459
1460       if ( EltSize >= 32) {
1461         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1462         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1463         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1464         setOperationAction(ISD::VSELECT,             VT, Legal);
1465         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1466         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1467         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1468       }
1469     }
1470     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1471       MVT VT = (MVT::SimpleValueType)i;
1472
1473       // Do not attempt to promote non-256-bit vectors
1474       if (!VT.is512BitVector())
1475         continue;
1476
1477       setOperationAction(ISD::SELECT, VT, Promote);
1478       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1479     }
1480   }// has  AVX-512
1481
1482   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1483   // of this type with custom code.
1484   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1485            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1486     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1487                        Custom);
1488   }
1489
1490   // We want to custom lower some of our intrinsics.
1491   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1492   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1493   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1494   if (!Subtarget->is64Bit())
1495     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1496
1497   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1498   // handle type legalization for these operations here.
1499   //
1500   // FIXME: We really should do custom legalization for addition and
1501   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1502   // than generic legalization for 64-bit multiplication-with-overflow, though.
1503   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1504     // Add/Sub/Mul with overflow operations are custom lowered.
1505     MVT VT = IntVTs[i];
1506     setOperationAction(ISD::SADDO, VT, Custom);
1507     setOperationAction(ISD::UADDO, VT, Custom);
1508     setOperationAction(ISD::SSUBO, VT, Custom);
1509     setOperationAction(ISD::USUBO, VT, Custom);
1510     setOperationAction(ISD::SMULO, VT, Custom);
1511     setOperationAction(ISD::UMULO, VT, Custom);
1512   }
1513
1514   // There are no 8-bit 3-address imul/mul instructions
1515   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1516   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1517
1518   if (!Subtarget->is64Bit()) {
1519     // These libcalls are not available in 32-bit.
1520     setLibcallName(RTLIB::SHL_I128, nullptr);
1521     setLibcallName(RTLIB::SRL_I128, nullptr);
1522     setLibcallName(RTLIB::SRA_I128, nullptr);
1523   }
1524
1525   // Combine sin / cos into one node or libcall if possible.
1526   if (Subtarget->hasSinCos()) {
1527     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1528     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1529     if (Subtarget->isTargetDarwin()) {
1530       // For MacOSX, we don't want to the normal expansion of a libcall to
1531       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1532       // traffic.
1533       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1534       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1535     }
1536   }
1537
1538   if (Subtarget->isTargetWin64()) {
1539     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1540     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1541     setOperationAction(ISD::SREM, MVT::i128, Custom);
1542     setOperationAction(ISD::UREM, MVT::i128, Custom);
1543     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1544     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1545   }
1546
1547   // We have target-specific dag combine patterns for the following nodes:
1548   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1549   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1550   setTargetDAGCombine(ISD::VSELECT);
1551   setTargetDAGCombine(ISD::SELECT);
1552   setTargetDAGCombine(ISD::SHL);
1553   setTargetDAGCombine(ISD::SRA);
1554   setTargetDAGCombine(ISD::SRL);
1555   setTargetDAGCombine(ISD::OR);
1556   setTargetDAGCombine(ISD::AND);
1557   setTargetDAGCombine(ISD::ADD);
1558   setTargetDAGCombine(ISD::FADD);
1559   setTargetDAGCombine(ISD::FSUB);
1560   setTargetDAGCombine(ISD::FMA);
1561   setTargetDAGCombine(ISD::SUB);
1562   setTargetDAGCombine(ISD::LOAD);
1563   setTargetDAGCombine(ISD::STORE);
1564   setTargetDAGCombine(ISD::ZERO_EXTEND);
1565   setTargetDAGCombine(ISD::ANY_EXTEND);
1566   setTargetDAGCombine(ISD::SIGN_EXTEND);
1567   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1568   setTargetDAGCombine(ISD::TRUNCATE);
1569   setTargetDAGCombine(ISD::SINT_TO_FP);
1570   setTargetDAGCombine(ISD::SETCC);
1571   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1572   setTargetDAGCombine(ISD::BUILD_VECTOR);
1573   if (Subtarget->is64Bit())
1574     setTargetDAGCombine(ISD::MUL);
1575   setTargetDAGCombine(ISD::XOR);
1576
1577   computeRegisterProperties();
1578
1579   // On Darwin, -Os means optimize for size without hurting performance,
1580   // do not reduce the limit.
1581   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1582   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1583   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1584   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1585   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1586   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1587   setPrefLoopAlignment(4); // 2^4 bytes.
1588
1589   // Predictable cmov don't hurt on atom because it's in-order.
1590   PredictableSelectIsExpensive = !Subtarget->isAtom();
1591
1592   setPrefFunctionAlignment(4); // 2^4 bytes.
1593 }
1594
1595 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1596   if (!VT.isVector())
1597     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1598
1599   if (Subtarget->hasAVX512())
1600     switch(VT.getVectorNumElements()) {
1601     case  8: return MVT::v8i1;
1602     case 16: return MVT::v16i1;
1603   }
1604
1605   return VT.changeVectorElementTypeToInteger();
1606 }
1607
1608 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1609 /// the desired ByVal argument alignment.
1610 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1611   if (MaxAlign == 16)
1612     return;
1613   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1614     if (VTy->getBitWidth() == 128)
1615       MaxAlign = 16;
1616   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1617     unsigned EltAlign = 0;
1618     getMaxByValAlign(ATy->getElementType(), EltAlign);
1619     if (EltAlign > MaxAlign)
1620       MaxAlign = EltAlign;
1621   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1622     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1623       unsigned EltAlign = 0;
1624       getMaxByValAlign(STy->getElementType(i), EltAlign);
1625       if (EltAlign > MaxAlign)
1626         MaxAlign = EltAlign;
1627       if (MaxAlign == 16)
1628         break;
1629     }
1630   }
1631 }
1632
1633 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1634 /// function arguments in the caller parameter area. For X86, aggregates
1635 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1636 /// are at 4-byte boundaries.
1637 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1638   if (Subtarget->is64Bit()) {
1639     // Max of 8 and alignment of type.
1640     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1641     if (TyAlign > 8)
1642       return TyAlign;
1643     return 8;
1644   }
1645
1646   unsigned Align = 4;
1647   if (Subtarget->hasSSE1())
1648     getMaxByValAlign(Ty, Align);
1649   return Align;
1650 }
1651
1652 /// getOptimalMemOpType - Returns the target specific optimal type for load
1653 /// and store operations as a result of memset, memcpy, and memmove
1654 /// lowering. If DstAlign is zero that means it's safe to destination
1655 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1656 /// means there isn't a need to check it against alignment requirement,
1657 /// probably because the source does not need to be loaded. If 'IsMemset' is
1658 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1659 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1660 /// source is constant so it does not need to be loaded.
1661 /// It returns EVT::Other if the type should be determined using generic
1662 /// target-independent logic.
1663 EVT
1664 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1665                                        unsigned DstAlign, unsigned SrcAlign,
1666                                        bool IsMemset, bool ZeroMemset,
1667                                        bool MemcpyStrSrc,
1668                                        MachineFunction &MF) const {
1669   const Function *F = MF.getFunction();
1670   if ((!IsMemset || ZeroMemset) &&
1671       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1672                                        Attribute::NoImplicitFloat)) {
1673     if (Size >= 16 &&
1674         (Subtarget->isUnalignedMemAccessFast() ||
1675          ((DstAlign == 0 || DstAlign >= 16) &&
1676           (SrcAlign == 0 || SrcAlign >= 16)))) {
1677       if (Size >= 32) {
1678         if (Subtarget->hasInt256())
1679           return MVT::v8i32;
1680         if (Subtarget->hasFp256())
1681           return MVT::v8f32;
1682       }
1683       if (Subtarget->hasSSE2())
1684         return MVT::v4i32;
1685       if (Subtarget->hasSSE1())
1686         return MVT::v4f32;
1687     } else if (!MemcpyStrSrc && Size >= 8 &&
1688                !Subtarget->is64Bit() &&
1689                Subtarget->hasSSE2()) {
1690       // Do not use f64 to lower memcpy if source is string constant. It's
1691       // better to use i32 to avoid the loads.
1692       return MVT::f64;
1693     }
1694   }
1695   if (Subtarget->is64Bit() && Size >= 8)
1696     return MVT::i64;
1697   return MVT::i32;
1698 }
1699
1700 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1701   if (VT == MVT::f32)
1702     return X86ScalarSSEf32;
1703   else if (VT == MVT::f64)
1704     return X86ScalarSSEf64;
1705   return true;
1706 }
1707
1708 bool
1709 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1710                                                  unsigned,
1711                                                  bool *Fast) const {
1712   if (Fast)
1713     *Fast = Subtarget->isUnalignedMemAccessFast();
1714   return true;
1715 }
1716
1717 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1718 /// current function.  The returned value is a member of the
1719 /// MachineJumpTableInfo::JTEntryKind enum.
1720 unsigned X86TargetLowering::getJumpTableEncoding() const {
1721   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1722   // symbol.
1723   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1724       Subtarget->isPICStyleGOT())
1725     return MachineJumpTableInfo::EK_Custom32;
1726
1727   // Otherwise, use the normal jump table encoding heuristics.
1728   return TargetLowering::getJumpTableEncoding();
1729 }
1730
1731 const MCExpr *
1732 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1733                                              const MachineBasicBlock *MBB,
1734                                              unsigned uid,MCContext &Ctx) const{
1735   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1736          Subtarget->isPICStyleGOT());
1737   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1738   // entries.
1739   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1740                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1741 }
1742
1743 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1744 /// jumptable.
1745 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1746                                                     SelectionDAG &DAG) const {
1747   if (!Subtarget->is64Bit())
1748     // This doesn't have SDLoc associated with it, but is not really the
1749     // same as a Register.
1750     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1751   return Table;
1752 }
1753
1754 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1755 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1756 /// MCExpr.
1757 const MCExpr *X86TargetLowering::
1758 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1759                              MCContext &Ctx) const {
1760   // X86-64 uses RIP relative addressing based on the jump table label.
1761   if (Subtarget->isPICStyleRIPRel())
1762     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1763
1764   // Otherwise, the reference is relative to the PIC base.
1765   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1766 }
1767
1768 // FIXME: Why this routine is here? Move to RegInfo!
1769 std::pair<const TargetRegisterClass*, uint8_t>
1770 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1771   const TargetRegisterClass *RRC = nullptr;
1772   uint8_t Cost = 1;
1773   switch (VT.SimpleTy) {
1774   default:
1775     return TargetLowering::findRepresentativeClass(VT);
1776   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1777     RRC = Subtarget->is64Bit() ?
1778       (const TargetRegisterClass*)&X86::GR64RegClass :
1779       (const TargetRegisterClass*)&X86::GR32RegClass;
1780     break;
1781   case MVT::x86mmx:
1782     RRC = &X86::VR64RegClass;
1783     break;
1784   case MVT::f32: case MVT::f64:
1785   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1786   case MVT::v4f32: case MVT::v2f64:
1787   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1788   case MVT::v4f64:
1789     RRC = &X86::VR128RegClass;
1790     break;
1791   }
1792   return std::make_pair(RRC, Cost);
1793 }
1794
1795 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1796                                                unsigned &Offset) const {
1797   if (!Subtarget->isTargetLinux())
1798     return false;
1799
1800   if (Subtarget->is64Bit()) {
1801     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1802     Offset = 0x28;
1803     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1804       AddressSpace = 256;
1805     else
1806       AddressSpace = 257;
1807   } else {
1808     // %gs:0x14 on i386
1809     Offset = 0x14;
1810     AddressSpace = 256;
1811   }
1812   return true;
1813 }
1814
1815 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1816                                             unsigned DestAS) const {
1817   assert(SrcAS != DestAS && "Expected different address spaces!");
1818
1819   return SrcAS < 256 && DestAS < 256;
1820 }
1821
1822 //===----------------------------------------------------------------------===//
1823 //               Return Value Calling Convention Implementation
1824 //===----------------------------------------------------------------------===//
1825
1826 #include "X86GenCallingConv.inc"
1827
1828 bool
1829 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1830                                   MachineFunction &MF, bool isVarArg,
1831                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1832                         LLVMContext &Context) const {
1833   SmallVector<CCValAssign, 16> RVLocs;
1834   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1835                  RVLocs, Context);
1836   return CCInfo.CheckReturn(Outs, RetCC_X86);
1837 }
1838
1839 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1840   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1841   return ScratchRegs;
1842 }
1843
1844 SDValue
1845 X86TargetLowering::LowerReturn(SDValue Chain,
1846                                CallingConv::ID CallConv, bool isVarArg,
1847                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1848                                const SmallVectorImpl<SDValue> &OutVals,
1849                                SDLoc dl, SelectionDAG &DAG) const {
1850   MachineFunction &MF = DAG.getMachineFunction();
1851   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1852
1853   SmallVector<CCValAssign, 16> RVLocs;
1854   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1855                  RVLocs, *DAG.getContext());
1856   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1857
1858   SDValue Flag;
1859   SmallVector<SDValue, 6> RetOps;
1860   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1861   // Operand #1 = Bytes To Pop
1862   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1863                    MVT::i16));
1864
1865   // Copy the result values into the output registers.
1866   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1867     CCValAssign &VA = RVLocs[i];
1868     assert(VA.isRegLoc() && "Can only return in registers!");
1869     SDValue ValToCopy = OutVals[i];
1870     EVT ValVT = ValToCopy.getValueType();
1871
1872     // Promote values to the appropriate types
1873     if (VA.getLocInfo() == CCValAssign::SExt)
1874       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1875     else if (VA.getLocInfo() == CCValAssign::ZExt)
1876       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1877     else if (VA.getLocInfo() == CCValAssign::AExt)
1878       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1879     else if (VA.getLocInfo() == CCValAssign::BCvt)
1880       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1881
1882     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1883            "Unexpected FP-extend for return value.");  
1884
1885     // If this is x86-64, and we disabled SSE, we can't return FP values,
1886     // or SSE or MMX vectors.
1887     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1888          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1889           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1890       report_fatal_error("SSE register return with SSE disabled");
1891     }
1892     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1893     // llvm-gcc has never done it right and no one has noticed, so this
1894     // should be OK for now.
1895     if (ValVT == MVT::f64 &&
1896         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1897       report_fatal_error("SSE2 register return with SSE2 disabled");
1898
1899     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1900     // the RET instruction and handled by the FP Stackifier.
1901     if (VA.getLocReg() == X86::ST0 ||
1902         VA.getLocReg() == X86::ST1) {
1903       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1904       // change the value to the FP stack register class.
1905       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1906         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1907       RetOps.push_back(ValToCopy);
1908       // Don't emit a copytoreg.
1909       continue;
1910     }
1911
1912     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1913     // which is returned in RAX / RDX.
1914     if (Subtarget->is64Bit()) {
1915       if (ValVT == MVT::x86mmx) {
1916         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1917           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1918           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1919                                   ValToCopy);
1920           // If we don't have SSE2 available, convert to v4f32 so the generated
1921           // register is legal.
1922           if (!Subtarget->hasSSE2())
1923             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1924         }
1925       }
1926     }
1927
1928     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1929     Flag = Chain.getValue(1);
1930     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1931   }
1932
1933   // The x86-64 ABIs require that for returning structs by value we copy
1934   // the sret argument into %rax/%eax (depending on ABI) for the return.
1935   // Win32 requires us to put the sret argument to %eax as well.
1936   // We saved the argument into a virtual register in the entry block,
1937   // so now we copy the value out and into %rax/%eax.
1938   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1939       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1940     MachineFunction &MF = DAG.getMachineFunction();
1941     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1942     unsigned Reg = FuncInfo->getSRetReturnReg();
1943     assert(Reg &&
1944            "SRetReturnReg should have been set in LowerFormalArguments().");
1945     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1946
1947     unsigned RetValReg
1948         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1949           X86::RAX : X86::EAX;
1950     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1951     Flag = Chain.getValue(1);
1952
1953     // RAX/EAX now acts like a return value.
1954     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1955   }
1956
1957   RetOps[0] = Chain;  // Update chain.
1958
1959   // Add the flag if we have it.
1960   if (Flag.getNode())
1961     RetOps.push_back(Flag);
1962
1963   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1964 }
1965
1966 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1967   if (N->getNumValues() != 1)
1968     return false;
1969   if (!N->hasNUsesOfValue(1, 0))
1970     return false;
1971
1972   SDValue TCChain = Chain;
1973   SDNode *Copy = *N->use_begin();
1974   if (Copy->getOpcode() == ISD::CopyToReg) {
1975     // If the copy has a glue operand, we conservatively assume it isn't safe to
1976     // perform a tail call.
1977     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1978       return false;
1979     TCChain = Copy->getOperand(0);
1980   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1981     return false;
1982
1983   bool HasRet = false;
1984   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1985        UI != UE; ++UI) {
1986     if (UI->getOpcode() != X86ISD::RET_FLAG)
1987       return false;
1988     HasRet = true;
1989   }
1990
1991   if (!HasRet)
1992     return false;
1993
1994   Chain = TCChain;
1995   return true;
1996 }
1997
1998 MVT
1999 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2000                                             ISD::NodeType ExtendKind) const {
2001   MVT ReturnMVT;
2002   // TODO: Is this also valid on 32-bit?
2003   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2004     ReturnMVT = MVT::i8;
2005   else
2006     ReturnMVT = MVT::i32;
2007
2008   MVT MinVT = getRegisterType(ReturnMVT);
2009   return VT.bitsLT(MinVT) ? MinVT : VT;
2010 }
2011
2012 /// LowerCallResult - Lower the result values of a call into the
2013 /// appropriate copies out of appropriate physical registers.
2014 ///
2015 SDValue
2016 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2017                                    CallingConv::ID CallConv, bool isVarArg,
2018                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2019                                    SDLoc dl, SelectionDAG &DAG,
2020                                    SmallVectorImpl<SDValue> &InVals) const {
2021
2022   // Assign locations to each value returned by this call.
2023   SmallVector<CCValAssign, 16> RVLocs;
2024   bool Is64Bit = Subtarget->is64Bit();
2025   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2026                  DAG.getTarget(), RVLocs, *DAG.getContext());
2027   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2028
2029   // Copy all of the result registers out of their specified physreg.
2030   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2031     CCValAssign &VA = RVLocs[i];
2032     EVT CopyVT = VA.getValVT();
2033
2034     // If this is x86-64, and we disabled SSE, we can't return FP values
2035     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2036         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2037       report_fatal_error("SSE register return with SSE disabled");
2038     }
2039
2040     SDValue Val;
2041
2042     // If this is a call to a function that returns an fp value on the floating
2043     // point stack, we must guarantee the value is popped from the stack, so
2044     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2045     // if the return value is not used. We use the FpPOP_RETVAL instruction
2046     // instead.
2047     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2048       // If we prefer to use the value in xmm registers, copy it out as f80 and
2049       // use a truncate to move it from fp stack reg to xmm reg.
2050       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2051       SDValue Ops[] = { Chain, InFlag };
2052       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2053                                          MVT::Other, MVT::Glue, Ops), 1);
2054       Val = Chain.getValue(0);
2055
2056       // Round the f80 to the right size, which also moves it to the appropriate
2057       // xmm register.
2058       if (CopyVT != VA.getValVT())
2059         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2060                           // This truncation won't change the value.
2061                           DAG.getIntPtrConstant(1));
2062     } else {
2063       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2064                                  CopyVT, InFlag).getValue(1);
2065       Val = Chain.getValue(0);
2066     }
2067     InFlag = Chain.getValue(2);
2068     InVals.push_back(Val);
2069   }
2070
2071   return Chain;
2072 }
2073
2074 //===----------------------------------------------------------------------===//
2075 //                C & StdCall & Fast Calling Convention implementation
2076 //===----------------------------------------------------------------------===//
2077 //  StdCall calling convention seems to be standard for many Windows' API
2078 //  routines and around. It differs from C calling convention just a little:
2079 //  callee should clean up the stack, not caller. Symbols should be also
2080 //  decorated in some fancy way :) It doesn't support any vector arguments.
2081 //  For info on fast calling convention see Fast Calling Convention (tail call)
2082 //  implementation LowerX86_32FastCCCallTo.
2083
2084 /// CallIsStructReturn - Determines whether a call uses struct return
2085 /// semantics.
2086 enum StructReturnType {
2087   NotStructReturn,
2088   RegStructReturn,
2089   StackStructReturn
2090 };
2091 static StructReturnType
2092 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2093   if (Outs.empty())
2094     return NotStructReturn;
2095
2096   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2097   if (!Flags.isSRet())
2098     return NotStructReturn;
2099   if (Flags.isInReg())
2100     return RegStructReturn;
2101   return StackStructReturn;
2102 }
2103
2104 /// ArgsAreStructReturn - Determines whether a function uses struct
2105 /// return semantics.
2106 static StructReturnType
2107 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2108   if (Ins.empty())
2109     return NotStructReturn;
2110
2111   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2112   if (!Flags.isSRet())
2113     return NotStructReturn;
2114   if (Flags.isInReg())
2115     return RegStructReturn;
2116   return StackStructReturn;
2117 }
2118
2119 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2120 /// by "Src" to address "Dst" with size and alignment information specified by
2121 /// the specific parameter attribute. The copy will be passed as a byval
2122 /// function parameter.
2123 static SDValue
2124 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2125                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2126                           SDLoc dl) {
2127   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2128
2129   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2130                        /*isVolatile*/false, /*AlwaysInline=*/true,
2131                        MachinePointerInfo(), MachinePointerInfo());
2132 }
2133
2134 /// IsTailCallConvention - Return true if the calling convention is one that
2135 /// supports tail call optimization.
2136 static bool IsTailCallConvention(CallingConv::ID CC) {
2137   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2138           CC == CallingConv::HiPE);
2139 }
2140
2141 /// \brief Return true if the calling convention is a C calling convention.
2142 static bool IsCCallConvention(CallingConv::ID CC) {
2143   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2144           CC == CallingConv::X86_64_SysV);
2145 }
2146
2147 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2148   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2149     return false;
2150
2151   CallSite CS(CI);
2152   CallingConv::ID CalleeCC = CS.getCallingConv();
2153   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2154     return false;
2155
2156   return true;
2157 }
2158
2159 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2160 /// a tailcall target by changing its ABI.
2161 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2162                                    bool GuaranteedTailCallOpt) {
2163   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2164 }
2165
2166 SDValue
2167 X86TargetLowering::LowerMemArgument(SDValue Chain,
2168                                     CallingConv::ID CallConv,
2169                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2170                                     SDLoc dl, SelectionDAG &DAG,
2171                                     const CCValAssign &VA,
2172                                     MachineFrameInfo *MFI,
2173                                     unsigned i) const {
2174   // Create the nodes corresponding to a load from this parameter slot.
2175   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2176   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2177       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2178   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2179   EVT ValVT;
2180
2181   // If value is passed by pointer we have address passed instead of the value
2182   // itself.
2183   if (VA.getLocInfo() == CCValAssign::Indirect)
2184     ValVT = VA.getLocVT();
2185   else
2186     ValVT = VA.getValVT();
2187
2188   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2189   // changed with more analysis.
2190   // In case of tail call optimization mark all arguments mutable. Since they
2191   // could be overwritten by lowering of arguments in case of a tail call.
2192   if (Flags.isByVal()) {
2193     unsigned Bytes = Flags.getByValSize();
2194     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2195     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2196     return DAG.getFrameIndex(FI, getPointerTy());
2197   } else {
2198     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2199                                     VA.getLocMemOffset(), isImmutable);
2200     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2201     return DAG.getLoad(ValVT, dl, Chain, FIN,
2202                        MachinePointerInfo::getFixedStack(FI),
2203                        false, false, false, 0);
2204   }
2205 }
2206
2207 SDValue
2208 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2209                                         CallingConv::ID CallConv,
2210                                         bool isVarArg,
2211                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2212                                         SDLoc dl,
2213                                         SelectionDAG &DAG,
2214                                         SmallVectorImpl<SDValue> &InVals)
2215                                           const {
2216   MachineFunction &MF = DAG.getMachineFunction();
2217   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2218
2219   const Function* Fn = MF.getFunction();
2220   if (Fn->hasExternalLinkage() &&
2221       Subtarget->isTargetCygMing() &&
2222       Fn->getName() == "main")
2223     FuncInfo->setForceFramePointer(true);
2224
2225   MachineFrameInfo *MFI = MF.getFrameInfo();
2226   bool Is64Bit = Subtarget->is64Bit();
2227   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2228
2229   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2230          "Var args not supported with calling convention fastcc, ghc or hipe");
2231
2232   // Assign locations to all of the incoming arguments.
2233   SmallVector<CCValAssign, 16> ArgLocs;
2234   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2235                  ArgLocs, *DAG.getContext());
2236
2237   // Allocate shadow area for Win64
2238   if (IsWin64)
2239     CCInfo.AllocateStack(32, 8);
2240
2241   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2242
2243   unsigned LastVal = ~0U;
2244   SDValue ArgValue;
2245   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2246     CCValAssign &VA = ArgLocs[i];
2247     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2248     // places.
2249     assert(VA.getValNo() != LastVal &&
2250            "Don't support value assigned to multiple locs yet");
2251     (void)LastVal;
2252     LastVal = VA.getValNo();
2253
2254     if (VA.isRegLoc()) {
2255       EVT RegVT = VA.getLocVT();
2256       const TargetRegisterClass *RC;
2257       if (RegVT == MVT::i32)
2258         RC = &X86::GR32RegClass;
2259       else if (Is64Bit && RegVT == MVT::i64)
2260         RC = &X86::GR64RegClass;
2261       else if (RegVT == MVT::f32)
2262         RC = &X86::FR32RegClass;
2263       else if (RegVT == MVT::f64)
2264         RC = &X86::FR64RegClass;
2265       else if (RegVT.is512BitVector())
2266         RC = &X86::VR512RegClass;
2267       else if (RegVT.is256BitVector())
2268         RC = &X86::VR256RegClass;
2269       else if (RegVT.is128BitVector())
2270         RC = &X86::VR128RegClass;
2271       else if (RegVT == MVT::x86mmx)
2272         RC = &X86::VR64RegClass;
2273       else if (RegVT == MVT::i1)
2274         RC = &X86::VK1RegClass;
2275       else if (RegVT == MVT::v8i1)
2276         RC = &X86::VK8RegClass;
2277       else if (RegVT == MVT::v16i1)
2278         RC = &X86::VK16RegClass;
2279       else
2280         llvm_unreachable("Unknown argument type!");
2281
2282       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2283       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2284
2285       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2286       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2287       // right size.
2288       if (VA.getLocInfo() == CCValAssign::SExt)
2289         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2290                                DAG.getValueType(VA.getValVT()));
2291       else if (VA.getLocInfo() == CCValAssign::ZExt)
2292         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2293                                DAG.getValueType(VA.getValVT()));
2294       else if (VA.getLocInfo() == CCValAssign::BCvt)
2295         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2296
2297       if (VA.isExtInLoc()) {
2298         // Handle MMX values passed in XMM regs.
2299         if (RegVT.isVector())
2300           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2301         else
2302           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2303       }
2304     } else {
2305       assert(VA.isMemLoc());
2306       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2307     }
2308
2309     // If value is passed via pointer - do a load.
2310     if (VA.getLocInfo() == CCValAssign::Indirect)
2311       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2312                              MachinePointerInfo(), false, false, false, 0);
2313
2314     InVals.push_back(ArgValue);
2315   }
2316
2317   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2318     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2319       // The x86-64 ABIs require that for returning structs by value we copy
2320       // the sret argument into %rax/%eax (depending on ABI) for the return.
2321       // Win32 requires us to put the sret argument to %eax as well.
2322       // Save the argument into a virtual register so that we can access it
2323       // from the return points.
2324       if (Ins[i].Flags.isSRet()) {
2325         unsigned Reg = FuncInfo->getSRetReturnReg();
2326         if (!Reg) {
2327           MVT PtrTy = getPointerTy();
2328           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2329           FuncInfo->setSRetReturnReg(Reg);
2330         }
2331         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2332         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2333         break;
2334       }
2335     }
2336   }
2337
2338   unsigned StackSize = CCInfo.getNextStackOffset();
2339   // Align stack specially for tail calls.
2340   if (FuncIsMadeTailCallSafe(CallConv,
2341                              MF.getTarget().Options.GuaranteedTailCallOpt))
2342     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2343
2344   // If the function takes variable number of arguments, make a frame index for
2345   // the start of the first vararg value... for expansion of llvm.va_start.
2346   if (isVarArg) {
2347     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2348                     CallConv != CallingConv::X86_ThisCall)) {
2349       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2350     }
2351     if (Is64Bit) {
2352       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2353
2354       // FIXME: We should really autogenerate these arrays
2355       static const MCPhysReg GPR64ArgRegsWin64[] = {
2356         X86::RCX, X86::RDX, X86::R8,  X86::R9
2357       };
2358       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2359         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2360       };
2361       static const MCPhysReg XMMArgRegs64Bit[] = {
2362         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2363         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2364       };
2365       const MCPhysReg *GPR64ArgRegs;
2366       unsigned NumXMMRegs = 0;
2367
2368       if (IsWin64) {
2369         // The XMM registers which might contain var arg parameters are shadowed
2370         // in their paired GPR.  So we only need to save the GPR to their home
2371         // slots.
2372         TotalNumIntRegs = 4;
2373         GPR64ArgRegs = GPR64ArgRegsWin64;
2374       } else {
2375         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2376         GPR64ArgRegs = GPR64ArgRegs64Bit;
2377
2378         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2379                                                 TotalNumXMMRegs);
2380       }
2381       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2382                                                        TotalNumIntRegs);
2383
2384       bool NoImplicitFloatOps = Fn->getAttributes().
2385         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2386       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2387              "SSE register cannot be used when SSE is disabled!");
2388       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2389                NoImplicitFloatOps) &&
2390              "SSE register cannot be used when SSE is disabled!");
2391       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2392           !Subtarget->hasSSE1())
2393         // Kernel mode asks for SSE to be disabled, so don't push them
2394         // on the stack.
2395         TotalNumXMMRegs = 0;
2396
2397       if (IsWin64) {
2398         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2399         // Get to the caller-allocated home save location.  Add 8 to account
2400         // for the return address.
2401         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2402         FuncInfo->setRegSaveFrameIndex(
2403           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2404         // Fixup to set vararg frame on shadow area (4 x i64).
2405         if (NumIntRegs < 4)
2406           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2407       } else {
2408         // For X86-64, if there are vararg parameters that are passed via
2409         // registers, then we must store them to their spots on the stack so
2410         // they may be loaded by deferencing the result of va_next.
2411         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2412         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2413         FuncInfo->setRegSaveFrameIndex(
2414           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2415                                false));
2416       }
2417
2418       // Store the integer parameter registers.
2419       SmallVector<SDValue, 8> MemOps;
2420       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2421                                         getPointerTy());
2422       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2423       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2424         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2425                                   DAG.getIntPtrConstant(Offset));
2426         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2427                                      &X86::GR64RegClass);
2428         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2429         SDValue Store =
2430           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2431                        MachinePointerInfo::getFixedStack(
2432                          FuncInfo->getRegSaveFrameIndex(), Offset),
2433                        false, false, 0);
2434         MemOps.push_back(Store);
2435         Offset += 8;
2436       }
2437
2438       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2439         // Now store the XMM (fp + vector) parameter registers.
2440         SmallVector<SDValue, 11> SaveXMMOps;
2441         SaveXMMOps.push_back(Chain);
2442
2443         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2444         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2445         SaveXMMOps.push_back(ALVal);
2446
2447         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2448                                FuncInfo->getRegSaveFrameIndex()));
2449         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2450                                FuncInfo->getVarArgsFPOffset()));
2451
2452         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2453           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2454                                        &X86::VR128RegClass);
2455           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2456           SaveXMMOps.push_back(Val);
2457         }
2458         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2459                                      MVT::Other, SaveXMMOps));
2460       }
2461
2462       if (!MemOps.empty())
2463         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2464     }
2465   }
2466
2467   // Some CCs need callee pop.
2468   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2469                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2470     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2471   } else {
2472     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2473     // If this is an sret function, the return should pop the hidden pointer.
2474     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2475         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2476         argsAreStructReturn(Ins) == StackStructReturn)
2477       FuncInfo->setBytesToPopOnReturn(4);
2478   }
2479
2480   if (!Is64Bit) {
2481     // RegSaveFrameIndex is X86-64 only.
2482     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2483     if (CallConv == CallingConv::X86_FastCall ||
2484         CallConv == CallingConv::X86_ThisCall)
2485       // fastcc functions can't have varargs.
2486       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2487   }
2488
2489   FuncInfo->setArgumentStackSize(StackSize);
2490
2491   return Chain;
2492 }
2493
2494 SDValue
2495 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2496                                     SDValue StackPtr, SDValue Arg,
2497                                     SDLoc dl, SelectionDAG &DAG,
2498                                     const CCValAssign &VA,
2499                                     ISD::ArgFlagsTy Flags) const {
2500   unsigned LocMemOffset = VA.getLocMemOffset();
2501   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2502   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2503   if (Flags.isByVal())
2504     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2505
2506   return DAG.getStore(Chain, dl, Arg, PtrOff,
2507                       MachinePointerInfo::getStack(LocMemOffset),
2508                       false, false, 0);
2509 }
2510
2511 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2512 /// optimization is performed and it is required.
2513 SDValue
2514 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2515                                            SDValue &OutRetAddr, SDValue Chain,
2516                                            bool IsTailCall, bool Is64Bit,
2517                                            int FPDiff, SDLoc dl) const {
2518   // Adjust the Return address stack slot.
2519   EVT VT = getPointerTy();
2520   OutRetAddr = getReturnAddressFrameIndex(DAG);
2521
2522   // Load the "old" Return address.
2523   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2524                            false, false, false, 0);
2525   return SDValue(OutRetAddr.getNode(), 1);
2526 }
2527
2528 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2529 /// optimization is performed and it is required (FPDiff!=0).
2530 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2531                                         SDValue Chain, SDValue RetAddrFrIdx,
2532                                         EVT PtrVT, unsigned SlotSize,
2533                                         int FPDiff, SDLoc dl) {
2534   // Store the return address to the appropriate stack slot.
2535   if (!FPDiff) return Chain;
2536   // Calculate the new stack slot for the return address.
2537   int NewReturnAddrFI =
2538     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2539                                          false);
2540   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2541   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2542                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2543                        false, false, 0);
2544   return Chain;
2545 }
2546
2547 SDValue
2548 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2549                              SmallVectorImpl<SDValue> &InVals) const {
2550   SelectionDAG &DAG                     = CLI.DAG;
2551   SDLoc &dl                             = CLI.DL;
2552   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2553   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2554   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2555   SDValue Chain                         = CLI.Chain;
2556   SDValue Callee                        = CLI.Callee;
2557   CallingConv::ID CallConv              = CLI.CallConv;
2558   bool &isTailCall                      = CLI.IsTailCall;
2559   bool isVarArg                         = CLI.IsVarArg;
2560
2561   MachineFunction &MF = DAG.getMachineFunction();
2562   bool Is64Bit        = Subtarget->is64Bit();
2563   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2564   StructReturnType SR = callIsStructReturn(Outs);
2565   bool IsSibcall      = false;
2566
2567   if (MF.getTarget().Options.DisableTailCalls)
2568     isTailCall = false;
2569
2570   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2571   if (IsMustTail) {
2572     // Force this to be a tail call.  The verifier rules are enough to ensure
2573     // that we can lower this successfully without moving the return address
2574     // around.
2575     isTailCall = true;
2576   } else if (isTailCall) {
2577     // Check if it's really possible to do a tail call.
2578     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2579                     isVarArg, SR != NotStructReturn,
2580                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2581                     Outs, OutVals, Ins, DAG);
2582
2583     // Sibcalls are automatically detected tailcalls which do not require
2584     // ABI changes.
2585     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2586       IsSibcall = true;
2587
2588     if (isTailCall)
2589       ++NumTailCalls;
2590   }
2591
2592   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2593          "Var args not supported with calling convention fastcc, ghc or hipe");
2594
2595   // Analyze operands of the call, assigning locations to each operand.
2596   SmallVector<CCValAssign, 16> ArgLocs;
2597   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2598                  ArgLocs, *DAG.getContext());
2599
2600   // Allocate shadow area for Win64
2601   if (IsWin64)
2602     CCInfo.AllocateStack(32, 8);
2603
2604   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2605
2606   // Get a count of how many bytes are to be pushed on the stack.
2607   unsigned NumBytes = CCInfo.getNextStackOffset();
2608   if (IsSibcall)
2609     // This is a sibcall. The memory operands are available in caller's
2610     // own caller's stack.
2611     NumBytes = 0;
2612   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2613            IsTailCallConvention(CallConv))
2614     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2615
2616   int FPDiff = 0;
2617   if (isTailCall && !IsSibcall && !IsMustTail) {
2618     // Lower arguments at fp - stackoffset + fpdiff.
2619     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2620     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2621
2622     FPDiff = NumBytesCallerPushed - NumBytes;
2623
2624     // Set the delta of movement of the returnaddr stackslot.
2625     // But only set if delta is greater than previous delta.
2626     if (FPDiff < X86Info->getTCReturnAddrDelta())
2627       X86Info->setTCReturnAddrDelta(FPDiff);
2628   }
2629
2630   unsigned NumBytesToPush = NumBytes;
2631   unsigned NumBytesToPop = NumBytes;
2632
2633   // If we have an inalloca argument, all stack space has already been allocated
2634   // for us and be right at the top of the stack.  We don't support multiple
2635   // arguments passed in memory when using inalloca.
2636   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2637     NumBytesToPush = 0;
2638     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2639            "an inalloca argument must be the only memory argument");
2640   }
2641
2642   if (!IsSibcall)
2643     Chain = DAG.getCALLSEQ_START(
2644         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2645
2646   SDValue RetAddrFrIdx;
2647   // Load return address for tail calls.
2648   if (isTailCall && FPDiff)
2649     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2650                                     Is64Bit, FPDiff, dl);
2651
2652   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2653   SmallVector<SDValue, 8> MemOpChains;
2654   SDValue StackPtr;
2655
2656   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2657   // of tail call optimization arguments are handle later.
2658   const X86RegisterInfo *RegInfo =
2659     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2660   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2661     // Skip inalloca arguments, they have already been written.
2662     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2663     if (Flags.isInAlloca())
2664       continue;
2665
2666     CCValAssign &VA = ArgLocs[i];
2667     EVT RegVT = VA.getLocVT();
2668     SDValue Arg = OutVals[i];
2669     bool isByVal = Flags.isByVal();
2670
2671     // Promote the value if needed.
2672     switch (VA.getLocInfo()) {
2673     default: llvm_unreachable("Unknown loc info!");
2674     case CCValAssign::Full: break;
2675     case CCValAssign::SExt:
2676       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2677       break;
2678     case CCValAssign::ZExt:
2679       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2680       break;
2681     case CCValAssign::AExt:
2682       if (RegVT.is128BitVector()) {
2683         // Special case: passing MMX values in XMM registers.
2684         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2685         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2686         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2687       } else
2688         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2689       break;
2690     case CCValAssign::BCvt:
2691       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2692       break;
2693     case CCValAssign::Indirect: {
2694       // Store the argument.
2695       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2696       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2697       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2698                            MachinePointerInfo::getFixedStack(FI),
2699                            false, false, 0);
2700       Arg = SpillSlot;
2701       break;
2702     }
2703     }
2704
2705     if (VA.isRegLoc()) {
2706       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2707       if (isVarArg && IsWin64) {
2708         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2709         // shadow reg if callee is a varargs function.
2710         unsigned ShadowReg = 0;
2711         switch (VA.getLocReg()) {
2712         case X86::XMM0: ShadowReg = X86::RCX; break;
2713         case X86::XMM1: ShadowReg = X86::RDX; break;
2714         case X86::XMM2: ShadowReg = X86::R8; break;
2715         case X86::XMM3: ShadowReg = X86::R9; break;
2716         }
2717         if (ShadowReg)
2718           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2719       }
2720     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2721       assert(VA.isMemLoc());
2722       if (!StackPtr.getNode())
2723         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2724                                       getPointerTy());
2725       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2726                                              dl, DAG, VA, Flags));
2727     }
2728   }
2729
2730   if (!MemOpChains.empty())
2731     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2732
2733   if (Subtarget->isPICStyleGOT()) {
2734     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2735     // GOT pointer.
2736     if (!isTailCall) {
2737       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2738                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2739     } else {
2740       // If we are tail calling and generating PIC/GOT style code load the
2741       // address of the callee into ECX. The value in ecx is used as target of
2742       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2743       // for tail calls on PIC/GOT architectures. Normally we would just put the
2744       // address of GOT into ebx and then call target@PLT. But for tail calls
2745       // ebx would be restored (since ebx is callee saved) before jumping to the
2746       // target@PLT.
2747
2748       // Note: The actual moving to ECX is done further down.
2749       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2750       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2751           !G->getGlobal()->hasProtectedVisibility())
2752         Callee = LowerGlobalAddress(Callee, DAG);
2753       else if (isa<ExternalSymbolSDNode>(Callee))
2754         Callee = LowerExternalSymbol(Callee, DAG);
2755     }
2756   }
2757
2758   if (Is64Bit && isVarArg && !IsWin64) {
2759     // From AMD64 ABI document:
2760     // For calls that may call functions that use varargs or stdargs
2761     // (prototype-less calls or calls to functions containing ellipsis (...) in
2762     // the declaration) %al is used as hidden argument to specify the number
2763     // of SSE registers used. The contents of %al do not need to match exactly
2764     // the number of registers, but must be an ubound on the number of SSE
2765     // registers used and is in the range 0 - 8 inclusive.
2766
2767     // Count the number of XMM registers allocated.
2768     static const MCPhysReg XMMArgRegs[] = {
2769       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2770       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2771     };
2772     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2773     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2774            && "SSE registers cannot be used when SSE is disabled");
2775
2776     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2777                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2778   }
2779
2780   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2781   // don't need this because the eligibility check rejects calls that require
2782   // shuffling arguments passed in memory.
2783   if (!IsSibcall && isTailCall) {
2784     // Force all the incoming stack arguments to be loaded from the stack
2785     // before any new outgoing arguments are stored to the stack, because the
2786     // outgoing stack slots may alias the incoming argument stack slots, and
2787     // the alias isn't otherwise explicit. This is slightly more conservative
2788     // than necessary, because it means that each store effectively depends
2789     // on every argument instead of just those arguments it would clobber.
2790     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2791
2792     SmallVector<SDValue, 8> MemOpChains2;
2793     SDValue FIN;
2794     int FI = 0;
2795     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2796       CCValAssign &VA = ArgLocs[i];
2797       if (VA.isRegLoc())
2798         continue;
2799       assert(VA.isMemLoc());
2800       SDValue Arg = OutVals[i];
2801       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2802       // Skip inalloca arguments.  They don't require any work.
2803       if (Flags.isInAlloca())
2804         continue;
2805       // Create frame index.
2806       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2807       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2808       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2809       FIN = DAG.getFrameIndex(FI, getPointerTy());
2810
2811       if (Flags.isByVal()) {
2812         // Copy relative to framepointer.
2813         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2814         if (!StackPtr.getNode())
2815           StackPtr = DAG.getCopyFromReg(Chain, dl,
2816                                         RegInfo->getStackRegister(),
2817                                         getPointerTy());
2818         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2819
2820         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2821                                                          ArgChain,
2822                                                          Flags, DAG, dl));
2823       } else {
2824         // Store relative to framepointer.
2825         MemOpChains2.push_back(
2826           DAG.getStore(ArgChain, dl, Arg, FIN,
2827                        MachinePointerInfo::getFixedStack(FI),
2828                        false, false, 0));
2829       }
2830     }
2831
2832     if (!MemOpChains2.empty())
2833       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2834
2835     // Store the return address to the appropriate stack slot.
2836     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2837                                      getPointerTy(), RegInfo->getSlotSize(),
2838                                      FPDiff, dl);
2839   }
2840
2841   // Build a sequence of copy-to-reg nodes chained together with token chain
2842   // and flag operands which copy the outgoing args into registers.
2843   SDValue InFlag;
2844   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2845     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2846                              RegsToPass[i].second, InFlag);
2847     InFlag = Chain.getValue(1);
2848   }
2849
2850   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2851     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2852     // In the 64-bit large code model, we have to make all calls
2853     // through a register, since the call instruction's 32-bit
2854     // pc-relative offset may not be large enough to hold the whole
2855     // address.
2856   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2857     // If the callee is a GlobalAddress node (quite common, every direct call
2858     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2859     // it.
2860
2861     // We should use extra load for direct calls to dllimported functions in
2862     // non-JIT mode.
2863     const GlobalValue *GV = G->getGlobal();
2864     if (!GV->hasDLLImportStorageClass()) {
2865       unsigned char OpFlags = 0;
2866       bool ExtraLoad = false;
2867       unsigned WrapperKind = ISD::DELETED_NODE;
2868
2869       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2870       // external symbols most go through the PLT in PIC mode.  If the symbol
2871       // has hidden or protected visibility, or if it is static or local, then
2872       // we don't need to use the PLT - we can directly call it.
2873       if (Subtarget->isTargetELF() &&
2874           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2875           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2876         OpFlags = X86II::MO_PLT;
2877       } else if (Subtarget->isPICStyleStubAny() &&
2878                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2879                  (!Subtarget->getTargetTriple().isMacOSX() ||
2880                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2881         // PC-relative references to external symbols should go through $stub,
2882         // unless we're building with the leopard linker or later, which
2883         // automatically synthesizes these stubs.
2884         OpFlags = X86II::MO_DARWIN_STUB;
2885       } else if (Subtarget->isPICStyleRIPRel() &&
2886                  isa<Function>(GV) &&
2887                  cast<Function>(GV)->getAttributes().
2888                    hasAttribute(AttributeSet::FunctionIndex,
2889                                 Attribute::NonLazyBind)) {
2890         // If the function is marked as non-lazy, generate an indirect call
2891         // which loads from the GOT directly. This avoids runtime overhead
2892         // at the cost of eager binding (and one extra byte of encoding).
2893         OpFlags = X86II::MO_GOTPCREL;
2894         WrapperKind = X86ISD::WrapperRIP;
2895         ExtraLoad = true;
2896       }
2897
2898       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2899                                           G->getOffset(), OpFlags);
2900
2901       // Add a wrapper if needed.
2902       if (WrapperKind != ISD::DELETED_NODE)
2903         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2904       // Add extra indirection if needed.
2905       if (ExtraLoad)
2906         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2907                              MachinePointerInfo::getGOT(),
2908                              false, false, false, 0);
2909     }
2910   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2911     unsigned char OpFlags = 0;
2912
2913     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2914     // external symbols should go through the PLT.
2915     if (Subtarget->isTargetELF() &&
2916         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2917       OpFlags = X86II::MO_PLT;
2918     } else if (Subtarget->isPICStyleStubAny() &&
2919                (!Subtarget->getTargetTriple().isMacOSX() ||
2920                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2921       // PC-relative references to external symbols should go through $stub,
2922       // unless we're building with the leopard linker or later, which
2923       // automatically synthesizes these stubs.
2924       OpFlags = X86II::MO_DARWIN_STUB;
2925     }
2926
2927     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2928                                          OpFlags);
2929   }
2930
2931   // Returns a chain & a flag for retval copy to use.
2932   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2933   SmallVector<SDValue, 8> Ops;
2934
2935   if (!IsSibcall && isTailCall) {
2936     Chain = DAG.getCALLSEQ_END(Chain,
2937                                DAG.getIntPtrConstant(NumBytesToPop, true),
2938                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2939     InFlag = Chain.getValue(1);
2940   }
2941
2942   Ops.push_back(Chain);
2943   Ops.push_back(Callee);
2944
2945   if (isTailCall)
2946     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2947
2948   // Add argument registers to the end of the list so that they are known live
2949   // into the call.
2950   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2951     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2952                                   RegsToPass[i].second.getValueType()));
2953
2954   // Add a register mask operand representing the call-preserved registers.
2955   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2956   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2957   assert(Mask && "Missing call preserved mask for calling convention");
2958   Ops.push_back(DAG.getRegisterMask(Mask));
2959
2960   if (InFlag.getNode())
2961     Ops.push_back(InFlag);
2962
2963   if (isTailCall) {
2964     // We used to do:
2965     //// If this is the first return lowered for this function, add the regs
2966     //// to the liveout set for the function.
2967     // This isn't right, although it's probably harmless on x86; liveouts
2968     // should be computed from returns not tail calls.  Consider a void
2969     // function making a tail call to a function returning int.
2970     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2971   }
2972
2973   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2974   InFlag = Chain.getValue(1);
2975
2976   // Create the CALLSEQ_END node.
2977   unsigned NumBytesForCalleeToPop;
2978   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2979                        DAG.getTarget().Options.GuaranteedTailCallOpt))
2980     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2981   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2982            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2983            SR == StackStructReturn)
2984     // If this is a call to a struct-return function, the callee
2985     // pops the hidden struct pointer, so we have to push it back.
2986     // This is common for Darwin/X86, Linux & Mingw32 targets.
2987     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2988     NumBytesForCalleeToPop = 4;
2989   else
2990     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2991
2992   // Returns a flag for retval copy to use.
2993   if (!IsSibcall) {
2994     Chain = DAG.getCALLSEQ_END(Chain,
2995                                DAG.getIntPtrConstant(NumBytesToPop, true),
2996                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2997                                                      true),
2998                                InFlag, dl);
2999     InFlag = Chain.getValue(1);
3000   }
3001
3002   // Handle result values, copying them out of physregs into vregs that we
3003   // return.
3004   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3005                          Ins, dl, DAG, InVals);
3006 }
3007
3008 //===----------------------------------------------------------------------===//
3009 //                Fast Calling Convention (tail call) implementation
3010 //===----------------------------------------------------------------------===//
3011
3012 //  Like std call, callee cleans arguments, convention except that ECX is
3013 //  reserved for storing the tail called function address. Only 2 registers are
3014 //  free for argument passing (inreg). Tail call optimization is performed
3015 //  provided:
3016 //                * tailcallopt is enabled
3017 //                * caller/callee are fastcc
3018 //  On X86_64 architecture with GOT-style position independent code only local
3019 //  (within module) calls are supported at the moment.
3020 //  To keep the stack aligned according to platform abi the function
3021 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3022 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3023 //  If a tail called function callee has more arguments than the caller the
3024 //  caller needs to make sure that there is room to move the RETADDR to. This is
3025 //  achieved by reserving an area the size of the argument delta right after the
3026 //  original REtADDR, but before the saved framepointer or the spilled registers
3027 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3028 //  stack layout:
3029 //    arg1
3030 //    arg2
3031 //    RETADDR
3032 //    [ new RETADDR
3033 //      move area ]
3034 //    (possible EBP)
3035 //    ESI
3036 //    EDI
3037 //    local1 ..
3038
3039 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3040 /// for a 16 byte align requirement.
3041 unsigned
3042 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3043                                                SelectionDAG& DAG) const {
3044   MachineFunction &MF = DAG.getMachineFunction();
3045   const TargetMachine &TM = MF.getTarget();
3046   const X86RegisterInfo *RegInfo =
3047     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3048   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3049   unsigned StackAlignment = TFI.getStackAlignment();
3050   uint64_t AlignMask = StackAlignment - 1;
3051   int64_t Offset = StackSize;
3052   unsigned SlotSize = RegInfo->getSlotSize();
3053   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3054     // Number smaller than 12 so just add the difference.
3055     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3056   } else {
3057     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3058     Offset = ((~AlignMask) & Offset) + StackAlignment +
3059       (StackAlignment-SlotSize);
3060   }
3061   return Offset;
3062 }
3063
3064 /// MatchingStackOffset - Return true if the given stack call argument is
3065 /// already available in the same position (relatively) of the caller's
3066 /// incoming argument stack.
3067 static
3068 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3069                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3070                          const X86InstrInfo *TII) {
3071   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3072   int FI = INT_MAX;
3073   if (Arg.getOpcode() == ISD::CopyFromReg) {
3074     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3075     if (!TargetRegisterInfo::isVirtualRegister(VR))
3076       return false;
3077     MachineInstr *Def = MRI->getVRegDef(VR);
3078     if (!Def)
3079       return false;
3080     if (!Flags.isByVal()) {
3081       if (!TII->isLoadFromStackSlot(Def, FI))
3082         return false;
3083     } else {
3084       unsigned Opcode = Def->getOpcode();
3085       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3086           Def->getOperand(1).isFI()) {
3087         FI = Def->getOperand(1).getIndex();
3088         Bytes = Flags.getByValSize();
3089       } else
3090         return false;
3091     }
3092   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3093     if (Flags.isByVal())
3094       // ByVal argument is passed in as a pointer but it's now being
3095       // dereferenced. e.g.
3096       // define @foo(%struct.X* %A) {
3097       //   tail call @bar(%struct.X* byval %A)
3098       // }
3099       return false;
3100     SDValue Ptr = Ld->getBasePtr();
3101     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3102     if (!FINode)
3103       return false;
3104     FI = FINode->getIndex();
3105   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3106     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3107     FI = FINode->getIndex();
3108     Bytes = Flags.getByValSize();
3109   } else
3110     return false;
3111
3112   assert(FI != INT_MAX);
3113   if (!MFI->isFixedObjectIndex(FI))
3114     return false;
3115   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3116 }
3117
3118 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3119 /// for tail call optimization. Targets which want to do tail call
3120 /// optimization should implement this function.
3121 bool
3122 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3123                                                      CallingConv::ID CalleeCC,
3124                                                      bool isVarArg,
3125                                                      bool isCalleeStructRet,
3126                                                      bool isCallerStructRet,
3127                                                      Type *RetTy,
3128                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3129                                     const SmallVectorImpl<SDValue> &OutVals,
3130                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3131                                                      SelectionDAG &DAG) const {
3132   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3133     return false;
3134
3135   // If -tailcallopt is specified, make fastcc functions tail-callable.
3136   const MachineFunction &MF = DAG.getMachineFunction();
3137   const Function *CallerF = MF.getFunction();
3138
3139   // If the function return type is x86_fp80 and the callee return type is not,
3140   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3141   // perform a tailcall optimization here.
3142   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3143     return false;
3144
3145   CallingConv::ID CallerCC = CallerF->getCallingConv();
3146   bool CCMatch = CallerCC == CalleeCC;
3147   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3148   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3149
3150   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3151     if (IsTailCallConvention(CalleeCC) && CCMatch)
3152       return true;
3153     return false;
3154   }
3155
3156   // Look for obvious safe cases to perform tail call optimization that do not
3157   // require ABI changes. This is what gcc calls sibcall.
3158
3159   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3160   // emit a special epilogue.
3161   const X86RegisterInfo *RegInfo =
3162     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3163   if (RegInfo->needsStackRealignment(MF))
3164     return false;
3165
3166   // Also avoid sibcall optimization if either caller or callee uses struct
3167   // return semantics.
3168   if (isCalleeStructRet || isCallerStructRet)
3169     return false;
3170
3171   // An stdcall/thiscall caller is expected to clean up its arguments; the
3172   // callee isn't going to do that.
3173   // FIXME: this is more restrictive than needed. We could produce a tailcall
3174   // when the stack adjustment matches. For example, with a thiscall that takes
3175   // only one argument.
3176   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3177                    CallerCC == CallingConv::X86_ThisCall))
3178     return false;
3179
3180   // Do not sibcall optimize vararg calls unless all arguments are passed via
3181   // registers.
3182   if (isVarArg && !Outs.empty()) {
3183
3184     // Optimizing for varargs on Win64 is unlikely to be safe without
3185     // additional testing.
3186     if (IsCalleeWin64 || IsCallerWin64)
3187       return false;
3188
3189     SmallVector<CCValAssign, 16> ArgLocs;
3190     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3191                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3192
3193     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3194     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3195       if (!ArgLocs[i].isRegLoc())
3196         return false;
3197   }
3198
3199   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3200   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3201   // this into a sibcall.
3202   bool Unused = false;
3203   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3204     if (!Ins[i].Used) {
3205       Unused = true;
3206       break;
3207     }
3208   }
3209   if (Unused) {
3210     SmallVector<CCValAssign, 16> RVLocs;
3211     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3212                    DAG.getTarget(), RVLocs, *DAG.getContext());
3213     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3214     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3215       CCValAssign &VA = RVLocs[i];
3216       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3217         return false;
3218     }
3219   }
3220
3221   // If the calling conventions do not match, then we'd better make sure the
3222   // results are returned in the same way as what the caller expects.
3223   if (!CCMatch) {
3224     SmallVector<CCValAssign, 16> RVLocs1;
3225     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3226                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3227     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3228
3229     SmallVector<CCValAssign, 16> RVLocs2;
3230     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3231                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3232     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3233
3234     if (RVLocs1.size() != RVLocs2.size())
3235       return false;
3236     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3237       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3238         return false;
3239       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3240         return false;
3241       if (RVLocs1[i].isRegLoc()) {
3242         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3243           return false;
3244       } else {
3245         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3246           return false;
3247       }
3248     }
3249   }
3250
3251   // If the callee takes no arguments then go on to check the results of the
3252   // call.
3253   if (!Outs.empty()) {
3254     // Check if stack adjustment is needed. For now, do not do this if any
3255     // argument is passed on the stack.
3256     SmallVector<CCValAssign, 16> ArgLocs;
3257     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3258                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3259
3260     // Allocate shadow area for Win64
3261     if (IsCalleeWin64)
3262       CCInfo.AllocateStack(32, 8);
3263
3264     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3265     if (CCInfo.getNextStackOffset()) {
3266       MachineFunction &MF = DAG.getMachineFunction();
3267       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3268         return false;
3269
3270       // Check if the arguments are already laid out in the right way as
3271       // the caller's fixed stack objects.
3272       MachineFrameInfo *MFI = MF.getFrameInfo();
3273       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3274       const X86InstrInfo *TII =
3275           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3276       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3277         CCValAssign &VA = ArgLocs[i];
3278         SDValue Arg = OutVals[i];
3279         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3280         if (VA.getLocInfo() == CCValAssign::Indirect)
3281           return false;
3282         if (!VA.isRegLoc()) {
3283           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3284                                    MFI, MRI, TII))
3285             return false;
3286         }
3287       }
3288     }
3289
3290     // If the tailcall address may be in a register, then make sure it's
3291     // possible to register allocate for it. In 32-bit, the call address can
3292     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3293     // callee-saved registers are restored. These happen to be the same
3294     // registers used to pass 'inreg' arguments so watch out for those.
3295     if (!Subtarget->is64Bit() &&
3296         ((!isa<GlobalAddressSDNode>(Callee) &&
3297           !isa<ExternalSymbolSDNode>(Callee)) ||
3298          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3299       unsigned NumInRegs = 0;
3300       // In PIC we need an extra register to formulate the address computation
3301       // for the callee.
3302       unsigned MaxInRegs =
3303         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3304
3305       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3306         CCValAssign &VA = ArgLocs[i];
3307         if (!VA.isRegLoc())
3308           continue;
3309         unsigned Reg = VA.getLocReg();
3310         switch (Reg) {
3311         default: break;
3312         case X86::EAX: case X86::EDX: case X86::ECX:
3313           if (++NumInRegs == MaxInRegs)
3314             return false;
3315           break;
3316         }
3317       }
3318     }
3319   }
3320
3321   return true;
3322 }
3323
3324 FastISel *
3325 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3326                                   const TargetLibraryInfo *libInfo) const {
3327   return X86::createFastISel(funcInfo, libInfo);
3328 }
3329
3330 //===----------------------------------------------------------------------===//
3331 //                           Other Lowering Hooks
3332 //===----------------------------------------------------------------------===//
3333
3334 static bool MayFoldLoad(SDValue Op) {
3335   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3336 }
3337
3338 static bool MayFoldIntoStore(SDValue Op) {
3339   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3340 }
3341
3342 static bool isTargetShuffle(unsigned Opcode) {
3343   switch(Opcode) {
3344   default: return false;
3345   case X86ISD::PSHUFD:
3346   case X86ISD::PSHUFHW:
3347   case X86ISD::PSHUFLW:
3348   case X86ISD::SHUFP:
3349   case X86ISD::PALIGNR:
3350   case X86ISD::MOVLHPS:
3351   case X86ISD::MOVLHPD:
3352   case X86ISD::MOVHLPS:
3353   case X86ISD::MOVLPS:
3354   case X86ISD::MOVLPD:
3355   case X86ISD::MOVSHDUP:
3356   case X86ISD::MOVSLDUP:
3357   case X86ISD::MOVDDUP:
3358   case X86ISD::MOVSS:
3359   case X86ISD::MOVSD:
3360   case X86ISD::UNPCKL:
3361   case X86ISD::UNPCKH:
3362   case X86ISD::VPERMILP:
3363   case X86ISD::VPERM2X128:
3364   case X86ISD::VPERMI:
3365     return true;
3366   }
3367 }
3368
3369 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3370                                     SDValue V1, SelectionDAG &DAG) {
3371   switch(Opc) {
3372   default: llvm_unreachable("Unknown x86 shuffle node");
3373   case X86ISD::MOVSHDUP:
3374   case X86ISD::MOVSLDUP:
3375   case X86ISD::MOVDDUP:
3376     return DAG.getNode(Opc, dl, VT, V1);
3377   }
3378 }
3379
3380 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3381                                     SDValue V1, unsigned TargetMask,
3382                                     SelectionDAG &DAG) {
3383   switch(Opc) {
3384   default: llvm_unreachable("Unknown x86 shuffle node");
3385   case X86ISD::PSHUFD:
3386   case X86ISD::PSHUFHW:
3387   case X86ISD::PSHUFLW:
3388   case X86ISD::VPERMILP:
3389   case X86ISD::VPERMI:
3390     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3391   }
3392 }
3393
3394 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3395                                     SDValue V1, SDValue V2, unsigned TargetMask,
3396                                     SelectionDAG &DAG) {
3397   switch(Opc) {
3398   default: llvm_unreachable("Unknown x86 shuffle node");
3399   case X86ISD::PALIGNR:
3400   case X86ISD::SHUFP:
3401   case X86ISD::VPERM2X128:
3402     return DAG.getNode(Opc, dl, VT, V1, V2,
3403                        DAG.getConstant(TargetMask, MVT::i8));
3404   }
3405 }
3406
3407 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3408                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3409   switch(Opc) {
3410   default: llvm_unreachable("Unknown x86 shuffle node");
3411   case X86ISD::MOVLHPS:
3412   case X86ISD::MOVLHPD:
3413   case X86ISD::MOVHLPS:
3414   case X86ISD::MOVLPS:
3415   case X86ISD::MOVLPD:
3416   case X86ISD::MOVSS:
3417   case X86ISD::MOVSD:
3418   case X86ISD::UNPCKL:
3419   case X86ISD::UNPCKH:
3420     return DAG.getNode(Opc, dl, VT, V1, V2);
3421   }
3422 }
3423
3424 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3425   MachineFunction &MF = DAG.getMachineFunction();
3426   const X86RegisterInfo *RegInfo =
3427     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3428   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3429   int ReturnAddrIndex = FuncInfo->getRAIndex();
3430
3431   if (ReturnAddrIndex == 0) {
3432     // Set up a frame object for the return address.
3433     unsigned SlotSize = RegInfo->getSlotSize();
3434     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3435                                                            -(int64_t)SlotSize,
3436                                                            false);
3437     FuncInfo->setRAIndex(ReturnAddrIndex);
3438   }
3439
3440   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3441 }
3442
3443 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3444                                        bool hasSymbolicDisplacement) {
3445   // Offset should fit into 32 bit immediate field.
3446   if (!isInt<32>(Offset))
3447     return false;
3448
3449   // If we don't have a symbolic displacement - we don't have any extra
3450   // restrictions.
3451   if (!hasSymbolicDisplacement)
3452     return true;
3453
3454   // FIXME: Some tweaks might be needed for medium code model.
3455   if (M != CodeModel::Small && M != CodeModel::Kernel)
3456     return false;
3457
3458   // For small code model we assume that latest object is 16MB before end of 31
3459   // bits boundary. We may also accept pretty large negative constants knowing
3460   // that all objects are in the positive half of address space.
3461   if (M == CodeModel::Small && Offset < 16*1024*1024)
3462     return true;
3463
3464   // For kernel code model we know that all object resist in the negative half
3465   // of 32bits address space. We may not accept negative offsets, since they may
3466   // be just off and we may accept pretty large positive ones.
3467   if (M == CodeModel::Kernel && Offset > 0)
3468     return true;
3469
3470   return false;
3471 }
3472
3473 /// isCalleePop - Determines whether the callee is required to pop its
3474 /// own arguments. Callee pop is necessary to support tail calls.
3475 bool X86::isCalleePop(CallingConv::ID CallingConv,
3476                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3477   if (IsVarArg)
3478     return false;
3479
3480   switch (CallingConv) {
3481   default:
3482     return false;
3483   case CallingConv::X86_StdCall:
3484     return !is64Bit;
3485   case CallingConv::X86_FastCall:
3486     return !is64Bit;
3487   case CallingConv::X86_ThisCall:
3488     return !is64Bit;
3489   case CallingConv::Fast:
3490     return TailCallOpt;
3491   case CallingConv::GHC:
3492     return TailCallOpt;
3493   case CallingConv::HiPE:
3494     return TailCallOpt;
3495   }
3496 }
3497
3498 /// \brief Return true if the condition is an unsigned comparison operation.
3499 static bool isX86CCUnsigned(unsigned X86CC) {
3500   switch (X86CC) {
3501   default: llvm_unreachable("Invalid integer condition!");
3502   case X86::COND_E:     return true;
3503   case X86::COND_G:     return false;
3504   case X86::COND_GE:    return false;
3505   case X86::COND_L:     return false;
3506   case X86::COND_LE:    return false;
3507   case X86::COND_NE:    return true;
3508   case X86::COND_B:     return true;
3509   case X86::COND_A:     return true;
3510   case X86::COND_BE:    return true;
3511   case X86::COND_AE:    return true;
3512   }
3513   llvm_unreachable("covered switch fell through?!");
3514 }
3515
3516 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3517 /// specific condition code, returning the condition code and the LHS/RHS of the
3518 /// comparison to make.
3519 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3520                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3521   if (!isFP) {
3522     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3523       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3524         // X > -1   -> X == 0, jump !sign.
3525         RHS = DAG.getConstant(0, RHS.getValueType());
3526         return X86::COND_NS;
3527       }
3528       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3529         // X < 0   -> X == 0, jump on sign.
3530         return X86::COND_S;
3531       }
3532       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3533         // X < 1   -> X <= 0
3534         RHS = DAG.getConstant(0, RHS.getValueType());
3535         return X86::COND_LE;
3536       }
3537     }
3538
3539     switch (SetCCOpcode) {
3540     default: llvm_unreachable("Invalid integer condition!");
3541     case ISD::SETEQ:  return X86::COND_E;
3542     case ISD::SETGT:  return X86::COND_G;
3543     case ISD::SETGE:  return X86::COND_GE;
3544     case ISD::SETLT:  return X86::COND_L;
3545     case ISD::SETLE:  return X86::COND_LE;
3546     case ISD::SETNE:  return X86::COND_NE;
3547     case ISD::SETULT: return X86::COND_B;
3548     case ISD::SETUGT: return X86::COND_A;
3549     case ISD::SETULE: return X86::COND_BE;
3550     case ISD::SETUGE: return X86::COND_AE;
3551     }
3552   }
3553
3554   // First determine if it is required or is profitable to flip the operands.
3555
3556   // If LHS is a foldable load, but RHS is not, flip the condition.
3557   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3558       !ISD::isNON_EXTLoad(RHS.getNode())) {
3559     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3560     std::swap(LHS, RHS);
3561   }
3562
3563   switch (SetCCOpcode) {
3564   default: break;
3565   case ISD::SETOLT:
3566   case ISD::SETOLE:
3567   case ISD::SETUGT:
3568   case ISD::SETUGE:
3569     std::swap(LHS, RHS);
3570     break;
3571   }
3572
3573   // On a floating point condition, the flags are set as follows:
3574   // ZF  PF  CF   op
3575   //  0 | 0 | 0 | X > Y
3576   //  0 | 0 | 1 | X < Y
3577   //  1 | 0 | 0 | X == Y
3578   //  1 | 1 | 1 | unordered
3579   switch (SetCCOpcode) {
3580   default: llvm_unreachable("Condcode should be pre-legalized away");
3581   case ISD::SETUEQ:
3582   case ISD::SETEQ:   return X86::COND_E;
3583   case ISD::SETOLT:              // flipped
3584   case ISD::SETOGT:
3585   case ISD::SETGT:   return X86::COND_A;
3586   case ISD::SETOLE:              // flipped
3587   case ISD::SETOGE:
3588   case ISD::SETGE:   return X86::COND_AE;
3589   case ISD::SETUGT:              // flipped
3590   case ISD::SETULT:
3591   case ISD::SETLT:   return X86::COND_B;
3592   case ISD::SETUGE:              // flipped
3593   case ISD::SETULE:
3594   case ISD::SETLE:   return X86::COND_BE;
3595   case ISD::SETONE:
3596   case ISD::SETNE:   return X86::COND_NE;
3597   case ISD::SETUO:   return X86::COND_P;
3598   case ISD::SETO:    return X86::COND_NP;
3599   case ISD::SETOEQ:
3600   case ISD::SETUNE:  return X86::COND_INVALID;
3601   }
3602 }
3603
3604 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3605 /// code. Current x86 isa includes the following FP cmov instructions:
3606 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3607 static bool hasFPCMov(unsigned X86CC) {
3608   switch (X86CC) {
3609   default:
3610     return false;
3611   case X86::COND_B:
3612   case X86::COND_BE:
3613   case X86::COND_E:
3614   case X86::COND_P:
3615   case X86::COND_A:
3616   case X86::COND_AE:
3617   case X86::COND_NE:
3618   case X86::COND_NP:
3619     return true;
3620   }
3621 }
3622
3623 /// isFPImmLegal - Returns true if the target can instruction select the
3624 /// specified FP immediate natively. If false, the legalizer will
3625 /// materialize the FP immediate as a load from a constant pool.
3626 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3627   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3628     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3629       return true;
3630   }
3631   return false;
3632 }
3633
3634 /// \brief Returns true if it is beneficial to convert a load of a constant
3635 /// to just the constant itself.
3636 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3637                                                           Type *Ty) const {
3638   assert(Ty->isIntegerTy());
3639
3640   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3641   if (BitSize == 0 || BitSize > 64)
3642     return false;
3643   return true;
3644 }
3645
3646 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3647 /// the specified range (L, H].
3648 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3649   return (Val < 0) || (Val >= Low && Val < Hi);
3650 }
3651
3652 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3653 /// specified value.
3654 static bool isUndefOrEqual(int Val, int CmpVal) {
3655   return (Val < 0 || Val == CmpVal);
3656 }
3657
3658 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3659 /// from position Pos and ending in Pos+Size, falls within the specified
3660 /// sequential range (L, L+Pos]. or is undef.
3661 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3662                                        unsigned Pos, unsigned Size, int Low) {
3663   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3664     if (!isUndefOrEqual(Mask[i], Low))
3665       return false;
3666   return true;
3667 }
3668
3669 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3670 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3671 /// the second operand.
3672 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3673   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3674     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3675   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3676     return (Mask[0] < 2 && Mask[1] < 2);
3677   return false;
3678 }
3679
3680 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3681 /// is suitable for input to PSHUFHW.
3682 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3683   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3684     return false;
3685
3686   // Lower quadword copied in order or undef.
3687   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3688     return false;
3689
3690   // Upper quadword shuffled.
3691   for (unsigned i = 4; i != 8; ++i)
3692     if (!isUndefOrInRange(Mask[i], 4, 8))
3693       return false;
3694
3695   if (VT == MVT::v16i16) {
3696     // Lower quadword copied in order or undef.
3697     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3698       return false;
3699
3700     // Upper quadword shuffled.
3701     for (unsigned i = 12; i != 16; ++i)
3702       if (!isUndefOrInRange(Mask[i], 12, 16))
3703         return false;
3704   }
3705
3706   return true;
3707 }
3708
3709 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3710 /// is suitable for input to PSHUFLW.
3711 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3712   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3713     return false;
3714
3715   // Upper quadword copied in order.
3716   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3717     return false;
3718
3719   // Lower quadword shuffled.
3720   for (unsigned i = 0; i != 4; ++i)
3721     if (!isUndefOrInRange(Mask[i], 0, 4))
3722       return false;
3723
3724   if (VT == MVT::v16i16) {
3725     // Upper quadword copied in order.
3726     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3727       return false;
3728
3729     // Lower quadword shuffled.
3730     for (unsigned i = 8; i != 12; ++i)
3731       if (!isUndefOrInRange(Mask[i], 8, 12))
3732         return false;
3733   }
3734
3735   return true;
3736 }
3737
3738 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3739 /// is suitable for input to PALIGNR.
3740 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3741                           const X86Subtarget *Subtarget) {
3742   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3743       (VT.is256BitVector() && !Subtarget->hasInt256()))
3744     return false;
3745
3746   unsigned NumElts = VT.getVectorNumElements();
3747   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3748   unsigned NumLaneElts = NumElts/NumLanes;
3749
3750   // Do not handle 64-bit element shuffles with palignr.
3751   if (NumLaneElts == 2)
3752     return false;
3753
3754   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3755     unsigned i;
3756     for (i = 0; i != NumLaneElts; ++i) {
3757       if (Mask[i+l] >= 0)
3758         break;
3759     }
3760
3761     // Lane is all undef, go to next lane
3762     if (i == NumLaneElts)
3763       continue;
3764
3765     int Start = Mask[i+l];
3766
3767     // Make sure its in this lane in one of the sources
3768     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3769         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3770       return false;
3771
3772     // If not lane 0, then we must match lane 0
3773     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3774       return false;
3775
3776     // Correct second source to be contiguous with first source
3777     if (Start >= (int)NumElts)
3778       Start -= NumElts - NumLaneElts;
3779
3780     // Make sure we're shifting in the right direction.
3781     if (Start <= (int)(i+l))
3782       return false;
3783
3784     Start -= i;
3785
3786     // Check the rest of the elements to see if they are consecutive.
3787     for (++i; i != NumLaneElts; ++i) {
3788       int Idx = Mask[i+l];
3789
3790       // Make sure its in this lane
3791       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3792           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3793         return false;
3794
3795       // If not lane 0, then we must match lane 0
3796       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3797         return false;
3798
3799       if (Idx >= (int)NumElts)
3800         Idx -= NumElts - NumLaneElts;
3801
3802       if (!isUndefOrEqual(Idx, Start+i))
3803         return false;
3804
3805     }
3806   }
3807
3808   return true;
3809 }
3810
3811 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3812 /// the two vector operands have swapped position.
3813 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3814                                      unsigned NumElems) {
3815   for (unsigned i = 0; i != NumElems; ++i) {
3816     int idx = Mask[i];
3817     if (idx < 0)
3818       continue;
3819     else if (idx < (int)NumElems)
3820       Mask[i] = idx + NumElems;
3821     else
3822       Mask[i] = idx - NumElems;
3823   }
3824 }
3825
3826 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3827 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3828 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3829 /// reverse of what x86 shuffles want.
3830 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3831
3832   unsigned NumElems = VT.getVectorNumElements();
3833   unsigned NumLanes = VT.getSizeInBits()/128;
3834   unsigned NumLaneElems = NumElems/NumLanes;
3835
3836   if (NumLaneElems != 2 && NumLaneElems != 4)
3837     return false;
3838
3839   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3840   bool symetricMaskRequired =
3841     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3842
3843   // VSHUFPSY divides the resulting vector into 4 chunks.
3844   // The sources are also splitted into 4 chunks, and each destination
3845   // chunk must come from a different source chunk.
3846   //
3847   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3848   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3849   //
3850   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3851   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3852   //
3853   // VSHUFPDY divides the resulting vector into 4 chunks.
3854   // The sources are also splitted into 4 chunks, and each destination
3855   // chunk must come from a different source chunk.
3856   //
3857   //  SRC1 =>      X3       X2       X1       X0
3858   //  SRC2 =>      Y3       Y2       Y1       Y0
3859   //
3860   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3861   //
3862   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3863   unsigned HalfLaneElems = NumLaneElems/2;
3864   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3865     for (unsigned i = 0; i != NumLaneElems; ++i) {
3866       int Idx = Mask[i+l];
3867       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3868       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3869         return false;
3870       // For VSHUFPSY, the mask of the second half must be the same as the
3871       // first but with the appropriate offsets. This works in the same way as
3872       // VPERMILPS works with masks.
3873       if (!symetricMaskRequired || Idx < 0)
3874         continue;
3875       if (MaskVal[i] < 0) {
3876         MaskVal[i] = Idx - l;
3877         continue;
3878       }
3879       if ((signed)(Idx - l) != MaskVal[i])
3880         return false;
3881     }
3882   }
3883
3884   return true;
3885 }
3886
3887 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3888 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3889 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3890   if (!VT.is128BitVector())
3891     return false;
3892
3893   unsigned NumElems = VT.getVectorNumElements();
3894
3895   if (NumElems != 4)
3896     return false;
3897
3898   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3899   return isUndefOrEqual(Mask[0], 6) &&
3900          isUndefOrEqual(Mask[1], 7) &&
3901          isUndefOrEqual(Mask[2], 2) &&
3902          isUndefOrEqual(Mask[3], 3);
3903 }
3904
3905 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3906 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3907 /// <2, 3, 2, 3>
3908 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3909   if (!VT.is128BitVector())
3910     return false;
3911
3912   unsigned NumElems = VT.getVectorNumElements();
3913
3914   if (NumElems != 4)
3915     return false;
3916
3917   return isUndefOrEqual(Mask[0], 2) &&
3918          isUndefOrEqual(Mask[1], 3) &&
3919          isUndefOrEqual(Mask[2], 2) &&
3920          isUndefOrEqual(Mask[3], 3);
3921 }
3922
3923 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3925 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3926   if (!VT.is128BitVector())
3927     return false;
3928
3929   unsigned NumElems = VT.getVectorNumElements();
3930
3931   if (NumElems != 2 && NumElems != 4)
3932     return false;
3933
3934   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3935     if (!isUndefOrEqual(Mask[i], i + NumElems))
3936       return false;
3937
3938   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3939     if (!isUndefOrEqual(Mask[i], i))
3940       return false;
3941
3942   return true;
3943 }
3944
3945 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3946 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3947 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3948   if (!VT.is128BitVector())
3949     return false;
3950
3951   unsigned NumElems = VT.getVectorNumElements();
3952
3953   if (NumElems != 2 && NumElems != 4)
3954     return false;
3955
3956   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3957     if (!isUndefOrEqual(Mask[i], i))
3958       return false;
3959
3960   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3961     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3962       return false;
3963
3964   return true;
3965 }
3966
3967 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3968 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3969 /// i. e: If all but one element come from the same vector.
3970 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3971   // TODO: Deal with AVX's VINSERTPS
3972   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3973     return false;
3974
3975   unsigned CorrectPosV1 = 0;
3976   unsigned CorrectPosV2 = 0;
3977   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3978     if (Mask[i] == -1) {
3979       ++CorrectPosV1;
3980       ++CorrectPosV2;
3981       continue;
3982     }
3983
3984     if (Mask[i] == i)
3985       ++CorrectPosV1;
3986     else if (Mask[i] == i + 4)
3987       ++CorrectPosV2;
3988   }
3989
3990   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3991     // We have 3 elements (undefs count as elements from any vector) from one
3992     // vector, and one from another.
3993     return true;
3994
3995   return false;
3996 }
3997
3998 //
3999 // Some special combinations that can be optimized.
4000 //
4001 static
4002 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4003                                SelectionDAG &DAG) {
4004   MVT VT = SVOp->getSimpleValueType(0);
4005   SDLoc dl(SVOp);
4006
4007   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4008     return SDValue();
4009
4010   ArrayRef<int> Mask = SVOp->getMask();
4011
4012   // These are the special masks that may be optimized.
4013   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4014   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4015   bool MatchEvenMask = true;
4016   bool MatchOddMask  = true;
4017   for (int i=0; i<8; ++i) {
4018     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4019       MatchEvenMask = false;
4020     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4021       MatchOddMask = false;
4022   }
4023
4024   if (!MatchEvenMask && !MatchOddMask)
4025     return SDValue();
4026
4027   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4028
4029   SDValue Op0 = SVOp->getOperand(0);
4030   SDValue Op1 = SVOp->getOperand(1);
4031
4032   if (MatchEvenMask) {
4033     // Shift the second operand right to 32 bits.
4034     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4035     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4036   } else {
4037     // Shift the first operand left to 32 bits.
4038     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4039     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4040   }
4041   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4042   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4043 }
4044
4045 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4046 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4047 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4048                          bool HasInt256, bool V2IsSplat = false) {
4049
4050   assert(VT.getSizeInBits() >= 128 &&
4051          "Unsupported vector type for unpckl");
4052
4053   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4054   unsigned NumLanes;
4055   unsigned NumOf256BitLanes;
4056   unsigned NumElts = VT.getVectorNumElements();
4057   if (VT.is256BitVector()) {
4058     if (NumElts != 4 && NumElts != 8 &&
4059         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4060     return false;
4061     NumLanes = 2;
4062     NumOf256BitLanes = 1;
4063   } else if (VT.is512BitVector()) {
4064     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4065            "Unsupported vector type for unpckh");
4066     NumLanes = 2;
4067     NumOf256BitLanes = 2;
4068   } else {
4069     NumLanes = 1;
4070     NumOf256BitLanes = 1;
4071   }
4072
4073   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4074   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4075
4076   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4077     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4078       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4079         int BitI  = Mask[l256*NumEltsInStride+l+i];
4080         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4081         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4082           return false;
4083         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4084           return false;
4085         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4086           return false;
4087       }
4088     }
4089   }
4090   return true;
4091 }
4092
4093 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4094 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4095 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4096                          bool HasInt256, bool V2IsSplat = false) {
4097   assert(VT.getSizeInBits() >= 128 &&
4098          "Unsupported vector type for unpckh");
4099
4100   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4101   unsigned NumLanes;
4102   unsigned NumOf256BitLanes;
4103   unsigned NumElts = VT.getVectorNumElements();
4104   if (VT.is256BitVector()) {
4105     if (NumElts != 4 && NumElts != 8 &&
4106         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4107     return false;
4108     NumLanes = 2;
4109     NumOf256BitLanes = 1;
4110   } else if (VT.is512BitVector()) {
4111     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4112            "Unsupported vector type for unpckh");
4113     NumLanes = 2;
4114     NumOf256BitLanes = 2;
4115   } else {
4116     NumLanes = 1;
4117     NumOf256BitLanes = 1;
4118   }
4119
4120   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4121   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4122
4123   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4124     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4125       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4126         int BitI  = Mask[l256*NumEltsInStride+l+i];
4127         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4128         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4129           return false;
4130         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4131           return false;
4132         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4133           return false;
4134       }
4135     }
4136   }
4137   return true;
4138 }
4139
4140 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4141 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4142 /// <0, 0, 1, 1>
4143 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4144   unsigned NumElts = VT.getVectorNumElements();
4145   bool Is256BitVec = VT.is256BitVector();
4146
4147   if (VT.is512BitVector())
4148     return false;
4149   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4150          "Unsupported vector type for unpckh");
4151
4152   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4153       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4154     return false;
4155
4156   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4157   // FIXME: Need a better way to get rid of this, there's no latency difference
4158   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4159   // the former later. We should also remove the "_undef" special mask.
4160   if (NumElts == 4 && Is256BitVec)
4161     return false;
4162
4163   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4164   // independently on 128-bit lanes.
4165   unsigned NumLanes = VT.getSizeInBits()/128;
4166   unsigned NumLaneElts = NumElts/NumLanes;
4167
4168   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4169     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4170       int BitI  = Mask[l+i];
4171       int BitI1 = Mask[l+i+1];
4172
4173       if (!isUndefOrEqual(BitI, j))
4174         return false;
4175       if (!isUndefOrEqual(BitI1, j))
4176         return false;
4177     }
4178   }
4179
4180   return true;
4181 }
4182
4183 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4184 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4185 /// <2, 2, 3, 3>
4186 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4187   unsigned NumElts = VT.getVectorNumElements();
4188
4189   if (VT.is512BitVector())
4190     return false;
4191
4192   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4193          "Unsupported vector type for unpckh");
4194
4195   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4196       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4197     return false;
4198
4199   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4200   // independently on 128-bit lanes.
4201   unsigned NumLanes = VT.getSizeInBits()/128;
4202   unsigned NumLaneElts = NumElts/NumLanes;
4203
4204   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4205     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4206       int BitI  = Mask[l+i];
4207       int BitI1 = Mask[l+i+1];
4208       if (!isUndefOrEqual(BitI, j))
4209         return false;
4210       if (!isUndefOrEqual(BitI1, j))
4211         return false;
4212     }
4213   }
4214   return true;
4215 }
4216
4217 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4218 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4219 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4220   if (!VT.is512BitVector())
4221     return false;
4222
4223   unsigned NumElts = VT.getVectorNumElements();
4224   unsigned HalfSize = NumElts/2;
4225   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4226     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4227       *Imm = 1;
4228       return true;
4229     }
4230   }
4231   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4232     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4233       *Imm = 0;
4234       return true;
4235     }
4236   }
4237   return false;
4238 }
4239
4240 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4241 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4242 /// MOVSD, and MOVD, i.e. setting the lowest element.
4243 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4244   if (VT.getVectorElementType().getSizeInBits() < 32)
4245     return false;
4246   if (!VT.is128BitVector())
4247     return false;
4248
4249   unsigned NumElts = VT.getVectorNumElements();
4250
4251   if (!isUndefOrEqual(Mask[0], NumElts))
4252     return false;
4253
4254   for (unsigned i = 1; i != NumElts; ++i)
4255     if (!isUndefOrEqual(Mask[i], i))
4256       return false;
4257
4258   return true;
4259 }
4260
4261 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4262 /// as permutations between 128-bit chunks or halves. As an example: this
4263 /// shuffle bellow:
4264 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4265 /// The first half comes from the second half of V1 and the second half from the
4266 /// the second half of V2.
4267 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4268   if (!HasFp256 || !VT.is256BitVector())
4269     return false;
4270
4271   // The shuffle result is divided into half A and half B. In total the two
4272   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4273   // B must come from C, D, E or F.
4274   unsigned HalfSize = VT.getVectorNumElements()/2;
4275   bool MatchA = false, MatchB = false;
4276
4277   // Check if A comes from one of C, D, E, F.
4278   for (unsigned Half = 0; Half != 4; ++Half) {
4279     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4280       MatchA = true;
4281       break;
4282     }
4283   }
4284
4285   // Check if B comes from one of C, D, E, F.
4286   for (unsigned Half = 0; Half != 4; ++Half) {
4287     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4288       MatchB = true;
4289       break;
4290     }
4291   }
4292
4293   return MatchA && MatchB;
4294 }
4295
4296 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4297 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4298 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4299   MVT VT = SVOp->getSimpleValueType(0);
4300
4301   unsigned HalfSize = VT.getVectorNumElements()/2;
4302
4303   unsigned FstHalf = 0, SndHalf = 0;
4304   for (unsigned i = 0; i < HalfSize; ++i) {
4305     if (SVOp->getMaskElt(i) > 0) {
4306       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4307       break;
4308     }
4309   }
4310   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4311     if (SVOp->getMaskElt(i) > 0) {
4312       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4313       break;
4314     }
4315   }
4316
4317   return (FstHalf | (SndHalf << 4));
4318 }
4319
4320 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4321 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4322   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4323   if (EltSize < 32)
4324     return false;
4325
4326   unsigned NumElts = VT.getVectorNumElements();
4327   Imm8 = 0;
4328   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4329     for (unsigned i = 0; i != NumElts; ++i) {
4330       if (Mask[i] < 0)
4331         continue;
4332       Imm8 |= Mask[i] << (i*2);
4333     }
4334     return true;
4335   }
4336
4337   unsigned LaneSize = 4;
4338   SmallVector<int, 4> MaskVal(LaneSize, -1);
4339
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 (Mask[i+l] < 0)
4345         continue;
4346       if (MaskVal[i] < 0) {
4347         MaskVal[i] = Mask[i+l] - l;
4348         Imm8 |= MaskVal[i] << (i*2);
4349         continue;
4350       }
4351       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4352         return false;
4353     }
4354   }
4355   return true;
4356 }
4357
4358 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4359 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4360 /// Note that VPERMIL mask matching is different depending whether theunderlying
4361 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4362 /// to the same elements of the low, but to the higher half of the source.
4363 /// In VPERMILPD the two lanes could be shuffled independently of each other
4364 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4365 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4366   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4367   if (VT.getSizeInBits() < 256 || EltSize < 32)
4368     return false;
4369   bool symetricMaskRequired = (EltSize == 32);
4370   unsigned NumElts = VT.getVectorNumElements();
4371
4372   unsigned NumLanes = VT.getSizeInBits()/128;
4373   unsigned LaneSize = NumElts/NumLanes;
4374   // 2 or 4 elements in one lane
4375
4376   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4377   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4378     for (unsigned i = 0; i != LaneSize; ++i) {
4379       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4380         return false;
4381       if (symetricMaskRequired) {
4382         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4383           ExpectedMaskVal[i] = Mask[i+l] - l;
4384           continue;
4385         }
4386         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4387           return false;
4388       }
4389     }
4390   }
4391   return true;
4392 }
4393
4394 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4395 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4396 /// element of vector 2 and the other elements to come from vector 1 in order.
4397 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4398                                bool V2IsSplat = false, bool V2IsUndef = false) {
4399   if (!VT.is128BitVector())
4400     return false;
4401
4402   unsigned NumOps = VT.getVectorNumElements();
4403   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4404     return false;
4405
4406   if (!isUndefOrEqual(Mask[0], 0))
4407     return false;
4408
4409   for (unsigned i = 1; i != NumOps; ++i)
4410     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4411           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4412           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4413       return false;
4414
4415   return true;
4416 }
4417
4418 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4419 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4420 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4421 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4422                            const X86Subtarget *Subtarget) {
4423   if (!Subtarget->hasSSE3())
4424     return false;
4425
4426   unsigned NumElems = VT.getVectorNumElements();
4427
4428   if ((VT.is128BitVector() && NumElems != 4) ||
4429       (VT.is256BitVector() && NumElems != 8) ||
4430       (VT.is512BitVector() && NumElems != 16))
4431     return false;
4432
4433   // "i+1" is the value the indexed mask element must have
4434   for (unsigned i = 0; i != NumElems; i += 2)
4435     if (!isUndefOrEqual(Mask[i], i+1) ||
4436         !isUndefOrEqual(Mask[i+1], i+1))
4437       return false;
4438
4439   return true;
4440 }
4441
4442 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4443 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4444 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4445 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4446                            const X86Subtarget *Subtarget) {
4447   if (!Subtarget->hasSSE3())
4448     return false;
4449
4450   unsigned NumElems = VT.getVectorNumElements();
4451
4452   if ((VT.is128BitVector() && NumElems != 4) ||
4453       (VT.is256BitVector() && NumElems != 8) ||
4454       (VT.is512BitVector() && NumElems != 16))
4455     return false;
4456
4457   // "i" is the value the indexed mask element must have
4458   for (unsigned i = 0; i != NumElems; i += 2)
4459     if (!isUndefOrEqual(Mask[i], i) ||
4460         !isUndefOrEqual(Mask[i+1], i))
4461       return false;
4462
4463   return true;
4464 }
4465
4466 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4467 /// specifies a shuffle of elements that is suitable for input to 256-bit
4468 /// version of MOVDDUP.
4469 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4470   if (!HasFp256 || !VT.is256BitVector())
4471     return false;
4472
4473   unsigned NumElts = VT.getVectorNumElements();
4474   if (NumElts != 4)
4475     return false;
4476
4477   for (unsigned i = 0; i != NumElts/2; ++i)
4478     if (!isUndefOrEqual(Mask[i], 0))
4479       return false;
4480   for (unsigned i = NumElts/2; i != NumElts; ++i)
4481     if (!isUndefOrEqual(Mask[i], NumElts/2))
4482       return false;
4483   return true;
4484 }
4485
4486 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4487 /// specifies a shuffle of elements that is suitable for input to 128-bit
4488 /// version of MOVDDUP.
4489 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4490   if (!VT.is128BitVector())
4491     return false;
4492
4493   unsigned e = VT.getVectorNumElements() / 2;
4494   for (unsigned i = 0; i != e; ++i)
4495     if (!isUndefOrEqual(Mask[i], i))
4496       return false;
4497   for (unsigned i = 0; i != e; ++i)
4498     if (!isUndefOrEqual(Mask[e+i], i))
4499       return false;
4500   return true;
4501 }
4502
4503 /// isVEXTRACTIndex - Return true if the specified
4504 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4505 /// suitable for instruction that extract 128 or 256 bit vectors
4506 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4507   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4508   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4509     return false;
4510
4511   // The index should be aligned on a vecWidth-bit boundary.
4512   uint64_t Index =
4513     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4514
4515   MVT VT = N->getSimpleValueType(0);
4516   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4517   bool Result = (Index * ElSize) % vecWidth == 0;
4518
4519   return Result;
4520 }
4521
4522 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4523 /// operand specifies a subvector insert that is suitable for input to
4524 /// insertion of 128 or 256-bit subvectors
4525 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4526   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4527   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4528     return false;
4529   // The index should be aligned on a vecWidth-bit boundary.
4530   uint64_t Index =
4531     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4532
4533   MVT VT = N->getSimpleValueType(0);
4534   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4535   bool Result = (Index * ElSize) % vecWidth == 0;
4536
4537   return Result;
4538 }
4539
4540 bool X86::isVINSERT128Index(SDNode *N) {
4541   return isVINSERTIndex(N, 128);
4542 }
4543
4544 bool X86::isVINSERT256Index(SDNode *N) {
4545   return isVINSERTIndex(N, 256);
4546 }
4547
4548 bool X86::isVEXTRACT128Index(SDNode *N) {
4549   return isVEXTRACTIndex(N, 128);
4550 }
4551
4552 bool X86::isVEXTRACT256Index(SDNode *N) {
4553   return isVEXTRACTIndex(N, 256);
4554 }
4555
4556 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4557 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4558 /// Handles 128-bit and 256-bit.
4559 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4560   MVT VT = N->getSimpleValueType(0);
4561
4562   assert((VT.getSizeInBits() >= 128) &&
4563          "Unsupported vector type for PSHUF/SHUFP");
4564
4565   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4566   // independently on 128-bit lanes.
4567   unsigned NumElts = VT.getVectorNumElements();
4568   unsigned NumLanes = VT.getSizeInBits()/128;
4569   unsigned NumLaneElts = NumElts/NumLanes;
4570
4571   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4572          "Only supports 2, 4 or 8 elements per lane");
4573
4574   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4575   unsigned Mask = 0;
4576   for (unsigned i = 0; i != NumElts; ++i) {
4577     int Elt = N->getMaskElt(i);
4578     if (Elt < 0) continue;
4579     Elt &= NumLaneElts - 1;
4580     unsigned ShAmt = (i << Shift) % 8;
4581     Mask |= Elt << ShAmt;
4582   }
4583
4584   return Mask;
4585 }
4586
4587 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4588 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4589 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4590   MVT VT = N->getSimpleValueType(0);
4591
4592   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4593          "Unsupported vector type for PSHUFHW");
4594
4595   unsigned NumElts = VT.getVectorNumElements();
4596
4597   unsigned Mask = 0;
4598   for (unsigned l = 0; l != NumElts; l += 8) {
4599     // 8 nodes per lane, but we only care about the last 4.
4600     for (unsigned i = 0; i < 4; ++i) {
4601       int Elt = N->getMaskElt(l+i+4);
4602       if (Elt < 0) continue;
4603       Elt &= 0x3; // only 2-bits.
4604       Mask |= Elt << (i * 2);
4605     }
4606   }
4607
4608   return Mask;
4609 }
4610
4611 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4612 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4613 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4614   MVT VT = N->getSimpleValueType(0);
4615
4616   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4617          "Unsupported vector type for PSHUFHW");
4618
4619   unsigned NumElts = VT.getVectorNumElements();
4620
4621   unsigned Mask = 0;
4622   for (unsigned l = 0; l != NumElts; l += 8) {
4623     // 8 nodes per lane, but we only care about the first 4.
4624     for (unsigned i = 0; i < 4; ++i) {
4625       int Elt = N->getMaskElt(l+i);
4626       if (Elt < 0) continue;
4627       Elt &= 0x3; // only 2-bits
4628       Mask |= Elt << (i * 2);
4629     }
4630   }
4631
4632   return Mask;
4633 }
4634
4635 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4636 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4637 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4638   MVT VT = SVOp->getSimpleValueType(0);
4639   unsigned EltSize = VT.is512BitVector() ? 1 :
4640     VT.getVectorElementType().getSizeInBits() >> 3;
4641
4642   unsigned NumElts = VT.getVectorNumElements();
4643   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4644   unsigned NumLaneElts = NumElts/NumLanes;
4645
4646   int Val = 0;
4647   unsigned i;
4648   for (i = 0; i != NumElts; ++i) {
4649     Val = SVOp->getMaskElt(i);
4650     if (Val >= 0)
4651       break;
4652   }
4653   if (Val >= (int)NumElts)
4654     Val -= NumElts - NumLaneElts;
4655
4656   assert(Val - i > 0 && "PALIGNR imm should be positive");
4657   return (Val - i) * EltSize;
4658 }
4659
4660 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4661   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4662   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4663     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4664
4665   uint64_t Index =
4666     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4667
4668   MVT VecVT = N->getOperand(0).getSimpleValueType();
4669   MVT ElVT = VecVT.getVectorElementType();
4670
4671   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4672   return Index / NumElemsPerChunk;
4673 }
4674
4675 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4676   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4677   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4678     llvm_unreachable("Illegal insert subvector for VINSERT");
4679
4680   uint64_t Index =
4681     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4682
4683   MVT VecVT = N->getSimpleValueType(0);
4684   MVT ElVT = VecVT.getVectorElementType();
4685
4686   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4687   return Index / NumElemsPerChunk;
4688 }
4689
4690 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4691 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4692 /// and VINSERTI128 instructions.
4693 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4694   return getExtractVEXTRACTImmediate(N, 128);
4695 }
4696
4697 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4698 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4699 /// and VINSERTI64x4 instructions.
4700 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4701   return getExtractVEXTRACTImmediate(N, 256);
4702 }
4703
4704 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4705 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4706 /// and VINSERTI128 instructions.
4707 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4708   return getInsertVINSERTImmediate(N, 128);
4709 }
4710
4711 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4712 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4713 /// and VINSERTI64x4 instructions.
4714 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4715   return getInsertVINSERTImmediate(N, 256);
4716 }
4717
4718 /// isZero - Returns true if Elt is a constant integer zero
4719 static bool isZero(SDValue V) {
4720   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4721   return C && C->isNullValue();
4722 }
4723
4724 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4725 /// constant +0.0.
4726 bool X86::isZeroNode(SDValue Elt) {
4727   if (isZero(Elt))
4728     return true;
4729   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4730     return CFP->getValueAPF().isPosZero();
4731   return false;
4732 }
4733
4734 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4735 /// their permute mask.
4736 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4737                                     SelectionDAG &DAG) {
4738   MVT VT = SVOp->getSimpleValueType(0);
4739   unsigned NumElems = VT.getVectorNumElements();
4740   SmallVector<int, 8> MaskVec;
4741
4742   for (unsigned i = 0; i != NumElems; ++i) {
4743     int Idx = SVOp->getMaskElt(i);
4744     if (Idx >= 0) {
4745       if (Idx < (int)NumElems)
4746         Idx += NumElems;
4747       else
4748         Idx -= NumElems;
4749     }
4750     MaskVec.push_back(Idx);
4751   }
4752   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4753                               SVOp->getOperand(0), &MaskVec[0]);
4754 }
4755
4756 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4757 /// match movhlps. The lower half elements should come from upper half of
4758 /// V1 (and in order), and the upper half elements should come from the upper
4759 /// half of V2 (and in order).
4760 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4761   if (!VT.is128BitVector())
4762     return false;
4763   if (VT.getVectorNumElements() != 4)
4764     return false;
4765   for (unsigned i = 0, e = 2; i != e; ++i)
4766     if (!isUndefOrEqual(Mask[i], i+2))
4767       return false;
4768   for (unsigned i = 2; i != 4; ++i)
4769     if (!isUndefOrEqual(Mask[i], i+4))
4770       return false;
4771   return true;
4772 }
4773
4774 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4775 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4776 /// required.
4777 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4778   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4779     return false;
4780   N = N->getOperand(0).getNode();
4781   if (!ISD::isNON_EXTLoad(N))
4782     return false;
4783   if (LD)
4784     *LD = cast<LoadSDNode>(N);
4785   return true;
4786 }
4787
4788 // Test whether the given value is a vector value which will be legalized
4789 // into a load.
4790 static bool WillBeConstantPoolLoad(SDNode *N) {
4791   if (N->getOpcode() != ISD::BUILD_VECTOR)
4792     return false;
4793
4794   // Check for any non-constant elements.
4795   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4796     switch (N->getOperand(i).getNode()->getOpcode()) {
4797     case ISD::UNDEF:
4798     case ISD::ConstantFP:
4799     case ISD::Constant:
4800       break;
4801     default:
4802       return false;
4803     }
4804
4805   // Vectors of all-zeros and all-ones are materialized with special
4806   // instructions rather than being loaded.
4807   return !ISD::isBuildVectorAllZeros(N) &&
4808          !ISD::isBuildVectorAllOnes(N);
4809 }
4810
4811 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4812 /// match movlp{s|d}. The lower half elements should come from lower half of
4813 /// V1 (and in order), and the upper half elements should come from the upper
4814 /// half of V2 (and in order). And since V1 will become the source of the
4815 /// MOVLP, it must be either a vector load or a scalar load to vector.
4816 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4817                                ArrayRef<int> Mask, MVT VT) {
4818   if (!VT.is128BitVector())
4819     return false;
4820
4821   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4822     return false;
4823   // Is V2 is a vector load, don't do this transformation. We will try to use
4824   // load folding shufps op.
4825   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4826     return false;
4827
4828   unsigned NumElems = VT.getVectorNumElements();
4829
4830   if (NumElems != 2 && NumElems != 4)
4831     return false;
4832   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4833     if (!isUndefOrEqual(Mask[i], i))
4834       return false;
4835   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4836     if (!isUndefOrEqual(Mask[i], i+NumElems))
4837       return false;
4838   return true;
4839 }
4840
4841 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4842 /// all the same.
4843 static bool isSplatVector(SDNode *N) {
4844   if (N->getOpcode() != ISD::BUILD_VECTOR)
4845     return false;
4846
4847   SDValue SplatValue = N->getOperand(0);
4848   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4849     if (N->getOperand(i) != SplatValue)
4850       return false;
4851   return true;
4852 }
4853
4854 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4855 /// to an zero vector.
4856 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4857 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4858   SDValue V1 = N->getOperand(0);
4859   SDValue V2 = N->getOperand(1);
4860   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4861   for (unsigned i = 0; i != NumElems; ++i) {
4862     int Idx = N->getMaskElt(i);
4863     if (Idx >= (int)NumElems) {
4864       unsigned Opc = V2.getOpcode();
4865       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4866         continue;
4867       if (Opc != ISD::BUILD_VECTOR ||
4868           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4869         return false;
4870     } else if (Idx >= 0) {
4871       unsigned Opc = V1.getOpcode();
4872       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4873         continue;
4874       if (Opc != ISD::BUILD_VECTOR ||
4875           !X86::isZeroNode(V1.getOperand(Idx)))
4876         return false;
4877     }
4878   }
4879   return true;
4880 }
4881
4882 /// getZeroVector - Returns a vector of specified type with all zero elements.
4883 ///
4884 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4885                              SelectionDAG &DAG, SDLoc dl) {
4886   assert(VT.isVector() && "Expected a vector type");
4887
4888   // Always build SSE zero vectors as <4 x i32> bitcasted
4889   // to their dest type. This ensures they get CSE'd.
4890   SDValue Vec;
4891   if (VT.is128BitVector()) {  // SSE
4892     if (Subtarget->hasSSE2()) {  // SSE2
4893       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4894       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4895     } else { // SSE1
4896       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4897       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4898     }
4899   } else if (VT.is256BitVector()) { // AVX
4900     if (Subtarget->hasInt256()) { // AVX2
4901       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4902       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4903       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4904     } else {
4905       // 256-bit logic and arithmetic instructions in AVX are all
4906       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4907       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4908       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4909       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4910     }
4911   } else if (VT.is512BitVector()) { // AVX-512
4912       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4913       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4914                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4915       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4916   } else if (VT.getScalarType() == MVT::i1) {
4917     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4918     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4919     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4920     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4921   } else
4922     llvm_unreachable("Unexpected vector type");
4923
4924   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4925 }
4926
4927 /// getOnesVector - Returns a vector of specified type with all bits set.
4928 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4929 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4930 /// Then bitcast to their original type, ensuring they get CSE'd.
4931 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4932                              SDLoc dl) {
4933   assert(VT.isVector() && "Expected a vector type");
4934
4935   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4936   SDValue Vec;
4937   if (VT.is256BitVector()) {
4938     if (HasInt256) { // AVX2
4939       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4940       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4941     } else { // AVX
4942       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4943       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4944     }
4945   } else if (VT.is128BitVector()) {
4946     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4947   } else
4948     llvm_unreachable("Unexpected vector type");
4949
4950   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4951 }
4952
4953 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4954 /// that point to V2 points to its first element.
4955 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4956   for (unsigned i = 0; i != NumElems; ++i) {
4957     if (Mask[i] > (int)NumElems) {
4958       Mask[i] = NumElems;
4959     }
4960   }
4961 }
4962
4963 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4964 /// operation of specified width.
4965 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4966                        SDValue V2) {
4967   unsigned NumElems = VT.getVectorNumElements();
4968   SmallVector<int, 8> Mask;
4969   Mask.push_back(NumElems);
4970   for (unsigned i = 1; i != NumElems; ++i)
4971     Mask.push_back(i);
4972   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4973 }
4974
4975 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4976 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4977                           SDValue V2) {
4978   unsigned NumElems = VT.getVectorNumElements();
4979   SmallVector<int, 8> Mask;
4980   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4981     Mask.push_back(i);
4982     Mask.push_back(i + NumElems);
4983   }
4984   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4985 }
4986
4987 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4988 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4989                           SDValue V2) {
4990   unsigned NumElems = VT.getVectorNumElements();
4991   SmallVector<int, 8> Mask;
4992   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4993     Mask.push_back(i + Half);
4994     Mask.push_back(i + NumElems + Half);
4995   }
4996   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4997 }
4998
4999 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5000 // a generic shuffle instruction because the target has no such instructions.
5001 // Generate shuffles which repeat i16 and i8 several times until they can be
5002 // represented by v4f32 and then be manipulated by target suported shuffles.
5003 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5004   MVT VT = V.getSimpleValueType();
5005   int NumElems = VT.getVectorNumElements();
5006   SDLoc dl(V);
5007
5008   while (NumElems > 4) {
5009     if (EltNo < NumElems/2) {
5010       V = getUnpackl(DAG, dl, VT, V, V);
5011     } else {
5012       V = getUnpackh(DAG, dl, VT, V, V);
5013       EltNo -= NumElems/2;
5014     }
5015     NumElems >>= 1;
5016   }
5017   return V;
5018 }
5019
5020 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5021 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5022   MVT VT = V.getSimpleValueType();
5023   SDLoc dl(V);
5024
5025   if (VT.is128BitVector()) {
5026     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5027     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5028     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5029                              &SplatMask[0]);
5030   } else if (VT.is256BitVector()) {
5031     // To use VPERMILPS to splat scalars, the second half of indicies must
5032     // refer to the higher part, which is a duplication of the lower one,
5033     // because VPERMILPS can only handle in-lane permutations.
5034     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5035                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5036
5037     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5038     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5039                              &SplatMask[0]);
5040   } else
5041     llvm_unreachable("Vector size not supported");
5042
5043   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5044 }
5045
5046 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5047 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5048   MVT SrcVT = SV->getSimpleValueType(0);
5049   SDValue V1 = SV->getOperand(0);
5050   SDLoc dl(SV);
5051
5052   int EltNo = SV->getSplatIndex();
5053   int NumElems = SrcVT.getVectorNumElements();
5054   bool Is256BitVec = SrcVT.is256BitVector();
5055
5056   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5057          "Unknown how to promote splat for type");
5058
5059   // Extract the 128-bit part containing the splat element and update
5060   // the splat element index when it refers to the higher register.
5061   if (Is256BitVec) {
5062     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5063     if (EltNo >= NumElems/2)
5064       EltNo -= NumElems/2;
5065   }
5066
5067   // All i16 and i8 vector types can't be used directly by a generic shuffle
5068   // instruction because the target has no such instruction. Generate shuffles
5069   // which repeat i16 and i8 several times until they fit in i32, and then can
5070   // be manipulated by target suported shuffles.
5071   MVT EltVT = SrcVT.getVectorElementType();
5072   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5073     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5074
5075   // Recreate the 256-bit vector and place the same 128-bit vector
5076   // into the low and high part. This is necessary because we want
5077   // to use VPERM* to shuffle the vectors
5078   if (Is256BitVec) {
5079     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5080   }
5081
5082   return getLegalSplat(DAG, V1, EltNo);
5083 }
5084
5085 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5086 /// vector of zero or undef vector.  This produces a shuffle where the low
5087 /// element of V2 is swizzled into the zero/undef vector, landing at element
5088 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5089 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5090                                            bool IsZero,
5091                                            const X86Subtarget *Subtarget,
5092                                            SelectionDAG &DAG) {
5093   MVT VT = V2.getSimpleValueType();
5094   SDValue V1 = IsZero
5095     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5096   unsigned NumElems = VT.getVectorNumElements();
5097   SmallVector<int, 16> MaskVec;
5098   for (unsigned i = 0; i != NumElems; ++i)
5099     // If this is the insertion idx, put the low elt of V2 here.
5100     MaskVec.push_back(i == Idx ? NumElems : i);
5101   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5102 }
5103
5104 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5105 /// target specific opcode. Returns true if the Mask could be calculated.
5106 /// Sets IsUnary to true if only uses one source.
5107 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5108                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5109   unsigned NumElems = VT.getVectorNumElements();
5110   SDValue ImmN;
5111
5112   IsUnary = false;
5113   switch(N->getOpcode()) {
5114   case X86ISD::SHUFP:
5115     ImmN = N->getOperand(N->getNumOperands()-1);
5116     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5117     break;
5118   case X86ISD::UNPCKH:
5119     DecodeUNPCKHMask(VT, Mask);
5120     break;
5121   case X86ISD::UNPCKL:
5122     DecodeUNPCKLMask(VT, Mask);
5123     break;
5124   case X86ISD::MOVHLPS:
5125     DecodeMOVHLPSMask(NumElems, Mask);
5126     break;
5127   case X86ISD::MOVLHPS:
5128     DecodeMOVLHPSMask(NumElems, Mask);
5129     break;
5130   case X86ISD::PALIGNR:
5131     ImmN = N->getOperand(N->getNumOperands()-1);
5132     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5133     break;
5134   case X86ISD::PSHUFD:
5135   case X86ISD::VPERMILP:
5136     ImmN = N->getOperand(N->getNumOperands()-1);
5137     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5138     IsUnary = true;
5139     break;
5140   case X86ISD::PSHUFHW:
5141     ImmN = N->getOperand(N->getNumOperands()-1);
5142     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5143     IsUnary = true;
5144     break;
5145   case X86ISD::PSHUFLW:
5146     ImmN = N->getOperand(N->getNumOperands()-1);
5147     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5148     IsUnary = true;
5149     break;
5150   case X86ISD::VPERMI:
5151     ImmN = N->getOperand(N->getNumOperands()-1);
5152     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5153     IsUnary = true;
5154     break;
5155   case X86ISD::MOVSS:
5156   case X86ISD::MOVSD: {
5157     // The index 0 always comes from the first element of the second source,
5158     // this is why MOVSS and MOVSD are used in the first place. The other
5159     // elements come from the other positions of the first source vector
5160     Mask.push_back(NumElems);
5161     for (unsigned i = 1; i != NumElems; ++i) {
5162       Mask.push_back(i);
5163     }
5164     break;
5165   }
5166   case X86ISD::VPERM2X128:
5167     ImmN = N->getOperand(N->getNumOperands()-1);
5168     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5169     if (Mask.empty()) return false;
5170     break;
5171   case X86ISD::MOVDDUP:
5172   case X86ISD::MOVLHPD:
5173   case X86ISD::MOVLPD:
5174   case X86ISD::MOVLPS:
5175   case X86ISD::MOVSHDUP:
5176   case X86ISD::MOVSLDUP:
5177     // Not yet implemented
5178     return false;
5179   default: llvm_unreachable("unknown target shuffle node");
5180   }
5181
5182   return true;
5183 }
5184
5185 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5186 /// element of the result of the vector shuffle.
5187 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5188                                    unsigned Depth) {
5189   if (Depth == 6)
5190     return SDValue();  // Limit search depth.
5191
5192   SDValue V = SDValue(N, 0);
5193   EVT VT = V.getValueType();
5194   unsigned Opcode = V.getOpcode();
5195
5196   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5197   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5198     int Elt = SV->getMaskElt(Index);
5199
5200     if (Elt < 0)
5201       return DAG.getUNDEF(VT.getVectorElementType());
5202
5203     unsigned NumElems = VT.getVectorNumElements();
5204     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5205                                          : SV->getOperand(1);
5206     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5207   }
5208
5209   // Recurse into target specific vector shuffles to find scalars.
5210   if (isTargetShuffle(Opcode)) {
5211     MVT ShufVT = V.getSimpleValueType();
5212     unsigned NumElems = ShufVT.getVectorNumElements();
5213     SmallVector<int, 16> ShuffleMask;
5214     bool IsUnary;
5215
5216     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5217       return SDValue();
5218
5219     int Elt = ShuffleMask[Index];
5220     if (Elt < 0)
5221       return DAG.getUNDEF(ShufVT.getVectorElementType());
5222
5223     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5224                                          : N->getOperand(1);
5225     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5226                                Depth+1);
5227   }
5228
5229   // Actual nodes that may contain scalar elements
5230   if (Opcode == ISD::BITCAST) {
5231     V = V.getOperand(0);
5232     EVT SrcVT = V.getValueType();
5233     unsigned NumElems = VT.getVectorNumElements();
5234
5235     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5236       return SDValue();
5237   }
5238
5239   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5240     return (Index == 0) ? V.getOperand(0)
5241                         : DAG.getUNDEF(VT.getVectorElementType());
5242
5243   if (V.getOpcode() == ISD::BUILD_VECTOR)
5244     return V.getOperand(Index);
5245
5246   return SDValue();
5247 }
5248
5249 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5250 /// shuffle operation which come from a consecutively from a zero. The
5251 /// search can start in two different directions, from left or right.
5252 /// We count undefs as zeros until PreferredNum is reached.
5253 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5254                                          unsigned NumElems, bool ZerosFromLeft,
5255                                          SelectionDAG &DAG,
5256                                          unsigned PreferredNum = -1U) {
5257   unsigned NumZeros = 0;
5258   for (unsigned i = 0; i != NumElems; ++i) {
5259     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5260     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5261     if (!Elt.getNode())
5262       break;
5263
5264     if (X86::isZeroNode(Elt))
5265       ++NumZeros;
5266     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5267       NumZeros = std::min(NumZeros + 1, PreferredNum);
5268     else
5269       break;
5270   }
5271
5272   return NumZeros;
5273 }
5274
5275 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5276 /// correspond consecutively to elements from one of the vector operands,
5277 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5278 static
5279 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5280                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5281                               unsigned NumElems, unsigned &OpNum) {
5282   bool SeenV1 = false;
5283   bool SeenV2 = false;
5284
5285   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5286     int Idx = SVOp->getMaskElt(i);
5287     // Ignore undef indicies
5288     if (Idx < 0)
5289       continue;
5290
5291     if (Idx < (int)NumElems)
5292       SeenV1 = true;
5293     else
5294       SeenV2 = true;
5295
5296     // Only accept consecutive elements from the same vector
5297     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5298       return false;
5299   }
5300
5301   OpNum = SeenV1 ? 0 : 1;
5302   return true;
5303 }
5304
5305 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5306 /// logical left shift of a vector.
5307 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5308                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5309   unsigned NumElems =
5310     SVOp->getSimpleValueType(0).getVectorNumElements();
5311   unsigned NumZeros = getNumOfConsecutiveZeros(
5312       SVOp, NumElems, false /* check zeros from right */, DAG,
5313       SVOp->getMaskElt(0));
5314   unsigned OpSrc;
5315
5316   if (!NumZeros)
5317     return false;
5318
5319   // Considering the elements in the mask that are not consecutive zeros,
5320   // check if they consecutively come from only one of the source vectors.
5321   //
5322   //               V1 = {X, A, B, C}     0
5323   //                         \  \  \    /
5324   //   vector_shuffle V1, V2 <1, 2, 3, X>
5325   //
5326   if (!isShuffleMaskConsecutive(SVOp,
5327             0,                   // Mask Start Index
5328             NumElems-NumZeros,   // Mask End Index(exclusive)
5329             NumZeros,            // Where to start looking in the src vector
5330             NumElems,            // Number of elements in vector
5331             OpSrc))              // Which source operand ?
5332     return false;
5333
5334   isLeft = false;
5335   ShAmt = NumZeros;
5336   ShVal = SVOp->getOperand(OpSrc);
5337   return true;
5338 }
5339
5340 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5341 /// logical left shift of a vector.
5342 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5343                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5344   unsigned NumElems =
5345     SVOp->getSimpleValueType(0).getVectorNumElements();
5346   unsigned NumZeros = getNumOfConsecutiveZeros(
5347       SVOp, NumElems, true /* check zeros from left */, DAG,
5348       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5349   unsigned OpSrc;
5350
5351   if (!NumZeros)
5352     return false;
5353
5354   // Considering the elements in the mask that are not consecutive zeros,
5355   // check if they consecutively come from only one of the source vectors.
5356   //
5357   //                           0    { A, B, X, X } = V2
5358   //                          / \    /  /
5359   //   vector_shuffle V1, V2 <X, X, 4, 5>
5360   //
5361   if (!isShuffleMaskConsecutive(SVOp,
5362             NumZeros,     // Mask Start Index
5363             NumElems,     // Mask End Index(exclusive)
5364             0,            // Where to start looking in the src vector
5365             NumElems,     // Number of elements in vector
5366             OpSrc))       // Which source operand ?
5367     return false;
5368
5369   isLeft = true;
5370   ShAmt = NumZeros;
5371   ShVal = SVOp->getOperand(OpSrc);
5372   return true;
5373 }
5374
5375 /// isVectorShift - Returns true if the shuffle can be implemented as a
5376 /// logical left or right shift of a vector.
5377 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5378                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5379   // Although the logic below support any bitwidth size, there are no
5380   // shift instructions which handle more than 128-bit vectors.
5381   if (!SVOp->getSimpleValueType(0).is128BitVector())
5382     return false;
5383
5384   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5385       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5386     return true;
5387
5388   return false;
5389 }
5390
5391 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5392 ///
5393 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5394                                        unsigned NumNonZero, unsigned NumZero,
5395                                        SelectionDAG &DAG,
5396                                        const X86Subtarget* Subtarget,
5397                                        const TargetLowering &TLI) {
5398   if (NumNonZero > 8)
5399     return SDValue();
5400
5401   SDLoc dl(Op);
5402   SDValue V;
5403   bool First = true;
5404   for (unsigned i = 0; i < 16; ++i) {
5405     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5406     if (ThisIsNonZero && First) {
5407       if (NumZero)
5408         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5409       else
5410         V = DAG.getUNDEF(MVT::v8i16);
5411       First = false;
5412     }
5413
5414     if ((i & 1) != 0) {
5415       SDValue ThisElt, LastElt;
5416       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5417       if (LastIsNonZero) {
5418         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5419                               MVT::i16, Op.getOperand(i-1));
5420       }
5421       if (ThisIsNonZero) {
5422         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5423         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5424                               ThisElt, DAG.getConstant(8, MVT::i8));
5425         if (LastIsNonZero)
5426           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5427       } else
5428         ThisElt = LastElt;
5429
5430       if (ThisElt.getNode())
5431         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5432                         DAG.getIntPtrConstant(i/2));
5433     }
5434   }
5435
5436   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5437 }
5438
5439 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5440 ///
5441 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5442                                      unsigned NumNonZero, unsigned NumZero,
5443                                      SelectionDAG &DAG,
5444                                      const X86Subtarget* Subtarget,
5445                                      const TargetLowering &TLI) {
5446   if (NumNonZero > 4)
5447     return SDValue();
5448
5449   SDLoc dl(Op);
5450   SDValue V;
5451   bool First = true;
5452   for (unsigned i = 0; i < 8; ++i) {
5453     bool isNonZero = (NonZeros & (1 << i)) != 0;
5454     if (isNonZero) {
5455       if (First) {
5456         if (NumZero)
5457           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5458         else
5459           V = DAG.getUNDEF(MVT::v8i16);
5460         First = false;
5461       }
5462       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5463                       MVT::v8i16, V, Op.getOperand(i),
5464                       DAG.getIntPtrConstant(i));
5465     }
5466   }
5467
5468   return V;
5469 }
5470
5471 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5472 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5473                                      unsigned NonZeros, unsigned NumNonZero,
5474                                      unsigned NumZero, SelectionDAG &DAG,
5475                                      const X86Subtarget *Subtarget,
5476                                      const TargetLowering &TLI) {
5477   // We know there's at least one non-zero element
5478   unsigned FirstNonZeroIdx = 0;
5479   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5480   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5481          X86::isZeroNode(FirstNonZero)) {
5482     ++FirstNonZeroIdx;
5483     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5484   }
5485
5486   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5487       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5488     return SDValue();
5489
5490   SDValue V = FirstNonZero.getOperand(0);
5491   MVT VVT = V.getSimpleValueType();
5492   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5493     return SDValue();
5494
5495   unsigned FirstNonZeroDst =
5496       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5497   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5498   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5499   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5500
5501   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5502     SDValue Elem = Op.getOperand(Idx);
5503     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5504       continue;
5505
5506     // TODO: What else can be here? Deal with it.
5507     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5508       return SDValue();
5509
5510     // TODO: Some optimizations are still possible here
5511     // ex: Getting one element from a vector, and the rest from another.
5512     if (Elem.getOperand(0) != V)
5513       return SDValue();
5514
5515     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5516     if (Dst == Idx)
5517       ++CorrectIdx;
5518     else if (IncorrectIdx == -1U) {
5519       IncorrectIdx = Idx;
5520       IncorrectDst = Dst;
5521     } else
5522       // There was already one element with an incorrect index.
5523       // We can't optimize this case to an insertps.
5524       return SDValue();
5525   }
5526
5527   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5528     SDLoc dl(Op);
5529     EVT VT = Op.getSimpleValueType();
5530     unsigned ElementMoveMask = 0;
5531     if (IncorrectIdx == -1U)
5532       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5533     else
5534       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5535
5536     SDValue InsertpsMask =
5537         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5538     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5539   }
5540
5541   return SDValue();
5542 }
5543
5544 /// getVShift - Return a vector logical shift node.
5545 ///
5546 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5547                          unsigned NumBits, SelectionDAG &DAG,
5548                          const TargetLowering &TLI, SDLoc dl) {
5549   assert(VT.is128BitVector() && "Unknown type for VShift");
5550   EVT ShVT = MVT::v2i64;
5551   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5552   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5553   return DAG.getNode(ISD::BITCAST, dl, VT,
5554                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5555                              DAG.getConstant(NumBits,
5556                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5557 }
5558
5559 static SDValue
5560 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5561
5562   // Check if the scalar load can be widened into a vector load. And if
5563   // the address is "base + cst" see if the cst can be "absorbed" into
5564   // the shuffle mask.
5565   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5566     SDValue Ptr = LD->getBasePtr();
5567     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5568       return SDValue();
5569     EVT PVT = LD->getValueType(0);
5570     if (PVT != MVT::i32 && PVT != MVT::f32)
5571       return SDValue();
5572
5573     int FI = -1;
5574     int64_t Offset = 0;
5575     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5576       FI = FINode->getIndex();
5577       Offset = 0;
5578     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5579                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5580       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5581       Offset = Ptr.getConstantOperandVal(1);
5582       Ptr = Ptr.getOperand(0);
5583     } else {
5584       return SDValue();
5585     }
5586
5587     // FIXME: 256-bit vector instructions don't require a strict alignment,
5588     // improve this code to support it better.
5589     unsigned RequiredAlign = VT.getSizeInBits()/8;
5590     SDValue Chain = LD->getChain();
5591     // Make sure the stack object alignment is at least 16 or 32.
5592     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5593     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5594       if (MFI->isFixedObjectIndex(FI)) {
5595         // Can't change the alignment. FIXME: It's possible to compute
5596         // the exact stack offset and reference FI + adjust offset instead.
5597         // If someone *really* cares about this. That's the way to implement it.
5598         return SDValue();
5599       } else {
5600         MFI->setObjectAlignment(FI, RequiredAlign);
5601       }
5602     }
5603
5604     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5605     // Ptr + (Offset & ~15).
5606     if (Offset < 0)
5607       return SDValue();
5608     if ((Offset % RequiredAlign) & 3)
5609       return SDValue();
5610     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5611     if (StartOffset)
5612       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5613                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5614
5615     int EltNo = (Offset - StartOffset) >> 2;
5616     unsigned NumElems = VT.getVectorNumElements();
5617
5618     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5619     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5620                              LD->getPointerInfo().getWithOffset(StartOffset),
5621                              false, false, false, 0);
5622
5623     SmallVector<int, 8> Mask;
5624     for (unsigned i = 0; i != NumElems; ++i)
5625       Mask.push_back(EltNo);
5626
5627     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5628   }
5629
5630   return SDValue();
5631 }
5632
5633 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5634 /// vector of type 'VT', see if the elements can be replaced by a single large
5635 /// load which has the same value as a build_vector whose operands are 'elts'.
5636 ///
5637 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5638 ///
5639 /// FIXME: we'd also like to handle the case where the last elements are zero
5640 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5641 /// There's even a handy isZeroNode for that purpose.
5642 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5643                                         SDLoc &DL, SelectionDAG &DAG,
5644                                         bool isAfterLegalize) {
5645   EVT EltVT = VT.getVectorElementType();
5646   unsigned NumElems = Elts.size();
5647
5648   LoadSDNode *LDBase = nullptr;
5649   unsigned LastLoadedElt = -1U;
5650
5651   // For each element in the initializer, see if we've found a load or an undef.
5652   // If we don't find an initial load element, or later load elements are
5653   // non-consecutive, bail out.
5654   for (unsigned i = 0; i < NumElems; ++i) {
5655     SDValue Elt = Elts[i];
5656
5657     if (!Elt.getNode() ||
5658         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5659       return SDValue();
5660     if (!LDBase) {
5661       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5662         return SDValue();
5663       LDBase = cast<LoadSDNode>(Elt.getNode());
5664       LastLoadedElt = i;
5665       continue;
5666     }
5667     if (Elt.getOpcode() == ISD::UNDEF)
5668       continue;
5669
5670     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5671     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5672       return SDValue();
5673     LastLoadedElt = i;
5674   }
5675
5676   // If we have found an entire vector of loads and undefs, then return a large
5677   // load of the entire vector width starting at the base pointer.  If we found
5678   // consecutive loads for the low half, generate a vzext_load node.
5679   if (LastLoadedElt == NumElems - 1) {
5680
5681     if (isAfterLegalize &&
5682         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5683       return SDValue();
5684
5685     SDValue NewLd = SDValue();
5686
5687     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5688       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5689                           LDBase->getPointerInfo(),
5690                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5691                           LDBase->isInvariant(), 0);
5692     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5693                         LDBase->getPointerInfo(),
5694                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5695                         LDBase->isInvariant(), LDBase->getAlignment());
5696
5697     if (LDBase->hasAnyUseOfValue(1)) {
5698       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5699                                      SDValue(LDBase, 1),
5700                                      SDValue(NewLd.getNode(), 1));
5701       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5702       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5703                              SDValue(NewLd.getNode(), 1));
5704     }
5705
5706     return NewLd;
5707   }
5708   if (NumElems == 4 && LastLoadedElt == 1 &&
5709       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5710     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5711     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5712     SDValue ResNode =
5713         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5714                                 LDBase->getPointerInfo(),
5715                                 LDBase->getAlignment(),
5716                                 false/*isVolatile*/, true/*ReadMem*/,
5717                                 false/*WriteMem*/);
5718
5719     // Make sure the newly-created LOAD is in the same position as LDBase in
5720     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5721     // update uses of LDBase's output chain to use the TokenFactor.
5722     if (LDBase->hasAnyUseOfValue(1)) {
5723       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5724                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5725       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5726       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5727                              SDValue(ResNode.getNode(), 1));
5728     }
5729
5730     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5731   }
5732   return SDValue();
5733 }
5734
5735 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5736 /// to generate a splat value for the following cases:
5737 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5738 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5739 /// a scalar load, or a constant.
5740 /// The VBROADCAST node is returned when a pattern is found,
5741 /// or SDValue() otherwise.
5742 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5743                                     SelectionDAG &DAG) {
5744   if (!Subtarget->hasFp256())
5745     return SDValue();
5746
5747   MVT VT = Op.getSimpleValueType();
5748   SDLoc dl(Op);
5749
5750   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5751          "Unsupported vector type for broadcast.");
5752
5753   SDValue Ld;
5754   bool ConstSplatVal;
5755
5756   switch (Op.getOpcode()) {
5757     default:
5758       // Unknown pattern found.
5759       return SDValue();
5760
5761     case ISD::BUILD_VECTOR: {
5762       // The BUILD_VECTOR node must be a splat.
5763       if (!isSplatVector(Op.getNode()))
5764         return SDValue();
5765
5766       Ld = Op.getOperand(0);
5767       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5768                      Ld.getOpcode() == ISD::ConstantFP);
5769
5770       // The suspected load node has several users. Make sure that all
5771       // of its users are from the BUILD_VECTOR node.
5772       // Constants may have multiple users.
5773       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5774         return SDValue();
5775       break;
5776     }
5777
5778     case ISD::VECTOR_SHUFFLE: {
5779       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5780
5781       // Shuffles must have a splat mask where the first element is
5782       // broadcasted.
5783       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5784         return SDValue();
5785
5786       SDValue Sc = Op.getOperand(0);
5787       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5788           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5789
5790         if (!Subtarget->hasInt256())
5791           return SDValue();
5792
5793         // Use the register form of the broadcast instruction available on AVX2.
5794         if (VT.getSizeInBits() >= 256)
5795           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5796         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5797       }
5798
5799       Ld = Sc.getOperand(0);
5800       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5801                        Ld.getOpcode() == ISD::ConstantFP);
5802
5803       // The scalar_to_vector node and the suspected
5804       // load node must have exactly one user.
5805       // Constants may have multiple users.
5806
5807       // AVX-512 has register version of the broadcast
5808       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5809         Ld.getValueType().getSizeInBits() >= 32;
5810       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5811           !hasRegVer))
5812         return SDValue();
5813       break;
5814     }
5815   }
5816
5817   bool IsGE256 = (VT.getSizeInBits() >= 256);
5818
5819   // Handle the broadcasting a single constant scalar from the constant pool
5820   // into a vector. On Sandybridge it is still better to load a constant vector
5821   // from the constant pool and not to broadcast it from a scalar.
5822   if (ConstSplatVal && Subtarget->hasInt256()) {
5823     EVT CVT = Ld.getValueType();
5824     assert(!CVT.isVector() && "Must not broadcast a vector type");
5825     unsigned ScalarSize = CVT.getSizeInBits();
5826
5827     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5828       const Constant *C = nullptr;
5829       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5830         C = CI->getConstantIntValue();
5831       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5832         C = CF->getConstantFPValue();
5833
5834       assert(C && "Invalid constant type");
5835
5836       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5837       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5838       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5839       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5840                        MachinePointerInfo::getConstantPool(),
5841                        false, false, false, Alignment);
5842
5843       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5844     }
5845   }
5846
5847   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5848   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5849
5850   // Handle AVX2 in-register broadcasts.
5851   if (!IsLoad && Subtarget->hasInt256() &&
5852       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5853     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5854
5855   // The scalar source must be a normal load.
5856   if (!IsLoad)
5857     return SDValue();
5858
5859   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5860     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5861
5862   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5863   // double since there is no vbroadcastsd xmm
5864   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5865     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5866       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5867   }
5868
5869   // Unsupported broadcast.
5870   return SDValue();
5871 }
5872
5873 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5874 /// underlying vector and index.
5875 ///
5876 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5877 /// index.
5878 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5879                                          SDValue ExtIdx) {
5880   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5881   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5882     return Idx;
5883
5884   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5885   // lowered this:
5886   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5887   // to:
5888   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5889   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5890   //                           undef)
5891   //                       Constant<0>)
5892   // In this case the vector is the extract_subvector expression and the index
5893   // is 2, as specified by the shuffle.
5894   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5895   SDValue ShuffleVec = SVOp->getOperand(0);
5896   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5897   assert(ShuffleVecVT.getVectorElementType() ==
5898          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5899
5900   int ShuffleIdx = SVOp->getMaskElt(Idx);
5901   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5902     ExtractedFromVec = ShuffleVec;
5903     return ShuffleIdx;
5904   }
5905   return Idx;
5906 }
5907
5908 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5909   MVT VT = Op.getSimpleValueType();
5910
5911   // Skip if insert_vec_elt is not supported.
5912   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5913   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5914     return SDValue();
5915
5916   SDLoc DL(Op);
5917   unsigned NumElems = Op.getNumOperands();
5918
5919   SDValue VecIn1;
5920   SDValue VecIn2;
5921   SmallVector<unsigned, 4> InsertIndices;
5922   SmallVector<int, 8> Mask(NumElems, -1);
5923
5924   for (unsigned i = 0; i != NumElems; ++i) {
5925     unsigned Opc = Op.getOperand(i).getOpcode();
5926
5927     if (Opc == ISD::UNDEF)
5928       continue;
5929
5930     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5931       // Quit if more than 1 elements need inserting.
5932       if (InsertIndices.size() > 1)
5933         return SDValue();
5934
5935       InsertIndices.push_back(i);
5936       continue;
5937     }
5938
5939     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5940     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5941     // Quit if non-constant index.
5942     if (!isa<ConstantSDNode>(ExtIdx))
5943       return SDValue();
5944     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5945
5946     // Quit if extracted from vector of different type.
5947     if (ExtractedFromVec.getValueType() != VT)
5948       return SDValue();
5949
5950     if (!VecIn1.getNode())
5951       VecIn1 = ExtractedFromVec;
5952     else if (VecIn1 != ExtractedFromVec) {
5953       if (!VecIn2.getNode())
5954         VecIn2 = ExtractedFromVec;
5955       else if (VecIn2 != ExtractedFromVec)
5956         // Quit if more than 2 vectors to shuffle
5957         return SDValue();
5958     }
5959
5960     if (ExtractedFromVec == VecIn1)
5961       Mask[i] = Idx;
5962     else if (ExtractedFromVec == VecIn2)
5963       Mask[i] = Idx + NumElems;
5964   }
5965
5966   if (!VecIn1.getNode())
5967     return SDValue();
5968
5969   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5970   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5971   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5972     unsigned Idx = InsertIndices[i];
5973     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5974                      DAG.getIntPtrConstant(Idx));
5975   }
5976
5977   return NV;
5978 }
5979
5980 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5981 SDValue
5982 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5983
5984   MVT VT = Op.getSimpleValueType();
5985   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5986          "Unexpected type in LowerBUILD_VECTORvXi1!");
5987
5988   SDLoc dl(Op);
5989   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5990     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5991     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5992     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5993   }
5994
5995   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5996     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5997     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5998     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5999   }
6000
6001   bool AllContants = true;
6002   uint64_t Immediate = 0;
6003   int NonConstIdx = -1;
6004   bool IsSplat = true;
6005   unsigned NumNonConsts = 0;
6006   unsigned NumConsts = 0;
6007   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6008     SDValue In = Op.getOperand(idx);
6009     if (In.getOpcode() == ISD::UNDEF)
6010       continue;
6011     if (!isa<ConstantSDNode>(In)) {
6012       AllContants = false;
6013       NonConstIdx = idx;
6014       NumNonConsts++;
6015     }
6016     else {
6017       NumConsts++;
6018       if (cast<ConstantSDNode>(In)->getZExtValue())
6019       Immediate |= (1ULL << idx);
6020     }
6021     if (In != Op.getOperand(0))
6022       IsSplat = false;
6023   }
6024
6025   if (AllContants) {
6026     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6027       DAG.getConstant(Immediate, MVT::i16));
6028     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6029                        DAG.getIntPtrConstant(0));
6030   }
6031
6032   if (NumNonConsts == 1 && NonConstIdx != 0) {
6033     SDValue DstVec;
6034     if (NumConsts) {
6035       SDValue VecAsImm = DAG.getConstant(Immediate,
6036                                          MVT::getIntegerVT(VT.getSizeInBits()));
6037       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6038     }
6039     else 
6040       DstVec = DAG.getUNDEF(VT);
6041     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6042                        Op.getOperand(NonConstIdx),
6043                        DAG.getIntPtrConstant(NonConstIdx));
6044   }
6045   if (!IsSplat && (NonConstIdx != 0))
6046     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6047   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6048   SDValue Select;
6049   if (IsSplat)
6050     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6051                           DAG.getConstant(-1, SelectVT),
6052                           DAG.getConstant(0, SelectVT));
6053   else
6054     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6055                          DAG.getConstant((Immediate | 1), SelectVT),
6056                          DAG.getConstant(Immediate, SelectVT));
6057   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6058 }
6059
6060 /// \brief Return true if \p N implements a horizontal binop and return the
6061 /// operands for the horizontal binop into V0 and V1.
6062 /// 
6063 /// This is a helper function of PerformBUILD_VECTORCombine.
6064 /// This function checks that the build_vector \p N in input implements a
6065 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6066 /// operation to match.
6067 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6068 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6069 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6070 /// arithmetic sub.
6071 ///
6072 /// This function only analyzes elements of \p N whose indices are
6073 /// in range [BaseIdx, LastIdx).
6074 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6075                               unsigned BaseIdx, unsigned LastIdx,
6076                               SDValue &V0, SDValue &V1) {
6077   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6078   assert(N->getValueType(0).isVector() &&
6079          N->getValueType(0).getVectorNumElements() >= LastIdx &&
6080          "Invalid Vector in input!");
6081   
6082   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6083   bool CanFold = true;
6084   unsigned ExpectedVExtractIdx = BaseIdx;
6085   unsigned NumElts = LastIdx - BaseIdx;
6086
6087   // Check if N implements a horizontal binop.
6088   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6089     SDValue Op = N->getOperand(i + BaseIdx);
6090     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6091
6092     if (!CanFold)
6093       break;
6094
6095     SDValue Op0 = Op.getOperand(0);
6096     SDValue Op1 = Op.getOperand(1);
6097
6098     // Try to match the following pattern:
6099     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6100     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6101         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6102         Op0.getOperand(0) == Op1.getOperand(0) &&
6103         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6104         isa<ConstantSDNode>(Op1.getOperand(1)));
6105     if (!CanFold)
6106       break;
6107
6108     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6109     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6110  
6111     if (i == 0)
6112       V0 = Op0.getOperand(0);
6113     else if (i * 2 == NumElts) {
6114       V1 = Op0.getOperand(0);
6115       ExpectedVExtractIdx = BaseIdx;
6116     }
6117
6118     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6119     if (I0 == ExpectedVExtractIdx)
6120       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6121     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6122       // Try to match the following dag sequence:
6123       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6124       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6125     } else
6126       CanFold = false;
6127
6128     ExpectedVExtractIdx += 2;
6129   }
6130
6131   return CanFold;
6132 }
6133
6134 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6135 /// a concat_vector. 
6136 ///
6137 /// This is a helper function of PerformBUILD_VECTORCombine.
6138 /// This function expects two 256-bit vectors called V0 and V1.
6139 /// At first, each vector is split into two separate 128-bit vectors.
6140 /// Then, the resulting 128-bit vectors are used to implement two
6141 /// horizontal binary operations. 
6142 ///
6143 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6144 ///
6145 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6146 /// the two new horizontal binop.
6147 /// When Mode is set, the first horizontal binop dag node would take as input
6148 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6149 /// horizontal binop dag node would take as input the lower 128-bit of V1
6150 /// and the upper 128-bit of V1.
6151 ///   Example:
6152 ///     HADD V0_LO, V0_HI
6153 ///     HADD V1_LO, V1_HI
6154 ///
6155 /// Otherwise, the first horizontal binop dag node takes as input the lower
6156 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6157 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6158 ///   Example:
6159 ///     HADD V0_LO, V1_LO
6160 ///     HADD V0_HI, V1_HI
6161 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6162                                      SDLoc DL, SelectionDAG &DAG,
6163                                      unsigned X86Opcode, bool Mode) {
6164   EVT VT = V0.getValueType();
6165   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6166          "Invalid nodes in input!");
6167
6168   unsigned NumElts = VT.getVectorNumElements();
6169   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6170   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6171   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6172   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6173   EVT NewVT = V0_LO.getValueType();
6174
6175   SDValue LO, HI;
6176   if (Mode) {
6177     LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6178     HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6179   } else {
6180     LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6181     HI = DAG.getNode(X86Opcode, DL, NewVT, V1_HI, V1_HI);
6182   }
6183
6184   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6185 }
6186
6187 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6188                                           const X86Subtarget *Subtarget) {
6189   SDLoc DL(N);
6190   EVT VT = N->getValueType(0);
6191   unsigned NumElts = VT.getVectorNumElements();
6192   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6193   SDValue InVec0, InVec1;
6194
6195   // Try to match horizontal ADD/SUB.
6196   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6197     // Try to match an SSE3 float HADD/HSUB.
6198     if (isHorizontalBinOp(BV, ISD::FADD, 0, NumElts, InVec0, InVec1))
6199       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6200     
6201     if (isHorizontalBinOp(BV, ISD::FSUB, 0, NumElts, InVec0, InVec1))
6202       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6203   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6204     // Try to match an SSSE3 integer HADD/HSUB.
6205     if (isHorizontalBinOp(BV, ISD::ADD, 0, NumElts, InVec0, InVec1))
6206       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6207     
6208     if (isHorizontalBinOp(BV, ISD::SUB, 0, NumElts, InVec0, InVec1))
6209       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6210   }
6211   
6212   if (!Subtarget->hasAVX())
6213     return SDValue();
6214
6215   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6216     // Try to match an AVX horizontal add/sub of packed single/double
6217     // precision floating point values from 256-bit vectors.
6218     SDValue InVec2, InVec3;
6219     if (isHorizontalBinOp(BV, ISD::FADD, 0, NumElts/2, InVec0, InVec1) &&
6220         isHorizontalBinOp(BV, ISD::FADD, NumElts/2, NumElts, InVec2, InVec3) &&
6221         InVec0.getNode() == InVec2.getNode() &&
6222         InVec1.getNode() == InVec3.getNode())
6223       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6224
6225     if (isHorizontalBinOp(BV, ISD::FSUB, 0, NumElts/2, InVec0, InVec1) &&
6226         isHorizontalBinOp(BV, ISD::FSUB, NumElts/2, NumElts, InVec2, InVec3) &&
6227         InVec0.getNode() == InVec2.getNode() &&
6228         InVec1.getNode() == InVec3.getNode())
6229       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6230   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6231     // Try to match an AVX2 horizontal add/sub of signed integers.
6232     SDValue InVec2, InVec3;
6233     unsigned X86Opcode;
6234     bool CanFold = true;
6235
6236     if (isHorizontalBinOp(BV, ISD::ADD, 0, NumElts/2, InVec0, InVec1) &&
6237         isHorizontalBinOp(BV, ISD::ADD, NumElts/2, NumElts, InVec2, InVec3) &&
6238         InVec0.getNode() == InVec2.getNode() &&
6239         InVec1.getNode() == InVec3.getNode())
6240       X86Opcode = X86ISD::HADD;
6241     else if (isHorizontalBinOp(BV, ISD::SUB, 0, NumElts/2, InVec0, InVec1) &&
6242         isHorizontalBinOp(BV, ISD::SUB, NumElts/2, NumElts, InVec2, InVec3) &&
6243         InVec0.getNode() == InVec2.getNode() &&
6244         InVec1.getNode() == InVec3.getNode())
6245       X86Opcode = X86ISD::HSUB;
6246     else
6247       CanFold = false;
6248
6249     if (CanFold) {
6250       // Fold this build_vector into a single horizontal add/sub.
6251       // Do this only if the target has AVX2.
6252       if (Subtarget->hasAVX2())
6253         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6254  
6255       // Convert this build_vector into a pair of horizontal binop followed by
6256       // a concat vector.
6257       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false);
6258     }
6259   }
6260
6261   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6262        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6263     unsigned X86Opcode;
6264     if (isHorizontalBinOp(BV, ISD::ADD, 0, NumElts, InVec0, InVec1))
6265       X86Opcode = X86ISD::HADD;
6266     else if (isHorizontalBinOp(BV, ISD::SUB, 0, NumElts, InVec0, InVec1))
6267       X86Opcode = X86ISD::HSUB;
6268     else if (isHorizontalBinOp(BV, ISD::FADD, 0, NumElts, InVec0, InVec1))
6269       X86Opcode = X86ISD::FHADD;
6270     else if (isHorizontalBinOp(BV, ISD::FSUB, 0, NumElts, InVec0, InVec1))
6271       X86Opcode = X86ISD::FHSUB;
6272     else
6273       return SDValue();
6274
6275     // Convert this build_vector into two horizontal add/sub followed by
6276     // a concat vector.
6277     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true);
6278   }
6279
6280   return SDValue();
6281 }
6282
6283 SDValue
6284 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6285   SDLoc dl(Op);
6286
6287   MVT VT = Op.getSimpleValueType();
6288   MVT ExtVT = VT.getVectorElementType();
6289   unsigned NumElems = Op.getNumOperands();
6290
6291   // Generate vectors for predicate vectors.
6292   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6293     return LowerBUILD_VECTORvXi1(Op, DAG);
6294
6295   // Vectors containing all zeros can be matched by pxor and xorps later
6296   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6297     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6298     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6299     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6300       return Op;
6301
6302     return getZeroVector(VT, Subtarget, DAG, dl);
6303   }
6304
6305   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6306   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6307   // vpcmpeqd on 256-bit vectors.
6308   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6309     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6310       return Op;
6311
6312     if (!VT.is512BitVector())
6313       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6314   }
6315
6316   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6317   if (Broadcast.getNode())
6318     return Broadcast;
6319
6320   unsigned EVTBits = ExtVT.getSizeInBits();
6321
6322   unsigned NumZero  = 0;
6323   unsigned NumNonZero = 0;
6324   unsigned NonZeros = 0;
6325   bool IsAllConstants = true;
6326   SmallSet<SDValue, 8> Values;
6327   for (unsigned i = 0; i < NumElems; ++i) {
6328     SDValue Elt = Op.getOperand(i);
6329     if (Elt.getOpcode() == ISD::UNDEF)
6330       continue;
6331     Values.insert(Elt);
6332     if (Elt.getOpcode() != ISD::Constant &&
6333         Elt.getOpcode() != ISD::ConstantFP)
6334       IsAllConstants = false;
6335     if (X86::isZeroNode(Elt))
6336       NumZero++;
6337     else {
6338       NonZeros |= (1 << i);
6339       NumNonZero++;
6340     }
6341   }
6342
6343   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6344   if (NumNonZero == 0)
6345     return DAG.getUNDEF(VT);
6346
6347   // Special case for single non-zero, non-undef, element.
6348   if (NumNonZero == 1) {
6349     unsigned Idx = countTrailingZeros(NonZeros);
6350     SDValue Item = Op.getOperand(Idx);
6351
6352     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6353     // the value are obviously zero, truncate the value to i32 and do the
6354     // insertion that way.  Only do this if the value is non-constant or if the
6355     // value is a constant being inserted into element 0.  It is cheaper to do
6356     // a constant pool load than it is to do a movd + shuffle.
6357     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6358         (!IsAllConstants || Idx == 0)) {
6359       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6360         // Handle SSE only.
6361         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6362         EVT VecVT = MVT::v4i32;
6363         unsigned VecElts = 4;
6364
6365         // Truncate the value (which may itself be a constant) to i32, and
6366         // convert it to a vector with movd (S2V+shuffle to zero extend).
6367         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6368         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6369         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6370
6371         // Now we have our 32-bit value zero extended in the low element of
6372         // a vector.  If Idx != 0, swizzle it into place.
6373         if (Idx != 0) {
6374           SmallVector<int, 4> Mask;
6375           Mask.push_back(Idx);
6376           for (unsigned i = 1; i != VecElts; ++i)
6377             Mask.push_back(i);
6378           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6379                                       &Mask[0]);
6380         }
6381         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6382       }
6383     }
6384
6385     // If we have a constant or non-constant insertion into the low element of
6386     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6387     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6388     // depending on what the source datatype is.
6389     if (Idx == 0) {
6390       if (NumZero == 0)
6391         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6392
6393       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6394           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6395         if (VT.is256BitVector() || VT.is512BitVector()) {
6396           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6397           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6398                              Item, DAG.getIntPtrConstant(0));
6399         }
6400         assert(VT.is128BitVector() && "Expected an SSE value type!");
6401         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6402         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6403         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6404       }
6405
6406       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6407         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6408         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6409         if (VT.is256BitVector()) {
6410           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6411           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6412         } else {
6413           assert(VT.is128BitVector() && "Expected an SSE value type!");
6414           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6415         }
6416         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6417       }
6418     }
6419
6420     // Is it a vector logical left shift?
6421     if (NumElems == 2 && Idx == 1 &&
6422         X86::isZeroNode(Op.getOperand(0)) &&
6423         !X86::isZeroNode(Op.getOperand(1))) {
6424       unsigned NumBits = VT.getSizeInBits();
6425       return getVShift(true, VT,
6426                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6427                                    VT, Op.getOperand(1)),
6428                        NumBits/2, DAG, *this, dl);
6429     }
6430
6431     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6432       return SDValue();
6433
6434     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6435     // is a non-constant being inserted into an element other than the low one,
6436     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6437     // movd/movss) to move this into the low element, then shuffle it into
6438     // place.
6439     if (EVTBits == 32) {
6440       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6441
6442       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6443       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6444       SmallVector<int, 8> MaskVec;
6445       for (unsigned i = 0; i != NumElems; ++i)
6446         MaskVec.push_back(i == Idx ? 0 : 1);
6447       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6448     }
6449   }
6450
6451   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6452   if (Values.size() == 1) {
6453     if (EVTBits == 32) {
6454       // Instead of a shuffle like this:
6455       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6456       // Check if it's possible to issue this instead.
6457       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6458       unsigned Idx = countTrailingZeros(NonZeros);
6459       SDValue Item = Op.getOperand(Idx);
6460       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6461         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6462     }
6463     return SDValue();
6464   }
6465
6466   // A vector full of immediates; various special cases are already
6467   // handled, so this is best done with a single constant-pool load.
6468   if (IsAllConstants)
6469     return SDValue();
6470
6471   // For AVX-length vectors, build the individual 128-bit pieces and use
6472   // shuffles to put them in place.
6473   if (VT.is256BitVector() || VT.is512BitVector()) {
6474     SmallVector<SDValue, 64> V;
6475     for (unsigned i = 0; i != NumElems; ++i)
6476       V.push_back(Op.getOperand(i));
6477
6478     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6479
6480     // Build both the lower and upper subvector.
6481     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6482                                 makeArrayRef(&V[0], NumElems/2));
6483     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6484                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6485
6486     // Recreate the wider vector with the lower and upper part.
6487     if (VT.is256BitVector())
6488       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6489     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6490   }
6491
6492   // Let legalizer expand 2-wide build_vectors.
6493   if (EVTBits == 64) {
6494     if (NumNonZero == 1) {
6495       // One half is zero or undef.
6496       unsigned Idx = countTrailingZeros(NonZeros);
6497       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6498                                  Op.getOperand(Idx));
6499       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6500     }
6501     return SDValue();
6502   }
6503
6504   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6505   if (EVTBits == 8 && NumElems == 16) {
6506     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6507                                         Subtarget, *this);
6508     if (V.getNode()) return V;
6509   }
6510
6511   if (EVTBits == 16 && NumElems == 8) {
6512     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6513                                       Subtarget, *this);
6514     if (V.getNode()) return V;
6515   }
6516
6517   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6518   if (EVTBits == 32 && NumElems == 4) {
6519     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6520                                       NumZero, DAG, Subtarget, *this);
6521     if (V.getNode())
6522       return V;
6523   }
6524
6525   // If element VT is == 32 bits, turn it into a number of shuffles.
6526   SmallVector<SDValue, 8> V(NumElems);
6527   if (NumElems == 4 && NumZero > 0) {
6528     for (unsigned i = 0; i < 4; ++i) {
6529       bool isZero = !(NonZeros & (1 << i));
6530       if (isZero)
6531         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6532       else
6533         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6534     }
6535
6536     for (unsigned i = 0; i < 2; ++i) {
6537       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6538         default: break;
6539         case 0:
6540           V[i] = V[i*2];  // Must be a zero vector.
6541           break;
6542         case 1:
6543           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6544           break;
6545         case 2:
6546           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6547           break;
6548         case 3:
6549           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6550           break;
6551       }
6552     }
6553
6554     bool Reverse1 = (NonZeros & 0x3) == 2;
6555     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6556     int MaskVec[] = {
6557       Reverse1 ? 1 : 0,
6558       Reverse1 ? 0 : 1,
6559       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6560       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6561     };
6562     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6563   }
6564
6565   if (Values.size() > 1 && VT.is128BitVector()) {
6566     // Check for a build vector of consecutive loads.
6567     for (unsigned i = 0; i < NumElems; ++i)
6568       V[i] = Op.getOperand(i);
6569
6570     // Check for elements which are consecutive loads.
6571     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6572     if (LD.getNode())
6573       return LD;
6574
6575     // Check for a build vector from mostly shuffle plus few inserting.
6576     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6577     if (Sh.getNode())
6578       return Sh;
6579
6580     // For SSE 4.1, use insertps to put the high elements into the low element.
6581     if (getSubtarget()->hasSSE41()) {
6582       SDValue Result;
6583       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6584         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6585       else
6586         Result = DAG.getUNDEF(VT);
6587
6588       for (unsigned i = 1; i < NumElems; ++i) {
6589         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6590         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6591                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6592       }
6593       return Result;
6594     }
6595
6596     // Otherwise, expand into a number of unpckl*, start by extending each of
6597     // our (non-undef) elements to the full vector width with the element in the
6598     // bottom slot of the vector (which generates no code for SSE).
6599     for (unsigned i = 0; i < NumElems; ++i) {
6600       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6601         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6602       else
6603         V[i] = DAG.getUNDEF(VT);
6604     }
6605
6606     // Next, we iteratively mix elements, e.g. for v4f32:
6607     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6608     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6609     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6610     unsigned EltStride = NumElems >> 1;
6611     while (EltStride != 0) {
6612       for (unsigned i = 0; i < EltStride; ++i) {
6613         // If V[i+EltStride] is undef and this is the first round of mixing,
6614         // then it is safe to just drop this shuffle: V[i] is already in the
6615         // right place, the one element (since it's the first round) being
6616         // inserted as undef can be dropped.  This isn't safe for successive
6617         // rounds because they will permute elements within both vectors.
6618         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6619             EltStride == NumElems/2)
6620           continue;
6621
6622         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6623       }
6624       EltStride >>= 1;
6625     }
6626     return V[0];
6627   }
6628   return SDValue();
6629 }
6630
6631 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6632 // to create 256-bit vectors from two other 128-bit ones.
6633 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6634   SDLoc dl(Op);
6635   MVT ResVT = Op.getSimpleValueType();
6636
6637   assert((ResVT.is256BitVector() ||
6638           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6639
6640   SDValue V1 = Op.getOperand(0);
6641   SDValue V2 = Op.getOperand(1);
6642   unsigned NumElems = ResVT.getVectorNumElements();
6643   if(ResVT.is256BitVector())
6644     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6645
6646   if (Op.getNumOperands() == 4) {
6647     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6648                                 ResVT.getVectorNumElements()/2);
6649     SDValue V3 = Op.getOperand(2);
6650     SDValue V4 = Op.getOperand(3);
6651     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6652       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6653   }
6654   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6655 }
6656
6657 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6658   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6659   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6660          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6661           Op.getNumOperands() == 4)));
6662
6663   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6664   // from two other 128-bit ones.
6665
6666   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6667   return LowerAVXCONCAT_VECTORS(Op, DAG);
6668 }
6669
6670 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6671                         bool hasInt256, unsigned *MaskOut = nullptr) {
6672   MVT EltVT = VT.getVectorElementType();
6673
6674   // There is no blend with immediate in AVX-512.
6675   if (VT.is512BitVector())
6676     return false;
6677
6678   if (!hasSSE41 || EltVT == MVT::i8)
6679     return false;
6680   if (!hasInt256 && VT == MVT::v16i16)
6681     return false;
6682
6683   unsigned MaskValue = 0;
6684   unsigned NumElems = VT.getVectorNumElements();
6685   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6686   unsigned NumLanes = (NumElems - 1) / 8 + 1;
6687   unsigned NumElemsInLane = NumElems / NumLanes;
6688
6689   // Blend for v16i16 should be symetric for the both lanes.
6690   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6691
6692     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6693     int EltIdx = MaskVals[i];
6694
6695     if ((EltIdx < 0 || EltIdx == (int)i) &&
6696         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6697       continue;
6698
6699     if (((unsigned)EltIdx == (i + NumElems)) &&
6700         (SndLaneEltIdx < 0 ||
6701          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6702       MaskValue |= (1 << i);
6703     else
6704       return false;
6705   }
6706
6707   if (MaskOut)
6708     *MaskOut = MaskValue;
6709   return true;
6710 }
6711
6712 // Try to lower a shuffle node into a simple blend instruction.
6713 // This function assumes isBlendMask returns true for this
6714 // SuffleVectorSDNode
6715 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6716                                           unsigned MaskValue,
6717                                           const X86Subtarget *Subtarget,
6718                                           SelectionDAG &DAG) {
6719   MVT VT = SVOp->getSimpleValueType(0);
6720   MVT EltVT = VT.getVectorElementType();
6721   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6722                      Subtarget->hasInt256() && "Trying to lower a "
6723                                                "VECTOR_SHUFFLE to a Blend but "
6724                                                "with the wrong mask"));
6725   SDValue V1 = SVOp->getOperand(0);
6726   SDValue V2 = SVOp->getOperand(1);
6727   SDLoc dl(SVOp);
6728   unsigned NumElems = VT.getVectorNumElements();
6729
6730   // Convert i32 vectors to floating point if it is not AVX2.
6731   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6732   MVT BlendVT = VT;
6733   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6734     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6735                                NumElems);
6736     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6737     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6738   }
6739
6740   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6741                             DAG.getConstant(MaskValue, MVT::i32));
6742   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6743 }
6744
6745 /// In vector type \p VT, return true if the element at index \p InputIdx
6746 /// falls on a different 128-bit lane than \p OutputIdx.
6747 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6748                                      unsigned OutputIdx) {
6749   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6750   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6751 }
6752
6753 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6754 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6755 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6756 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6757 /// zero.
6758 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6759                          SelectionDAG &DAG) {
6760   MVT VT = V1.getSimpleValueType();
6761   assert(VT.is128BitVector() || VT.is256BitVector());
6762
6763   MVT EltVT = VT.getVectorElementType();
6764   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6765   unsigned NumElts = VT.getVectorNumElements();
6766
6767   SmallVector<SDValue, 32> PshufbMask;
6768   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6769     int InputIdx = MaskVals[OutputIdx];
6770     unsigned InputByteIdx;
6771
6772     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6773       InputByteIdx = 0x80;
6774     else {
6775       // Cross lane is not allowed.
6776       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6777         return SDValue();
6778       InputByteIdx = InputIdx * EltSizeInBytes;
6779       // Index is an byte offset within the 128-bit lane.
6780       InputByteIdx &= 0xf;
6781     }
6782
6783     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6784       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6785       if (InputByteIdx != 0x80)
6786         ++InputByteIdx;
6787     }
6788   }
6789
6790   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6791   if (ShufVT != VT)
6792     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6793   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6794                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6795 }
6796
6797 // v8i16 shuffles - Prefer shuffles in the following order:
6798 // 1. [all]   pshuflw, pshufhw, optional move
6799 // 2. [ssse3] 1 x pshufb
6800 // 3. [ssse3] 2 x pshufb + 1 x por
6801 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6802 static SDValue
6803 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6804                          SelectionDAG &DAG) {
6805   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6806   SDValue V1 = SVOp->getOperand(0);
6807   SDValue V2 = SVOp->getOperand(1);
6808   SDLoc dl(SVOp);
6809   SmallVector<int, 8> MaskVals;
6810
6811   // Determine if more than 1 of the words in each of the low and high quadwords
6812   // of the result come from the same quadword of one of the two inputs.  Undef
6813   // mask values count as coming from any quadword, for better codegen.
6814   //
6815   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6816   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6817   unsigned LoQuad[] = { 0, 0, 0, 0 };
6818   unsigned HiQuad[] = { 0, 0, 0, 0 };
6819   // Indices of quads used.
6820   std::bitset<4> InputQuads;
6821   for (unsigned i = 0; i < 8; ++i) {
6822     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6823     int EltIdx = SVOp->getMaskElt(i);
6824     MaskVals.push_back(EltIdx);
6825     if (EltIdx < 0) {
6826       ++Quad[0];
6827       ++Quad[1];
6828       ++Quad[2];
6829       ++Quad[3];
6830       continue;
6831     }
6832     ++Quad[EltIdx / 4];
6833     InputQuads.set(EltIdx / 4);
6834   }
6835
6836   int BestLoQuad = -1;
6837   unsigned MaxQuad = 1;
6838   for (unsigned i = 0; i < 4; ++i) {
6839     if (LoQuad[i] > MaxQuad) {
6840       BestLoQuad = i;
6841       MaxQuad = LoQuad[i];
6842     }
6843   }
6844
6845   int BestHiQuad = -1;
6846   MaxQuad = 1;
6847   for (unsigned i = 0; i < 4; ++i) {
6848     if (HiQuad[i] > MaxQuad) {
6849       BestHiQuad = i;
6850       MaxQuad = HiQuad[i];
6851     }
6852   }
6853
6854   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6855   // of the two input vectors, shuffle them into one input vector so only a
6856   // single pshufb instruction is necessary. If there are more than 2 input
6857   // quads, disable the next transformation since it does not help SSSE3.
6858   bool V1Used = InputQuads[0] || InputQuads[1];
6859   bool V2Used = InputQuads[2] || InputQuads[3];
6860   if (Subtarget->hasSSSE3()) {
6861     if (InputQuads.count() == 2 && V1Used && V2Used) {
6862       BestLoQuad = InputQuads[0] ? 0 : 1;
6863       BestHiQuad = InputQuads[2] ? 2 : 3;
6864     }
6865     if (InputQuads.count() > 2) {
6866       BestLoQuad = -1;
6867       BestHiQuad = -1;
6868     }
6869   }
6870
6871   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6872   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6873   // words from all 4 input quadwords.
6874   SDValue NewV;
6875   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6876     int MaskV[] = {
6877       BestLoQuad < 0 ? 0 : BestLoQuad,
6878       BestHiQuad < 0 ? 1 : BestHiQuad
6879     };
6880     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6881                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6882                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6883     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6884
6885     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6886     // source words for the shuffle, to aid later transformations.
6887     bool AllWordsInNewV = true;
6888     bool InOrder[2] = { true, true };
6889     for (unsigned i = 0; i != 8; ++i) {
6890       int idx = MaskVals[i];
6891       if (idx != (int)i)
6892         InOrder[i/4] = false;
6893       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6894         continue;
6895       AllWordsInNewV = false;
6896       break;
6897     }
6898
6899     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6900     if (AllWordsInNewV) {
6901       for (int i = 0; i != 8; ++i) {
6902         int idx = MaskVals[i];
6903         if (idx < 0)
6904           continue;
6905         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6906         if ((idx != i) && idx < 4)
6907           pshufhw = false;
6908         if ((idx != i) && idx > 3)
6909           pshuflw = false;
6910       }
6911       V1 = NewV;
6912       V2Used = false;
6913       BestLoQuad = 0;
6914       BestHiQuad = 1;
6915     }
6916
6917     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6918     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6919     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6920       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6921       unsigned TargetMask = 0;
6922       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6923                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6924       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6925       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6926                              getShufflePSHUFLWImmediate(SVOp);
6927       V1 = NewV.getOperand(0);
6928       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6929     }
6930   }
6931
6932   // Promote splats to a larger type which usually leads to more efficient code.
6933   // FIXME: Is this true if pshufb is available?
6934   if (SVOp->isSplat())
6935     return PromoteSplat(SVOp, DAG);
6936
6937   // If we have SSSE3, and all words of the result are from 1 input vector,
6938   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6939   // is present, fall back to case 4.
6940   if (Subtarget->hasSSSE3()) {
6941     SmallVector<SDValue,16> pshufbMask;
6942
6943     // If we have elements from both input vectors, set the high bit of the
6944     // shuffle mask element to zero out elements that come from V2 in the V1
6945     // mask, and elements that come from V1 in the V2 mask, so that the two
6946     // results can be OR'd together.
6947     bool TwoInputs = V1Used && V2Used;
6948     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6949     if (!TwoInputs)
6950       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6951
6952     // Calculate the shuffle mask for the second input, shuffle it, and
6953     // OR it with the first shuffled input.
6954     CommuteVectorShuffleMask(MaskVals, 8);
6955     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6956     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6957     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6958   }
6959
6960   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6961   // and update MaskVals with new element order.
6962   std::bitset<8> InOrder;
6963   if (BestLoQuad >= 0) {
6964     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6965     for (int i = 0; i != 4; ++i) {
6966       int idx = MaskVals[i];
6967       if (idx < 0) {
6968         InOrder.set(i);
6969       } else if ((idx / 4) == BestLoQuad) {
6970         MaskV[i] = idx & 3;
6971         InOrder.set(i);
6972       }
6973     }
6974     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6975                                 &MaskV[0]);
6976
6977     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6978       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6979       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6980                                   NewV.getOperand(0),
6981                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6982     }
6983   }
6984
6985   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6986   // and update MaskVals with the new element order.
6987   if (BestHiQuad >= 0) {
6988     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6989     for (unsigned i = 4; i != 8; ++i) {
6990       int idx = MaskVals[i];
6991       if (idx < 0) {
6992         InOrder.set(i);
6993       } else if ((idx / 4) == BestHiQuad) {
6994         MaskV[i] = (idx & 3) + 4;
6995         InOrder.set(i);
6996       }
6997     }
6998     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6999                                 &MaskV[0]);
7000
7001     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7002       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7003       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
7004                                   NewV.getOperand(0),
7005                                   getShufflePSHUFHWImmediate(SVOp), DAG);
7006     }
7007   }
7008
7009   // In case BestHi & BestLo were both -1, which means each quadword has a word
7010   // from each of the four input quadwords, calculate the InOrder bitvector now
7011   // before falling through to the insert/extract cleanup.
7012   if (BestLoQuad == -1 && BestHiQuad == -1) {
7013     NewV = V1;
7014     for (int i = 0; i != 8; ++i)
7015       if (MaskVals[i] < 0 || MaskVals[i] == i)
7016         InOrder.set(i);
7017   }
7018
7019   // The other elements are put in the right place using pextrw and pinsrw.
7020   for (unsigned i = 0; i != 8; ++i) {
7021     if (InOrder[i])
7022       continue;
7023     int EltIdx = MaskVals[i];
7024     if (EltIdx < 0)
7025       continue;
7026     SDValue ExtOp = (EltIdx < 8) ?
7027       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
7028                   DAG.getIntPtrConstant(EltIdx)) :
7029       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
7030                   DAG.getIntPtrConstant(EltIdx - 8));
7031     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
7032                        DAG.getIntPtrConstant(i));
7033   }
7034   return NewV;
7035 }
7036
7037 /// \brief v16i16 shuffles
7038 ///
7039 /// FIXME: We only support generation of a single pshufb currently.  We can
7040 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
7041 /// well (e.g 2 x pshufb + 1 x por).
7042 static SDValue
7043 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
7044   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7045   SDValue V1 = SVOp->getOperand(0);
7046   SDValue V2 = SVOp->getOperand(1);
7047   SDLoc dl(SVOp);
7048
7049   if (V2.getOpcode() != ISD::UNDEF)
7050     return SDValue();
7051
7052   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7053   return getPSHUFB(MaskVals, V1, dl, DAG);
7054 }
7055
7056 // v16i8 shuffles - Prefer shuffles in the following order:
7057 // 1. [ssse3] 1 x pshufb
7058 // 2. [ssse3] 2 x pshufb + 1 x por
7059 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
7060 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
7061                                         const X86Subtarget* Subtarget,
7062                                         SelectionDAG &DAG) {
7063   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7064   SDValue V1 = SVOp->getOperand(0);
7065   SDValue V2 = SVOp->getOperand(1);
7066   SDLoc dl(SVOp);
7067   ArrayRef<int> MaskVals = SVOp->getMask();
7068
7069   // Promote splats to a larger type which usually leads to more efficient code.
7070   // FIXME: Is this true if pshufb is available?
7071   if (SVOp->isSplat())
7072     return PromoteSplat(SVOp, DAG);
7073
7074   // If we have SSSE3, case 1 is generated when all result bytes come from
7075   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
7076   // present, fall back to case 3.
7077
7078   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
7079   if (Subtarget->hasSSSE3()) {
7080     SmallVector<SDValue,16> pshufbMask;
7081
7082     // If all result elements are from one input vector, then only translate
7083     // undef mask values to 0x80 (zero out result) in the pshufb mask.
7084     //
7085     // Otherwise, we have elements from both input vectors, and must zero out
7086     // elements that come from V2 in the first mask, and V1 in the second mask
7087     // so that we can OR them together.
7088     for (unsigned i = 0; i != 16; ++i) {
7089       int EltIdx = MaskVals[i];
7090       if (EltIdx < 0 || EltIdx >= 16)
7091         EltIdx = 0x80;
7092       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7093     }
7094     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
7095                      DAG.getNode(ISD::BUILD_VECTOR, dl,
7096                                  MVT::v16i8, pshufbMask));
7097
7098     // As PSHUFB will zero elements with negative indices, it's safe to ignore
7099     // the 2nd operand if it's undefined or zero.
7100     if (V2.getOpcode() == ISD::UNDEF ||
7101         ISD::isBuildVectorAllZeros(V2.getNode()))
7102       return V1;
7103
7104     // Calculate the shuffle mask for the second input, shuffle it, and
7105     // OR it with the first shuffled input.
7106     pshufbMask.clear();
7107     for (unsigned i = 0; i != 16; ++i) {
7108       int EltIdx = MaskVals[i];
7109       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
7110       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7111     }
7112     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
7113                      DAG.getNode(ISD::BUILD_VECTOR, dl,
7114                                  MVT::v16i8, pshufbMask));
7115     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7116   }
7117
7118   // No SSSE3 - Calculate in place words and then fix all out of place words
7119   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
7120   // the 16 different words that comprise the two doublequadword input vectors.
7121   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7122   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7123   SDValue NewV = V1;
7124   for (int i = 0; i != 8; ++i) {
7125     int Elt0 = MaskVals[i*2];
7126     int Elt1 = MaskVals[i*2+1];
7127
7128     // This word of the result is all undef, skip it.
7129     if (Elt0 < 0 && Elt1 < 0)
7130       continue;
7131
7132     // This word of the result is already in the correct place, skip it.
7133     if ((Elt0 == i*2) && (Elt1 == i*2+1))
7134       continue;
7135
7136     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7137     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7138     SDValue InsElt;
7139
7140     // If Elt0 and Elt1 are defined, are consecutive, and can be load
7141     // using a single extract together, load it and store it.
7142     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7143       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7144                            DAG.getIntPtrConstant(Elt1 / 2));
7145       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7146                         DAG.getIntPtrConstant(i));
7147       continue;
7148     }
7149
7150     // If Elt1 is defined, extract it from the appropriate source.  If the
7151     // source byte is not also odd, shift the extracted word left 8 bits
7152     // otherwise clear the bottom 8 bits if we need to do an or.
7153     if (Elt1 >= 0) {
7154       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7155                            DAG.getIntPtrConstant(Elt1 / 2));
7156       if ((Elt1 & 1) == 0)
7157         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7158                              DAG.getConstant(8,
7159                                   TLI.getShiftAmountTy(InsElt.getValueType())));
7160       else if (Elt0 >= 0)
7161         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7162                              DAG.getConstant(0xFF00, MVT::i16));
7163     }
7164     // If Elt0 is defined, extract it from the appropriate source.  If the
7165     // source byte is not also even, shift the extracted word right 8 bits. If
7166     // Elt1 was also defined, OR the extracted values together before
7167     // inserting them in the result.
7168     if (Elt0 >= 0) {
7169       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7170                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7171       if ((Elt0 & 1) != 0)
7172         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7173                               DAG.getConstant(8,
7174                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
7175       else if (Elt1 >= 0)
7176         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7177                              DAG.getConstant(0x00FF, MVT::i16));
7178       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7179                          : InsElt0;
7180     }
7181     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7182                        DAG.getIntPtrConstant(i));
7183   }
7184   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7185 }
7186
7187 // v32i8 shuffles - Translate to VPSHUFB if possible.
7188 static
7189 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7190                                  const X86Subtarget *Subtarget,
7191                                  SelectionDAG &DAG) {
7192   MVT VT = SVOp->getSimpleValueType(0);
7193   SDValue V1 = SVOp->getOperand(0);
7194   SDValue V2 = SVOp->getOperand(1);
7195   SDLoc dl(SVOp);
7196   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7197
7198   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7199   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7200   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7201
7202   // VPSHUFB may be generated if
7203   // (1) one of input vector is undefined or zeroinitializer.
7204   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7205   // And (2) the mask indexes don't cross the 128-bit lane.
7206   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7207       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7208     return SDValue();
7209
7210   if (V1IsAllZero && !V2IsAllZero) {
7211     CommuteVectorShuffleMask(MaskVals, 32);
7212     V1 = V2;
7213   }
7214   return getPSHUFB(MaskVals, V1, dl, DAG);
7215 }
7216
7217 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7218 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7219 /// done when every pair / quad of shuffle mask elements point to elements in
7220 /// the right sequence. e.g.
7221 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7222 static
7223 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7224                                  SelectionDAG &DAG) {
7225   MVT VT = SVOp->getSimpleValueType(0);
7226   SDLoc dl(SVOp);
7227   unsigned NumElems = VT.getVectorNumElements();
7228   MVT NewVT;
7229   unsigned Scale;
7230   switch (VT.SimpleTy) {
7231   default: llvm_unreachable("Unexpected!");
7232   case MVT::v2i64:
7233   case MVT::v2f64:
7234            return SDValue(SVOp, 0);
7235   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
7236   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
7237   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
7238   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
7239   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7240   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
7241   }
7242
7243   SmallVector<int, 8> MaskVec;
7244   for (unsigned i = 0; i != NumElems; i += Scale) {
7245     int StartIdx = -1;
7246     for (unsigned j = 0; j != Scale; ++j) {
7247       int EltIdx = SVOp->getMaskElt(i+j);
7248       if (EltIdx < 0)
7249         continue;
7250       if (StartIdx < 0)
7251         StartIdx = (EltIdx / Scale);
7252       if (EltIdx != (int)(StartIdx*Scale + j))
7253         return SDValue();
7254     }
7255     MaskVec.push_back(StartIdx);
7256   }
7257
7258   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7259   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7260   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7261 }
7262
7263 /// getVZextMovL - Return a zero-extending vector move low node.
7264 ///
7265 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7266                             SDValue SrcOp, SelectionDAG &DAG,
7267                             const X86Subtarget *Subtarget, SDLoc dl) {
7268   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7269     LoadSDNode *LD = nullptr;
7270     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7271       LD = dyn_cast<LoadSDNode>(SrcOp);
7272     if (!LD) {
7273       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7274       // instead.
7275       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7276       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7277           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7278           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7279           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7280         // PR2108
7281         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7282         return DAG.getNode(ISD::BITCAST, dl, VT,
7283                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7284                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7285                                                    OpVT,
7286                                                    SrcOp.getOperand(0)
7287                                                           .getOperand(0))));
7288       }
7289     }
7290   }
7291
7292   return DAG.getNode(ISD::BITCAST, dl, VT,
7293                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7294                                  DAG.getNode(ISD::BITCAST, dl,
7295                                              OpVT, SrcOp)));
7296 }
7297
7298 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7299 /// which could not be matched by any known target speficic shuffle
7300 static SDValue
7301 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7302
7303   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7304   if (NewOp.getNode())
7305     return NewOp;
7306
7307   MVT VT = SVOp->getSimpleValueType(0);
7308
7309   unsigned NumElems = VT.getVectorNumElements();
7310   unsigned NumLaneElems = NumElems / 2;
7311
7312   SDLoc dl(SVOp);
7313   MVT EltVT = VT.getVectorElementType();
7314   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7315   SDValue Output[2];
7316
7317   SmallVector<int, 16> Mask;
7318   for (unsigned l = 0; l < 2; ++l) {
7319     // Build a shuffle mask for the output, discovering on the fly which
7320     // input vectors to use as shuffle operands (recorded in InputUsed).
7321     // If building a suitable shuffle vector proves too hard, then bail
7322     // out with UseBuildVector set.
7323     bool UseBuildVector = false;
7324     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7325     unsigned LaneStart = l * NumLaneElems;
7326     for (unsigned i = 0; i != NumLaneElems; ++i) {
7327       // The mask element.  This indexes into the input.
7328       int Idx = SVOp->getMaskElt(i+LaneStart);
7329       if (Idx < 0) {
7330         // the mask element does not index into any input vector.
7331         Mask.push_back(-1);
7332         continue;
7333       }
7334
7335       // The input vector this mask element indexes into.
7336       int Input = Idx / NumLaneElems;
7337
7338       // Turn the index into an offset from the start of the input vector.
7339       Idx -= Input * NumLaneElems;
7340
7341       // Find or create a shuffle vector operand to hold this input.
7342       unsigned OpNo;
7343       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7344         if (InputUsed[OpNo] == Input)
7345           // This input vector is already an operand.
7346           break;
7347         if (InputUsed[OpNo] < 0) {
7348           // Create a new operand for this input vector.
7349           InputUsed[OpNo] = Input;
7350           break;
7351         }
7352       }
7353
7354       if (OpNo >= array_lengthof(InputUsed)) {
7355         // More than two input vectors used!  Give up on trying to create a
7356         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7357         UseBuildVector = true;
7358         break;
7359       }
7360
7361       // Add the mask index for the new shuffle vector.
7362       Mask.push_back(Idx + OpNo * NumLaneElems);
7363     }
7364
7365     if (UseBuildVector) {
7366       SmallVector<SDValue, 16> SVOps;
7367       for (unsigned i = 0; i != NumLaneElems; ++i) {
7368         // The mask element.  This indexes into the input.
7369         int Idx = SVOp->getMaskElt(i+LaneStart);
7370         if (Idx < 0) {
7371           SVOps.push_back(DAG.getUNDEF(EltVT));
7372           continue;
7373         }
7374
7375         // The input vector this mask element indexes into.
7376         int Input = Idx / NumElems;
7377
7378         // Turn the index into an offset from the start of the input vector.
7379         Idx -= Input * NumElems;
7380
7381         // Extract the vector element by hand.
7382         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7383                                     SVOp->getOperand(Input),
7384                                     DAG.getIntPtrConstant(Idx)));
7385       }
7386
7387       // Construct the output using a BUILD_VECTOR.
7388       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7389     } else if (InputUsed[0] < 0) {
7390       // No input vectors were used! The result is undefined.
7391       Output[l] = DAG.getUNDEF(NVT);
7392     } else {
7393       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7394                                         (InputUsed[0] % 2) * NumLaneElems,
7395                                         DAG, dl);
7396       // If only one input was used, use an undefined vector for the other.
7397       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7398         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7399                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7400       // At least one input vector was used. Create a new shuffle vector.
7401       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7402     }
7403
7404     Mask.clear();
7405   }
7406
7407   // Concatenate the result back
7408   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7409 }
7410
7411 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7412 /// 4 elements, and match them with several different shuffle types.
7413 static SDValue
7414 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7415   SDValue V1 = SVOp->getOperand(0);
7416   SDValue V2 = SVOp->getOperand(1);
7417   SDLoc dl(SVOp);
7418   MVT VT = SVOp->getSimpleValueType(0);
7419
7420   assert(VT.is128BitVector() && "Unsupported vector size");
7421
7422   std::pair<int, int> Locs[4];
7423   int Mask1[] = { -1, -1, -1, -1 };
7424   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7425
7426   unsigned NumHi = 0;
7427   unsigned NumLo = 0;
7428   for (unsigned i = 0; i != 4; ++i) {
7429     int Idx = PermMask[i];
7430     if (Idx < 0) {
7431       Locs[i] = std::make_pair(-1, -1);
7432     } else {
7433       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7434       if (Idx < 4) {
7435         Locs[i] = std::make_pair(0, NumLo);
7436         Mask1[NumLo] = Idx;
7437         NumLo++;
7438       } else {
7439         Locs[i] = std::make_pair(1, NumHi);
7440         if (2+NumHi < 4)
7441           Mask1[2+NumHi] = Idx;
7442         NumHi++;
7443       }
7444     }
7445   }
7446
7447   if (NumLo <= 2 && NumHi <= 2) {
7448     // If no more than two elements come from either vector. This can be
7449     // implemented with two shuffles. First shuffle gather the elements.
7450     // The second shuffle, which takes the first shuffle as both of its
7451     // vector operands, put the elements into the right order.
7452     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7453
7454     int Mask2[] = { -1, -1, -1, -1 };
7455
7456     for (unsigned i = 0; i != 4; ++i)
7457       if (Locs[i].first != -1) {
7458         unsigned Idx = (i < 2) ? 0 : 4;
7459         Idx += Locs[i].first * 2 + Locs[i].second;
7460         Mask2[i] = Idx;
7461       }
7462
7463     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7464   }
7465
7466   if (NumLo == 3 || NumHi == 3) {
7467     // Otherwise, we must have three elements from one vector, call it X, and
7468     // one element from the other, call it Y.  First, use a shufps to build an
7469     // intermediate vector with the one element from Y and the element from X
7470     // that will be in the same half in the final destination (the indexes don't
7471     // matter). Then, use a shufps to build the final vector, taking the half
7472     // containing the element from Y from the intermediate, and the other half
7473     // from X.
7474     if (NumHi == 3) {
7475       // Normalize it so the 3 elements come from V1.
7476       CommuteVectorShuffleMask(PermMask, 4);
7477       std::swap(V1, V2);
7478     }
7479
7480     // Find the element from V2.
7481     unsigned HiIndex;
7482     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7483       int Val = PermMask[HiIndex];
7484       if (Val < 0)
7485         continue;
7486       if (Val >= 4)
7487         break;
7488     }
7489
7490     Mask1[0] = PermMask[HiIndex];
7491     Mask1[1] = -1;
7492     Mask1[2] = PermMask[HiIndex^1];
7493     Mask1[3] = -1;
7494     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7495
7496     if (HiIndex >= 2) {
7497       Mask1[0] = PermMask[0];
7498       Mask1[1] = PermMask[1];
7499       Mask1[2] = HiIndex & 1 ? 6 : 4;
7500       Mask1[3] = HiIndex & 1 ? 4 : 6;
7501       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7502     }
7503
7504     Mask1[0] = HiIndex & 1 ? 2 : 0;
7505     Mask1[1] = HiIndex & 1 ? 0 : 2;
7506     Mask1[2] = PermMask[2];
7507     Mask1[3] = PermMask[3];
7508     if (Mask1[2] >= 0)
7509       Mask1[2] += 4;
7510     if (Mask1[3] >= 0)
7511       Mask1[3] += 4;
7512     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7513   }
7514
7515   // Break it into (shuffle shuffle_hi, shuffle_lo).
7516   int LoMask[] = { -1, -1, -1, -1 };
7517   int HiMask[] = { -1, -1, -1, -1 };
7518
7519   int *MaskPtr = LoMask;
7520   unsigned MaskIdx = 0;
7521   unsigned LoIdx = 0;
7522   unsigned HiIdx = 2;
7523   for (unsigned i = 0; i != 4; ++i) {
7524     if (i == 2) {
7525       MaskPtr = HiMask;
7526       MaskIdx = 1;
7527       LoIdx = 0;
7528       HiIdx = 2;
7529     }
7530     int Idx = PermMask[i];
7531     if (Idx < 0) {
7532       Locs[i] = std::make_pair(-1, -1);
7533     } else if (Idx < 4) {
7534       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7535       MaskPtr[LoIdx] = Idx;
7536       LoIdx++;
7537     } else {
7538       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7539       MaskPtr[HiIdx] = Idx;
7540       HiIdx++;
7541     }
7542   }
7543
7544   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7545   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7546   int MaskOps[] = { -1, -1, -1, -1 };
7547   for (unsigned i = 0; i != 4; ++i)
7548     if (Locs[i].first != -1)
7549       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7550   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7551 }
7552
7553 static bool MayFoldVectorLoad(SDValue V) {
7554   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7555     V = V.getOperand(0);
7556
7557   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7558     V = V.getOperand(0);
7559   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7560       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7561     // BUILD_VECTOR (load), undef
7562     V = V.getOperand(0);
7563
7564   return MayFoldLoad(V);
7565 }
7566
7567 static
7568 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7569   MVT VT = Op.getSimpleValueType();
7570
7571   // Canonizalize to v2f64.
7572   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7573   return DAG.getNode(ISD::BITCAST, dl, VT,
7574                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7575                                           V1, DAG));
7576 }
7577
7578 static
7579 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7580                         bool HasSSE2) {
7581   SDValue V1 = Op.getOperand(0);
7582   SDValue V2 = Op.getOperand(1);
7583   MVT VT = Op.getSimpleValueType();
7584
7585   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7586
7587   if (HasSSE2 && VT == MVT::v2f64)
7588     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7589
7590   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7591   return DAG.getNode(ISD::BITCAST, dl, VT,
7592                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7593                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7594                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7595 }
7596
7597 static
7598 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7599   SDValue V1 = Op.getOperand(0);
7600   SDValue V2 = Op.getOperand(1);
7601   MVT VT = Op.getSimpleValueType();
7602
7603   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7604          "unsupported shuffle type");
7605
7606   if (V2.getOpcode() == ISD::UNDEF)
7607     V2 = V1;
7608
7609   // v4i32 or v4f32
7610   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7611 }
7612
7613 static
7614 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7615   SDValue V1 = Op.getOperand(0);
7616   SDValue V2 = Op.getOperand(1);
7617   MVT VT = Op.getSimpleValueType();
7618   unsigned NumElems = VT.getVectorNumElements();
7619
7620   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7621   // operand of these instructions is only memory, so check if there's a
7622   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7623   // same masks.
7624   bool CanFoldLoad = false;
7625
7626   // Trivial case, when V2 comes from a load.
7627   if (MayFoldVectorLoad(V2))
7628     CanFoldLoad = true;
7629
7630   // When V1 is a load, it can be folded later into a store in isel, example:
7631   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7632   //    turns into:
7633   //  (MOVLPSmr addr:$src1, VR128:$src2)
7634   // So, recognize this potential and also use MOVLPS or MOVLPD
7635   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7636     CanFoldLoad = true;
7637
7638   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7639   if (CanFoldLoad) {
7640     if (HasSSE2 && NumElems == 2)
7641       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7642
7643     if (NumElems == 4)
7644       // If we don't care about the second element, proceed to use movss.
7645       if (SVOp->getMaskElt(1) != -1)
7646         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7647   }
7648
7649   // movl and movlp will both match v2i64, but v2i64 is never matched by
7650   // movl earlier because we make it strict to avoid messing with the movlp load
7651   // folding logic (see the code above getMOVLP call). Match it here then,
7652   // this is horrible, but will stay like this until we move all shuffle
7653   // matching to x86 specific nodes. Note that for the 1st condition all
7654   // types are matched with movsd.
7655   if (HasSSE2) {
7656     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7657     // as to remove this logic from here, as much as possible
7658     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7659       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7660     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7661   }
7662
7663   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7664
7665   // Invert the operand order and use SHUFPS to match it.
7666   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7667                               getShuffleSHUFImmediate(SVOp), DAG);
7668 }
7669
7670 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7671                                          SelectionDAG &DAG) {
7672   SDLoc dl(Load);
7673   MVT VT = Load->getSimpleValueType(0);
7674   MVT EVT = VT.getVectorElementType();
7675   SDValue Addr = Load->getOperand(1);
7676   SDValue NewAddr = DAG.getNode(
7677       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7678       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7679
7680   SDValue NewLoad =
7681       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7682                   DAG.getMachineFunction().getMachineMemOperand(
7683                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7684   return NewLoad;
7685 }
7686
7687 // It is only safe to call this function if isINSERTPSMask is true for
7688 // this shufflevector mask.
7689 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7690                            SelectionDAG &DAG) {
7691   // Generate an insertps instruction when inserting an f32 from memory onto a
7692   // v4f32 or when copying a member from one v4f32 to another.
7693   // We also use it for transferring i32 from one register to another,
7694   // since it simply copies the same bits.
7695   // If we're transferring an i32 from memory to a specific element in a
7696   // register, we output a generic DAG that will match the PINSRD
7697   // instruction.
7698   MVT VT = SVOp->getSimpleValueType(0);
7699   MVT EVT = VT.getVectorElementType();
7700   SDValue V1 = SVOp->getOperand(0);
7701   SDValue V2 = SVOp->getOperand(1);
7702   auto Mask = SVOp->getMask();
7703   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7704          "unsupported vector type for insertps/pinsrd");
7705
7706   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7707   auto FromV2Predicate = [](const int &i) { return i >= 4; };
7708   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7709
7710   SDValue From;
7711   SDValue To;
7712   unsigned DestIndex;
7713   if (FromV1 == 1) {
7714     From = V1;
7715     To = V2;
7716     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7717                 Mask.begin();
7718   } else {
7719     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7720            "More than one element from V1 and from V2, or no elements from one "
7721            "of the vectors. This case should not have returned true from "
7722            "isINSERTPSMask");
7723     From = V2;
7724     To = V1;
7725     DestIndex =
7726         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7727   }
7728
7729   if (MayFoldLoad(From)) {
7730     // Trivial case, when From comes from a load and is only used by the
7731     // shuffle. Make it use insertps from the vector that we need from that
7732     // load.
7733     SDValue NewLoad =
7734         NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7735     if (!NewLoad.getNode())
7736       return SDValue();
7737
7738     if (EVT == MVT::f32) {
7739       // Create this as a scalar to vector to match the instruction pattern.
7740       SDValue LoadScalarToVector =
7741           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7742       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7743       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7744                          InsertpsMask);
7745     } else { // EVT == MVT::i32
7746       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7747       // instruction, to match the PINSRD instruction, which loads an i32 to a
7748       // certain vector element.
7749       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7750                          DAG.getConstant(DestIndex, MVT::i32));
7751     }
7752   }
7753
7754   // Vector-element-to-vector
7755   unsigned SrcIndex = Mask[DestIndex] % 4;
7756   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7757   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7758 }
7759
7760 // Reduce a vector shuffle to zext.
7761 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7762                                     SelectionDAG &DAG) {
7763   // PMOVZX is only available from SSE41.
7764   if (!Subtarget->hasSSE41())
7765     return SDValue();
7766
7767   MVT VT = Op.getSimpleValueType();
7768
7769   // Only AVX2 support 256-bit vector integer extending.
7770   if (!Subtarget->hasInt256() && VT.is256BitVector())
7771     return SDValue();
7772
7773   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7774   SDLoc DL(Op);
7775   SDValue V1 = Op.getOperand(0);
7776   SDValue V2 = Op.getOperand(1);
7777   unsigned NumElems = VT.getVectorNumElements();
7778
7779   // Extending is an unary operation and the element type of the source vector
7780   // won't be equal to or larger than i64.
7781   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7782       VT.getVectorElementType() == MVT::i64)
7783     return SDValue();
7784
7785   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7786   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7787   while ((1U << Shift) < NumElems) {
7788     if (SVOp->getMaskElt(1U << Shift) == 1)
7789       break;
7790     Shift += 1;
7791     // The maximal ratio is 8, i.e. from i8 to i64.
7792     if (Shift > 3)
7793       return SDValue();
7794   }
7795
7796   // Check the shuffle mask.
7797   unsigned Mask = (1U << Shift) - 1;
7798   for (unsigned i = 0; i != NumElems; ++i) {
7799     int EltIdx = SVOp->getMaskElt(i);
7800     if ((i & Mask) != 0 && EltIdx != -1)
7801       return SDValue();
7802     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7803       return SDValue();
7804   }
7805
7806   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7807   MVT NeVT = MVT::getIntegerVT(NBits);
7808   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7809
7810   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7811     return SDValue();
7812
7813   // Simplify the operand as it's prepared to be fed into shuffle.
7814   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7815   if (V1.getOpcode() == ISD::BITCAST &&
7816       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7817       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7818       V1.getOperand(0).getOperand(0)
7819         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7820     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7821     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7822     ConstantSDNode *CIdx =
7823       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7824     // If it's foldable, i.e. normal load with single use, we will let code
7825     // selection to fold it. Otherwise, we will short the conversion sequence.
7826     if (CIdx && CIdx->getZExtValue() == 0 &&
7827         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7828       MVT FullVT = V.getSimpleValueType();
7829       MVT V1VT = V1.getSimpleValueType();
7830       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7831         // The "ext_vec_elt" node is wider than the result node.
7832         // In this case we should extract subvector from V.
7833         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7834         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7835         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7836                                         FullVT.getVectorNumElements()/Ratio);
7837         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7838                         DAG.getIntPtrConstant(0));
7839       }
7840       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7841     }
7842   }
7843
7844   return DAG.getNode(ISD::BITCAST, DL, VT,
7845                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7846 }
7847
7848 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7849                                       SelectionDAG &DAG) {
7850   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7851   MVT VT = Op.getSimpleValueType();
7852   SDLoc dl(Op);
7853   SDValue V1 = Op.getOperand(0);
7854   SDValue V2 = Op.getOperand(1);
7855
7856   if (isZeroShuffle(SVOp))
7857     return getZeroVector(VT, Subtarget, DAG, dl);
7858
7859   // Handle splat operations
7860   if (SVOp->isSplat()) {
7861     // Use vbroadcast whenever the splat comes from a foldable load
7862     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7863     if (Broadcast.getNode())
7864       return Broadcast;
7865   }
7866
7867   // Check integer expanding shuffles.
7868   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7869   if (NewOp.getNode())
7870     return NewOp;
7871
7872   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7873   // do it!
7874   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7875       VT == MVT::v32i8) {
7876     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7877     if (NewOp.getNode())
7878       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7879   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7880     // FIXME: Figure out a cleaner way to do this.
7881     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7882       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7883       if (NewOp.getNode()) {
7884         MVT NewVT = NewOp.getSimpleValueType();
7885         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7886                                NewVT, true, false))
7887           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7888                               dl);
7889       }
7890     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7891       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7892       if (NewOp.getNode()) {
7893         MVT NewVT = NewOp.getSimpleValueType();
7894         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7895           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7896                               dl);
7897       }
7898     }
7899   }
7900   return SDValue();
7901 }
7902
7903 SDValue
7904 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7905   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7906   SDValue V1 = Op.getOperand(0);
7907   SDValue V2 = Op.getOperand(1);
7908   MVT VT = Op.getSimpleValueType();
7909   SDLoc dl(Op);
7910   unsigned NumElems = VT.getVectorNumElements();
7911   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7912   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7913   bool V1IsSplat = false;
7914   bool V2IsSplat = false;
7915   bool HasSSE2 = Subtarget->hasSSE2();
7916   bool HasFp256    = Subtarget->hasFp256();
7917   bool HasInt256   = Subtarget->hasInt256();
7918   MachineFunction &MF = DAG.getMachineFunction();
7919   bool OptForSize = MF.getFunction()->getAttributes().
7920     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7921
7922   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7923
7924   if (V1IsUndef && V2IsUndef)
7925     return DAG.getUNDEF(VT);
7926
7927   // When we create a shuffle node we put the UNDEF node to second operand,
7928   // but in some cases the first operand may be transformed to UNDEF.
7929   // In this case we should just commute the node.
7930   if (V1IsUndef)
7931     return CommuteVectorShuffle(SVOp, DAG);
7932
7933   // Vector shuffle lowering takes 3 steps:
7934   //
7935   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7936   //    narrowing and commutation of operands should be handled.
7937   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7938   //    shuffle nodes.
7939   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7940   //    so the shuffle can be broken into other shuffles and the legalizer can
7941   //    try the lowering again.
7942   //
7943   // The general idea is that no vector_shuffle operation should be left to
7944   // be matched during isel, all of them must be converted to a target specific
7945   // node here.
7946
7947   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7948   // narrowing and commutation of operands should be handled. The actual code
7949   // doesn't include all of those, work in progress...
7950   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7951   if (NewOp.getNode())
7952     return NewOp;
7953
7954   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7955
7956   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7957   // unpckh_undef). Only use pshufd if speed is more important than size.
7958   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7959     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7960   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7961     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7962
7963   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7964       V2IsUndef && MayFoldVectorLoad(V1))
7965     return getMOVDDup(Op, dl, V1, DAG);
7966
7967   if (isMOVHLPS_v_undef_Mask(M, VT))
7968     return getMOVHighToLow(Op, dl, DAG);
7969
7970   // Use to match splats
7971   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7972       (VT == MVT::v2f64 || VT == MVT::v2i64))
7973     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7974
7975   if (isPSHUFDMask(M, VT)) {
7976     // The actual implementation will match the mask in the if above and then
7977     // during isel it can match several different instructions, not only pshufd
7978     // as its name says, sad but true, emulate the behavior for now...
7979     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7980       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7981
7982     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7983
7984     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7985       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7986
7987     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7988       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7989                                   DAG);
7990
7991     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7992                                 TargetMask, DAG);
7993   }
7994
7995   if (isPALIGNRMask(M, VT, Subtarget))
7996     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7997                                 getShufflePALIGNRImmediate(SVOp),
7998                                 DAG);
7999
8000   // Check if this can be converted into a logical shift.
8001   bool isLeft = false;
8002   unsigned ShAmt = 0;
8003   SDValue ShVal;
8004   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
8005   if (isShift && ShVal.hasOneUse()) {
8006     // If the shifted value has multiple uses, it may be cheaper to use
8007     // v_set0 + movlhps or movhlps, etc.
8008     MVT EltVT = VT.getVectorElementType();
8009     ShAmt *= EltVT.getSizeInBits();
8010     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8011   }
8012
8013   if (isMOVLMask(M, VT)) {
8014     if (ISD::isBuildVectorAllZeros(V1.getNode()))
8015       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
8016     if (!isMOVLPMask(M, VT)) {
8017       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
8018         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8019
8020       if (VT == MVT::v4i32 || VT == MVT::v4f32)
8021         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8022     }
8023   }
8024
8025   // FIXME: fold these into legal mask.
8026   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
8027     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
8028
8029   if (isMOVHLPSMask(M, VT))
8030     return getMOVHighToLow(Op, dl, DAG);
8031
8032   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
8033     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
8034
8035   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
8036     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
8037
8038   if (isMOVLPMask(M, VT))
8039     return getMOVLP(Op, dl, DAG, HasSSE2);
8040
8041   if (ShouldXformToMOVHLPS(M, VT) ||
8042       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
8043     return CommuteVectorShuffle(SVOp, DAG);
8044
8045   if (isShift) {
8046     // No better options. Use a vshldq / vsrldq.
8047     MVT EltVT = VT.getVectorElementType();
8048     ShAmt *= EltVT.getSizeInBits();
8049     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8050   }
8051
8052   bool Commuted = false;
8053   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
8054   // 1,1,1,1 -> v8i16 though.
8055   V1IsSplat = isSplatVector(V1.getNode());
8056   V2IsSplat = isSplatVector(V2.getNode());
8057
8058   // Canonicalize the splat or undef, if present, to be on the RHS.
8059   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
8060     CommuteVectorShuffleMask(M, NumElems);
8061     std::swap(V1, V2);
8062     std::swap(V1IsSplat, V2IsSplat);
8063     Commuted = true;
8064   }
8065
8066   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
8067     // Shuffling low element of v1 into undef, just return v1.
8068     if (V2IsUndef)
8069       return V1;
8070     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
8071     // the instruction selector will not match, so get a canonical MOVL with
8072     // swapped operands to undo the commute.
8073     return getMOVL(DAG, dl, VT, V2, V1);
8074   }
8075
8076   if (isUNPCKLMask(M, VT, HasInt256))
8077     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8078
8079   if (isUNPCKHMask(M, VT, HasInt256))
8080     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8081
8082   if (V2IsSplat) {
8083     // Normalize mask so all entries that point to V2 points to its first
8084     // element then try to match unpck{h|l} again. If match, return a
8085     // new vector_shuffle with the corrected mask.p
8086     SmallVector<int, 8> NewMask(M.begin(), M.end());
8087     NormalizeMask(NewMask, NumElems);
8088     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
8089       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8090     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
8091       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8092   }
8093
8094   if (Commuted) {
8095     // Commute is back and try unpck* again.
8096     // FIXME: this seems wrong.
8097     CommuteVectorShuffleMask(M, NumElems);
8098     std::swap(V1, V2);
8099     std::swap(V1IsSplat, V2IsSplat);
8100
8101     if (isUNPCKLMask(M, VT, HasInt256))
8102       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8103
8104     if (isUNPCKHMask(M, VT, HasInt256))
8105       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8106   }
8107
8108   // Normalize the node to match x86 shuffle ops if needed
8109   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
8110     return CommuteVectorShuffle(SVOp, DAG);
8111
8112   // The checks below are all present in isShuffleMaskLegal, but they are
8113   // inlined here right now to enable us to directly emit target specific
8114   // nodes, and remove one by one until they don't return Op anymore.
8115
8116   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
8117       SVOp->getSplatIndex() == 0 && V2IsUndef) {
8118     if (VT == MVT::v2f64 || VT == MVT::v2i64)
8119       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8120   }
8121
8122   if (isPSHUFHWMask(M, VT, HasInt256))
8123     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8124                                 getShufflePSHUFHWImmediate(SVOp),
8125                                 DAG);
8126
8127   if (isPSHUFLWMask(M, VT, HasInt256))
8128     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8129                                 getShufflePSHUFLWImmediate(SVOp),
8130                                 DAG);
8131
8132   if (isSHUFPMask(M, VT))
8133     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8134                                 getShuffleSHUFImmediate(SVOp), DAG);
8135
8136   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8137     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8138   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8139     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8140
8141   //===--------------------------------------------------------------------===//
8142   // Generate target specific nodes for 128 or 256-bit shuffles only
8143   // supported in the AVX instruction set.
8144   //
8145
8146   // Handle VMOVDDUPY permutations
8147   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8148     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8149
8150   // Handle VPERMILPS/D* permutations
8151   if (isVPERMILPMask(M, VT)) {
8152     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8153       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8154                                   getShuffleSHUFImmediate(SVOp), DAG);
8155     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8156                                 getShuffleSHUFImmediate(SVOp), DAG);
8157   }
8158
8159   unsigned Idx;
8160   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8161     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8162                               Idx*(NumElems/2), DAG, dl);
8163
8164   // Handle VPERM2F128/VPERM2I128 permutations
8165   if (isVPERM2X128Mask(M, VT, HasFp256))
8166     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8167                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8168
8169   unsigned MaskValue;
8170   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8171                   &MaskValue))
8172     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8173
8174   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8175     return getINSERTPS(SVOp, dl, DAG);
8176
8177   unsigned Imm8;
8178   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8179     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8180
8181   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8182       VT.is512BitVector()) {
8183     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8184     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8185     SmallVector<SDValue, 16> permclMask;
8186     for (unsigned i = 0; i != NumElems; ++i) {
8187       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8188     }
8189
8190     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8191     if (V2IsUndef)
8192       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8193       return DAG.getNode(X86ISD::VPERMV, dl, VT,
8194                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8195     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8196                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8197   }
8198
8199   //===--------------------------------------------------------------------===//
8200   // Since no target specific shuffle was selected for this generic one,
8201   // lower it into other known shuffles. FIXME: this isn't true yet, but
8202   // this is the plan.
8203   //
8204
8205   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8206   if (VT == MVT::v8i16) {
8207     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8208     if (NewOp.getNode())
8209       return NewOp;
8210   }
8211
8212   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8213     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8214     if (NewOp.getNode())
8215       return NewOp;
8216   }
8217
8218   if (VT == MVT::v16i8) {
8219     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8220     if (NewOp.getNode())
8221       return NewOp;
8222   }
8223
8224   if (VT == MVT::v32i8) {
8225     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8226     if (NewOp.getNode())
8227       return NewOp;
8228   }
8229
8230   // Handle all 128-bit wide vectors with 4 elements, and match them with
8231   // several different shuffle types.
8232   if (NumElems == 4 && VT.is128BitVector())
8233     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8234
8235   // Handle general 256-bit shuffles
8236   if (VT.is256BitVector())
8237     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8238
8239   return SDValue();
8240 }
8241
8242 // This function assumes its argument is a BUILD_VECTOR of constants or
8243 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8244 // true.
8245 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8246                                     unsigned &MaskValue) {
8247   MaskValue = 0;
8248   unsigned NumElems = BuildVector->getNumOperands();
8249   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8250   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8251   unsigned NumElemsInLane = NumElems / NumLanes;
8252
8253   // Blend for v16i16 should be symetric for the both lanes.
8254   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8255     SDValue EltCond = BuildVector->getOperand(i);
8256     SDValue SndLaneEltCond =
8257         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8258
8259     int Lane1Cond = -1, Lane2Cond = -1;
8260     if (isa<ConstantSDNode>(EltCond))
8261       Lane1Cond = !isZero(EltCond);
8262     if (isa<ConstantSDNode>(SndLaneEltCond))
8263       Lane2Cond = !isZero(SndLaneEltCond);
8264
8265     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8266       // Lane1Cond != 0, means we want the first argument.
8267       // Lane1Cond == 0, means we want the second argument.
8268       // The encoding of this argument is 0 for the first argument, 1
8269       // for the second. Therefore, invert the condition.
8270       MaskValue |= !Lane1Cond << i;
8271     else if (Lane1Cond < 0)
8272       MaskValue |= !Lane2Cond << i;
8273     else
8274       return false;
8275   }
8276   return true;
8277 }
8278
8279 // Try to lower a vselect node into a simple blend instruction.
8280 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8281                                    SelectionDAG &DAG) {
8282   SDValue Cond = Op.getOperand(0);
8283   SDValue LHS = Op.getOperand(1);
8284   SDValue RHS = Op.getOperand(2);
8285   SDLoc dl(Op);
8286   MVT VT = Op.getSimpleValueType();
8287   MVT EltVT = VT.getVectorElementType();
8288   unsigned NumElems = VT.getVectorNumElements();
8289
8290   // There is no blend with immediate in AVX-512.
8291   if (VT.is512BitVector())
8292     return SDValue();
8293
8294   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8295     return SDValue();
8296   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8297     return SDValue();
8298
8299   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8300     return SDValue();
8301
8302   // Check the mask for BLEND and build the value.
8303   unsigned MaskValue = 0;
8304   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8305     return SDValue();
8306
8307   // Convert i32 vectors to floating point if it is not AVX2.
8308   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8309   MVT BlendVT = VT;
8310   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8311     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8312                                NumElems);
8313     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8314     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8315   }
8316
8317   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8318                             DAG.getConstant(MaskValue, MVT::i32));
8319   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8320 }
8321
8322 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8323   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8324   if (BlendOp.getNode())
8325     return BlendOp;
8326
8327   // Some types for vselect were previously set to Expand, not Legal or
8328   // Custom. Return an empty SDValue so we fall-through to Expand, after
8329   // the Custom lowering phase.
8330   MVT VT = Op.getSimpleValueType();
8331   switch (VT.SimpleTy) {
8332   default:
8333     break;
8334   case MVT::v8i16:
8335   case MVT::v16i16:
8336     return SDValue();
8337   }
8338
8339   // We couldn't create a "Blend with immediate" node.
8340   // This node should still be legal, but we'll have to emit a blendv*
8341   // instruction.
8342   return Op;
8343 }
8344
8345 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8346   MVT VT = Op.getSimpleValueType();
8347   SDLoc dl(Op);
8348
8349   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8350     return SDValue();
8351
8352   if (VT.getSizeInBits() == 8) {
8353     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8354                                   Op.getOperand(0), Op.getOperand(1));
8355     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8356                                   DAG.getValueType(VT));
8357     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8358   }
8359
8360   if (VT.getSizeInBits() == 16) {
8361     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8362     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8363     if (Idx == 0)
8364       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8365                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8366                                      DAG.getNode(ISD::BITCAST, dl,
8367                                                  MVT::v4i32,
8368                                                  Op.getOperand(0)),
8369                                      Op.getOperand(1)));
8370     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8371                                   Op.getOperand(0), Op.getOperand(1));
8372     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8373                                   DAG.getValueType(VT));
8374     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8375   }
8376
8377   if (VT == MVT::f32) {
8378     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8379     // the result back to FR32 register. It's only worth matching if the
8380     // result has a single use which is a store or a bitcast to i32.  And in
8381     // the case of a store, it's not worth it if the index is a constant 0,
8382     // because a MOVSSmr can be used instead, which is smaller and faster.
8383     if (!Op.hasOneUse())
8384       return SDValue();
8385     SDNode *User = *Op.getNode()->use_begin();
8386     if ((User->getOpcode() != ISD::STORE ||
8387          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8388           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8389         (User->getOpcode() != ISD::BITCAST ||
8390          User->getValueType(0) != MVT::i32))
8391       return SDValue();
8392     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8393                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8394                                               Op.getOperand(0)),
8395                                               Op.getOperand(1));
8396     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8397   }
8398
8399   if (VT == MVT::i32 || VT == MVT::i64) {
8400     // ExtractPS/pextrq works with constant index.
8401     if (isa<ConstantSDNode>(Op.getOperand(1)))
8402       return Op;
8403   }
8404   return SDValue();
8405 }
8406
8407 /// Extract one bit from mask vector, like v16i1 or v8i1.
8408 /// AVX-512 feature.
8409 SDValue
8410 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8411   SDValue Vec = Op.getOperand(0);
8412   SDLoc dl(Vec);
8413   MVT VecVT = Vec.getSimpleValueType();
8414   SDValue Idx = Op.getOperand(1);
8415   MVT EltVT = Op.getSimpleValueType();
8416
8417   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8418
8419   // variable index can't be handled in mask registers,
8420   // extend vector to VR512
8421   if (!isa<ConstantSDNode>(Idx)) {
8422     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8423     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8424     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8425                               ExtVT.getVectorElementType(), Ext, Idx);
8426     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8427   }
8428
8429   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8430   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8431   unsigned MaxSift = rc->getSize()*8 - 1;
8432   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8433                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8434   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8435                     DAG.getConstant(MaxSift, MVT::i8));
8436   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8437                        DAG.getIntPtrConstant(0));
8438 }
8439
8440 SDValue
8441 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8442                                            SelectionDAG &DAG) const {
8443   SDLoc dl(Op);
8444   SDValue Vec = Op.getOperand(0);
8445   MVT VecVT = Vec.getSimpleValueType();
8446   SDValue Idx = Op.getOperand(1);
8447
8448   if (Op.getSimpleValueType() == MVT::i1)
8449     return ExtractBitFromMaskVector(Op, DAG);
8450
8451   if (!isa<ConstantSDNode>(Idx)) {
8452     if (VecVT.is512BitVector() ||
8453         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8454          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8455
8456       MVT MaskEltVT =
8457         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8458       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8459                                     MaskEltVT.getSizeInBits());
8460
8461       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8462       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8463                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8464                                 Idx, DAG.getConstant(0, getPointerTy()));
8465       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8466       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8467                         Perm, DAG.getConstant(0, getPointerTy()));
8468     }
8469     return SDValue();
8470   }
8471
8472   // If this is a 256-bit vector result, first extract the 128-bit vector and
8473   // then extract the element from the 128-bit vector.
8474   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8475
8476     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8477     // Get the 128-bit vector.
8478     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8479     MVT EltVT = VecVT.getVectorElementType();
8480
8481     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8482
8483     //if (IdxVal >= NumElems/2)
8484     //  IdxVal -= NumElems/2;
8485     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8486     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8487                        DAG.getConstant(IdxVal, MVT::i32));
8488   }
8489
8490   assert(VecVT.is128BitVector() && "Unexpected vector length");
8491
8492   if (Subtarget->hasSSE41()) {
8493     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8494     if (Res.getNode())
8495       return Res;
8496   }
8497
8498   MVT VT = Op.getSimpleValueType();
8499   // TODO: handle v16i8.
8500   if (VT.getSizeInBits() == 16) {
8501     SDValue Vec = Op.getOperand(0);
8502     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8503     if (Idx == 0)
8504       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8505                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8506                                      DAG.getNode(ISD::BITCAST, dl,
8507                                                  MVT::v4i32, Vec),
8508                                      Op.getOperand(1)));
8509     // Transform it so it match pextrw which produces a 32-bit result.
8510     MVT EltVT = MVT::i32;
8511     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8512                                   Op.getOperand(0), Op.getOperand(1));
8513     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8514                                   DAG.getValueType(VT));
8515     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8516   }
8517
8518   if (VT.getSizeInBits() == 32) {
8519     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8520     if (Idx == 0)
8521       return Op;
8522
8523     // SHUFPS the element to the lowest double word, then movss.
8524     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8525     MVT VVT = Op.getOperand(0).getSimpleValueType();
8526     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8527                                        DAG.getUNDEF(VVT), Mask);
8528     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8529                        DAG.getIntPtrConstant(0));
8530   }
8531
8532   if (VT.getSizeInBits() == 64) {
8533     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8534     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8535     //        to match extract_elt for f64.
8536     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8537     if (Idx == 0)
8538       return Op;
8539
8540     // UNPCKHPD the element to the lowest double word, then movsd.
8541     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8542     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8543     int Mask[2] = { 1, -1 };
8544     MVT VVT = Op.getOperand(0).getSimpleValueType();
8545     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8546                                        DAG.getUNDEF(VVT), Mask);
8547     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8548                        DAG.getIntPtrConstant(0));
8549   }
8550
8551   return SDValue();
8552 }
8553
8554 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8555   MVT VT = Op.getSimpleValueType();
8556   MVT EltVT = VT.getVectorElementType();
8557   SDLoc dl(Op);
8558
8559   SDValue N0 = Op.getOperand(0);
8560   SDValue N1 = Op.getOperand(1);
8561   SDValue N2 = Op.getOperand(2);
8562
8563   if (!VT.is128BitVector())
8564     return SDValue();
8565
8566   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8567       isa<ConstantSDNode>(N2)) {
8568     unsigned Opc;
8569     if (VT == MVT::v8i16)
8570       Opc = X86ISD::PINSRW;
8571     else if (VT == MVT::v16i8)
8572       Opc = X86ISD::PINSRB;
8573     else
8574       Opc = X86ISD::PINSRB;
8575
8576     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8577     // argument.
8578     if (N1.getValueType() != MVT::i32)
8579       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8580     if (N2.getValueType() != MVT::i32)
8581       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8582     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8583   }
8584
8585   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8586     // Bits [7:6] of the constant are the source select.  This will always be
8587     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8588     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8589     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8590     // Bits [5:4] of the constant are the destination select.  This is the
8591     //  value of the incoming immediate.
8592     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8593     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8594     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8595     // Create this as a scalar to vector..
8596     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8597     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8598   }
8599
8600   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8601     // PINSR* works with constant index.
8602     return Op;
8603   }
8604   return SDValue();
8605 }
8606
8607 /// Insert one bit to mask vector, like v16i1 or v8i1.
8608 /// AVX-512 feature.
8609 SDValue 
8610 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8611   SDLoc dl(Op);
8612   SDValue Vec = Op.getOperand(0);
8613   SDValue Elt = Op.getOperand(1);
8614   SDValue Idx = Op.getOperand(2);
8615   MVT VecVT = Vec.getSimpleValueType();
8616
8617   if (!isa<ConstantSDNode>(Idx)) {
8618     // Non constant index. Extend source and destination,
8619     // insert element and then truncate the result.
8620     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8621     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8622     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8623       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8624       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8625     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8626   }
8627
8628   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8629   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8630   if (Vec.getOpcode() == ISD::UNDEF)
8631     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8632                        DAG.getConstant(IdxVal, MVT::i8));
8633   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8634   unsigned MaxSift = rc->getSize()*8 - 1;
8635   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8636                     DAG.getConstant(MaxSift, MVT::i8));
8637   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8638                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8639   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8640 }
8641 SDValue
8642 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8643   MVT VT = Op.getSimpleValueType();
8644   MVT EltVT = VT.getVectorElementType();
8645   
8646   if (EltVT == MVT::i1)
8647     return InsertBitToMaskVector(Op, DAG);
8648
8649   SDLoc dl(Op);
8650   SDValue N0 = Op.getOperand(0);
8651   SDValue N1 = Op.getOperand(1);
8652   SDValue N2 = Op.getOperand(2);
8653
8654   // If this is a 256-bit vector result, first extract the 128-bit vector,
8655   // insert the element into the extracted half and then place it back.
8656   if (VT.is256BitVector() || VT.is512BitVector()) {
8657     if (!isa<ConstantSDNode>(N2))
8658       return SDValue();
8659
8660     // Get the desired 128-bit vector half.
8661     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8662     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8663
8664     // Insert the element into the desired half.
8665     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8666     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8667
8668     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8669                     DAG.getConstant(IdxIn128, MVT::i32));
8670
8671     // Insert the changed part back to the 256-bit vector
8672     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8673   }
8674
8675   if (Subtarget->hasSSE41())
8676     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8677
8678   if (EltVT == MVT::i8)
8679     return SDValue();
8680
8681   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8682     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8683     // as its second argument.
8684     if (N1.getValueType() != MVT::i32)
8685       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8686     if (N2.getValueType() != MVT::i32)
8687       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8688     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8689   }
8690   return SDValue();
8691 }
8692
8693 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8694   SDLoc dl(Op);
8695   MVT OpVT = Op.getSimpleValueType();
8696
8697   // If this is a 256-bit vector result, first insert into a 128-bit
8698   // vector and then insert into the 256-bit vector.
8699   if (!OpVT.is128BitVector()) {
8700     // Insert into a 128-bit vector.
8701     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8702     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8703                                  OpVT.getVectorNumElements() / SizeFactor);
8704
8705     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8706
8707     // Insert the 128-bit vector.
8708     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8709   }
8710
8711   if (OpVT == MVT::v1i64 &&
8712       Op.getOperand(0).getValueType() == MVT::i64)
8713     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8714
8715   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8716   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8717   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8718                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8719 }
8720
8721 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8722 // a simple subregister reference or explicit instructions to grab
8723 // upper bits of a vector.
8724 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8725                                       SelectionDAG &DAG) {
8726   SDLoc dl(Op);
8727   SDValue In =  Op.getOperand(0);
8728   SDValue Idx = Op.getOperand(1);
8729   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8730   MVT ResVT   = Op.getSimpleValueType();
8731   MVT InVT    = In.getSimpleValueType();
8732
8733   if (Subtarget->hasFp256()) {
8734     if (ResVT.is128BitVector() &&
8735         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8736         isa<ConstantSDNode>(Idx)) {
8737       return Extract128BitVector(In, IdxVal, DAG, dl);
8738     }
8739     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8740         isa<ConstantSDNode>(Idx)) {
8741       return Extract256BitVector(In, IdxVal, DAG, dl);
8742     }
8743   }
8744   return SDValue();
8745 }
8746
8747 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8748 // simple superregister reference or explicit instructions to insert
8749 // the upper bits of a vector.
8750 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8751                                      SelectionDAG &DAG) {
8752   if (Subtarget->hasFp256()) {
8753     SDLoc dl(Op.getNode());
8754     SDValue Vec = Op.getNode()->getOperand(0);
8755     SDValue SubVec = Op.getNode()->getOperand(1);
8756     SDValue Idx = Op.getNode()->getOperand(2);
8757
8758     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8759          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8760         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8761         isa<ConstantSDNode>(Idx)) {
8762       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8763       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8764     }
8765
8766     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8767         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8768         isa<ConstantSDNode>(Idx)) {
8769       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8770       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8771     }
8772   }
8773   return SDValue();
8774 }
8775
8776 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8777 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8778 // one of the above mentioned nodes. It has to be wrapped because otherwise
8779 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8780 // be used to form addressing mode. These wrapped nodes will be selected
8781 // into MOV32ri.
8782 SDValue
8783 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8784   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8785
8786   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8787   // global base reg.
8788   unsigned char OpFlag = 0;
8789   unsigned WrapperKind = X86ISD::Wrapper;
8790   CodeModel::Model M = DAG.getTarget().getCodeModel();
8791
8792   if (Subtarget->isPICStyleRIPRel() &&
8793       (M == CodeModel::Small || M == CodeModel::Kernel))
8794     WrapperKind = X86ISD::WrapperRIP;
8795   else if (Subtarget->isPICStyleGOT())
8796     OpFlag = X86II::MO_GOTOFF;
8797   else if (Subtarget->isPICStyleStubPIC())
8798     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8799
8800   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8801                                              CP->getAlignment(),
8802                                              CP->getOffset(), OpFlag);
8803   SDLoc DL(CP);
8804   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8805   // With PIC, the address is actually $g + Offset.
8806   if (OpFlag) {
8807     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8808                          DAG.getNode(X86ISD::GlobalBaseReg,
8809                                      SDLoc(), getPointerTy()),
8810                          Result);
8811   }
8812
8813   return Result;
8814 }
8815
8816 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8817   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8818
8819   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8820   // global base reg.
8821   unsigned char OpFlag = 0;
8822   unsigned WrapperKind = X86ISD::Wrapper;
8823   CodeModel::Model M = DAG.getTarget().getCodeModel();
8824
8825   if (Subtarget->isPICStyleRIPRel() &&
8826       (M == CodeModel::Small || M == CodeModel::Kernel))
8827     WrapperKind = X86ISD::WrapperRIP;
8828   else if (Subtarget->isPICStyleGOT())
8829     OpFlag = X86II::MO_GOTOFF;
8830   else if (Subtarget->isPICStyleStubPIC())
8831     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8832
8833   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8834                                           OpFlag);
8835   SDLoc DL(JT);
8836   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8837
8838   // With PIC, the address is actually $g + Offset.
8839   if (OpFlag)
8840     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8841                          DAG.getNode(X86ISD::GlobalBaseReg,
8842                                      SDLoc(), getPointerTy()),
8843                          Result);
8844
8845   return Result;
8846 }
8847
8848 SDValue
8849 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8850   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8851
8852   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8853   // global base reg.
8854   unsigned char OpFlag = 0;
8855   unsigned WrapperKind = X86ISD::Wrapper;
8856   CodeModel::Model M = DAG.getTarget().getCodeModel();
8857
8858   if (Subtarget->isPICStyleRIPRel() &&
8859       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8860     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8861       OpFlag = X86II::MO_GOTPCREL;
8862     WrapperKind = X86ISD::WrapperRIP;
8863   } else if (Subtarget->isPICStyleGOT()) {
8864     OpFlag = X86II::MO_GOT;
8865   } else if (Subtarget->isPICStyleStubPIC()) {
8866     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8867   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8868     OpFlag = X86II::MO_DARWIN_NONLAZY;
8869   }
8870
8871   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8872
8873   SDLoc DL(Op);
8874   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8875
8876   // With PIC, the address is actually $g + Offset.
8877   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
8878       !Subtarget->is64Bit()) {
8879     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8880                          DAG.getNode(X86ISD::GlobalBaseReg,
8881                                      SDLoc(), getPointerTy()),
8882                          Result);
8883   }
8884
8885   // For symbols that require a load from a stub to get the address, emit the
8886   // load.
8887   if (isGlobalStubReference(OpFlag))
8888     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8889                          MachinePointerInfo::getGOT(), false, false, false, 0);
8890
8891   return Result;
8892 }
8893
8894 SDValue
8895 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8896   // Create the TargetBlockAddressAddress node.
8897   unsigned char OpFlags =
8898     Subtarget->ClassifyBlockAddressReference();
8899   CodeModel::Model M = DAG.getTarget().getCodeModel();
8900   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8901   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8902   SDLoc dl(Op);
8903   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8904                                              OpFlags);
8905
8906   if (Subtarget->isPICStyleRIPRel() &&
8907       (M == CodeModel::Small || M == CodeModel::Kernel))
8908     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8909   else
8910     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8911
8912   // With PIC, the address is actually $g + Offset.
8913   if (isGlobalRelativeToPICBase(OpFlags)) {
8914     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8915                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8916                          Result);
8917   }
8918
8919   return Result;
8920 }
8921
8922 SDValue
8923 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8924                                       int64_t Offset, SelectionDAG &DAG) const {
8925   // Create the TargetGlobalAddress node, folding in the constant
8926   // offset if it is legal.
8927   unsigned char OpFlags =
8928       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
8929   CodeModel::Model M = DAG.getTarget().getCodeModel();
8930   SDValue Result;
8931   if (OpFlags == X86II::MO_NO_FLAG &&
8932       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8933     // A direct static reference to a global.
8934     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8935     Offset = 0;
8936   } else {
8937     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8938   }
8939
8940   if (Subtarget->isPICStyleRIPRel() &&
8941       (M == CodeModel::Small || M == CodeModel::Kernel))
8942     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8943   else
8944     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8945
8946   // With PIC, the address is actually $g + Offset.
8947   if (isGlobalRelativeToPICBase(OpFlags)) {
8948     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8949                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8950                          Result);
8951   }
8952
8953   // For globals that require a load from a stub to get the address, emit the
8954   // load.
8955   if (isGlobalStubReference(OpFlags))
8956     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8957                          MachinePointerInfo::getGOT(), false, false, false, 0);
8958
8959   // If there was a non-zero offset that we didn't fold, create an explicit
8960   // addition for it.
8961   if (Offset != 0)
8962     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8963                          DAG.getConstant(Offset, getPointerTy()));
8964
8965   return Result;
8966 }
8967
8968 SDValue
8969 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8970   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8971   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8972   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8973 }
8974
8975 static SDValue
8976 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8977            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8978            unsigned char OperandFlags, bool LocalDynamic = false) {
8979   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8980   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8981   SDLoc dl(GA);
8982   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8983                                            GA->getValueType(0),
8984                                            GA->getOffset(),
8985                                            OperandFlags);
8986
8987   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8988                                            : X86ISD::TLSADDR;
8989
8990   if (InFlag) {
8991     SDValue Ops[] = { Chain,  TGA, *InFlag };
8992     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8993   } else {
8994     SDValue Ops[]  = { Chain, TGA };
8995     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8996   }
8997
8998   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8999   MFI->setAdjustsStack(true);
9000
9001   SDValue Flag = Chain.getValue(1);
9002   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
9003 }
9004
9005 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
9006 static SDValue
9007 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9008                                 const EVT PtrVT) {
9009   SDValue InFlag;
9010   SDLoc dl(GA);  // ? function entry point might be better
9011   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9012                                    DAG.getNode(X86ISD::GlobalBaseReg,
9013                                                SDLoc(), PtrVT), InFlag);
9014   InFlag = Chain.getValue(1);
9015
9016   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
9017 }
9018
9019 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
9020 static SDValue
9021 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9022                                 const EVT PtrVT) {
9023   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
9024                     X86::RAX, X86II::MO_TLSGD);
9025 }
9026
9027 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
9028                                            SelectionDAG &DAG,
9029                                            const EVT PtrVT,
9030                                            bool is64Bit) {
9031   SDLoc dl(GA);
9032
9033   // Get the start address of the TLS block for this module.
9034   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
9035       .getInfo<X86MachineFunctionInfo>();
9036   MFI->incNumLocalDynamicTLSAccesses();
9037
9038   SDValue Base;
9039   if (is64Bit) {
9040     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
9041                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
9042   } else {
9043     SDValue InFlag;
9044     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9045         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
9046     InFlag = Chain.getValue(1);
9047     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
9048                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
9049   }
9050
9051   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
9052   // of Base.
9053
9054   // Build x@dtpoff.
9055   unsigned char OperandFlags = X86II::MO_DTPOFF;
9056   unsigned WrapperKind = X86ISD::Wrapper;
9057   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9058                                            GA->getValueType(0),
9059                                            GA->getOffset(), OperandFlags);
9060   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9061
9062   // Add x@dtpoff with the base.
9063   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
9064 }
9065
9066 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
9067 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9068                                    const EVT PtrVT, TLSModel::Model model,
9069                                    bool is64Bit, bool isPIC) {
9070   SDLoc dl(GA);
9071
9072   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
9073   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
9074                                                          is64Bit ? 257 : 256));
9075
9076   SDValue ThreadPointer =
9077       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
9078                   MachinePointerInfo(Ptr), false, false, false, 0);
9079
9080   unsigned char OperandFlags = 0;
9081   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
9082   // initialexec.
9083   unsigned WrapperKind = X86ISD::Wrapper;
9084   if (model == TLSModel::LocalExec) {
9085     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
9086   } else if (model == TLSModel::InitialExec) {
9087     if (is64Bit) {
9088       OperandFlags = X86II::MO_GOTTPOFF;
9089       WrapperKind = X86ISD::WrapperRIP;
9090     } else {
9091       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
9092     }
9093   } else {
9094     llvm_unreachable("Unexpected model");
9095   }
9096
9097   // emit "addl x@ntpoff,%eax" (local exec)
9098   // or "addl x@indntpoff,%eax" (initial exec)
9099   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
9100   SDValue TGA =
9101       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
9102                                  GA->getOffset(), OperandFlags);
9103   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9104
9105   if (model == TLSModel::InitialExec) {
9106     if (isPIC && !is64Bit) {
9107       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
9108                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
9109                            Offset);
9110     }
9111
9112     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
9113                          MachinePointerInfo::getGOT(), false, false, false, 0);
9114   }
9115
9116   // The address of the thread local variable is the add of the thread
9117   // pointer with the offset of the variable.
9118   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9119 }
9120
9121 SDValue
9122 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9123
9124   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9125   const GlobalValue *GV = GA->getGlobal();
9126
9127   if (Subtarget->isTargetELF()) {
9128     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9129
9130     switch (model) {
9131       case TLSModel::GeneralDynamic:
9132         if (Subtarget->is64Bit())
9133           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9134         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9135       case TLSModel::LocalDynamic:
9136         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9137                                            Subtarget->is64Bit());
9138       case TLSModel::InitialExec:
9139       case TLSModel::LocalExec:
9140         return LowerToTLSExecModel(
9141             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9142             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9143     }
9144     llvm_unreachable("Unknown TLS model.");
9145   }
9146
9147   if (Subtarget->isTargetDarwin()) {
9148     // Darwin only has one model of TLS.  Lower to that.
9149     unsigned char OpFlag = 0;
9150     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9151                            X86ISD::WrapperRIP : X86ISD::Wrapper;
9152
9153     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9154     // global base reg.
9155     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9156                  !Subtarget->is64Bit();
9157     if (PIC32)
9158       OpFlag = X86II::MO_TLVP_PIC_BASE;
9159     else
9160       OpFlag = X86II::MO_TLVP;
9161     SDLoc DL(Op);
9162     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9163                                                 GA->getValueType(0),
9164                                                 GA->getOffset(), OpFlag);
9165     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9166
9167     // With PIC32, the address is actually $g + Offset.
9168     if (PIC32)
9169       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9170                            DAG.getNode(X86ISD::GlobalBaseReg,
9171                                        SDLoc(), getPointerTy()),
9172                            Offset);
9173
9174     // Lowering the machine isd will make sure everything is in the right
9175     // location.
9176     SDValue Chain = DAG.getEntryNode();
9177     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9178     SDValue Args[] = { Chain, Offset };
9179     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9180
9181     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9182     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9183     MFI->setAdjustsStack(true);
9184
9185     // And our return value (tls address) is in the standard call return value
9186     // location.
9187     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9188     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9189                               Chain.getValue(1));
9190   }
9191
9192   if (Subtarget->isTargetKnownWindowsMSVC() ||
9193       Subtarget->isTargetWindowsGNU()) {
9194     // Just use the implicit TLS architecture
9195     // Need to generate someting similar to:
9196     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9197     //                                  ; from TEB
9198     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
9199     //   mov     rcx, qword [rdx+rcx*8]
9200     //   mov     eax, .tls$:tlsvar
9201     //   [rax+rcx] contains the address
9202     // Windows 64bit: gs:0x58
9203     // Windows 32bit: fs:__tls_array
9204
9205     SDLoc dl(GA);
9206     SDValue Chain = DAG.getEntryNode();
9207
9208     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9209     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9210     // use its literal value of 0x2C.
9211     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9212                                         ? Type::getInt8PtrTy(*DAG.getContext(),
9213                                                              256)
9214                                         : Type::getInt32PtrTy(*DAG.getContext(),
9215                                                               257));
9216
9217     SDValue TlsArray =
9218         Subtarget->is64Bit()
9219             ? DAG.getIntPtrConstant(0x58)
9220             : (Subtarget->isTargetWindowsGNU()
9221                    ? DAG.getIntPtrConstant(0x2C)
9222                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9223
9224     SDValue ThreadPointer =
9225         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9226                     MachinePointerInfo(Ptr), false, false, false, 0);
9227
9228     // Load the _tls_index variable
9229     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9230     if (Subtarget->is64Bit())
9231       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9232                            IDX, MachinePointerInfo(), MVT::i32,
9233                            false, false, 0);
9234     else
9235       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9236                         false, false, false, 0);
9237
9238     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9239                                     getPointerTy());
9240     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9241
9242     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9243     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9244                       false, false, false, 0);
9245
9246     // Get the offset of start of .tls section
9247     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9248                                              GA->getValueType(0),
9249                                              GA->getOffset(), X86II::MO_SECREL);
9250     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9251
9252     // The address of the thread local variable is the add of the thread
9253     // pointer with the offset of the variable.
9254     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9255   }
9256
9257   llvm_unreachable("TLS not implemented for this target.");
9258 }
9259
9260 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9261 /// and take a 2 x i32 value to shift plus a shift amount.
9262 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9263   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9264   MVT VT = Op.getSimpleValueType();
9265   unsigned VTBits = VT.getSizeInBits();
9266   SDLoc dl(Op);
9267   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9268   SDValue ShOpLo = Op.getOperand(0);
9269   SDValue ShOpHi = Op.getOperand(1);
9270   SDValue ShAmt  = Op.getOperand(2);
9271   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9272   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9273   // during isel.
9274   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9275                                   DAG.getConstant(VTBits - 1, MVT::i8));
9276   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9277                                      DAG.getConstant(VTBits - 1, MVT::i8))
9278                        : DAG.getConstant(0, VT);
9279
9280   SDValue Tmp2, Tmp3;
9281   if (Op.getOpcode() == ISD::SHL_PARTS) {
9282     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9283     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9284   } else {
9285     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9286     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9287   }
9288
9289   // If the shift amount is larger or equal than the width of a part we can't
9290   // rely on the results of shld/shrd. Insert a test and select the appropriate
9291   // values for large shift amounts.
9292   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9293                                 DAG.getConstant(VTBits, MVT::i8));
9294   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9295                              AndNode, DAG.getConstant(0, MVT::i8));
9296
9297   SDValue Hi, Lo;
9298   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9299   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9300   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9301
9302   if (Op.getOpcode() == ISD::SHL_PARTS) {
9303     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9304     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9305   } else {
9306     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9307     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9308   }
9309
9310   SDValue Ops[2] = { Lo, Hi };
9311   return DAG.getMergeValues(Ops, dl);
9312 }
9313
9314 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9315                                            SelectionDAG &DAG) const {
9316   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9317
9318   if (SrcVT.isVector())
9319     return SDValue();
9320
9321   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9322          "Unknown SINT_TO_FP to lower!");
9323
9324   // These are really Legal; return the operand so the caller accepts it as
9325   // Legal.
9326   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9327     return Op;
9328   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9329       Subtarget->is64Bit()) {
9330     return Op;
9331   }
9332
9333   SDLoc dl(Op);
9334   unsigned Size = SrcVT.getSizeInBits()/8;
9335   MachineFunction &MF = DAG.getMachineFunction();
9336   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9337   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9338   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9339                                StackSlot,
9340                                MachinePointerInfo::getFixedStack(SSFI),
9341                                false, false, 0);
9342   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9343 }
9344
9345 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9346                                      SDValue StackSlot,
9347                                      SelectionDAG &DAG) const {
9348   // Build the FILD
9349   SDLoc DL(Op);
9350   SDVTList Tys;
9351   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9352   if (useSSE)
9353     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9354   else
9355     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9356
9357   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9358
9359   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9360   MachineMemOperand *MMO;
9361   if (FI) {
9362     int SSFI = FI->getIndex();
9363     MMO =
9364       DAG.getMachineFunction()
9365       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9366                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9367   } else {
9368     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9369     StackSlot = StackSlot.getOperand(1);
9370   }
9371   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9372   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9373                                            X86ISD::FILD, DL,
9374                                            Tys, Ops, SrcVT, MMO);
9375
9376   if (useSSE) {
9377     Chain = Result.getValue(1);
9378     SDValue InFlag = Result.getValue(2);
9379
9380     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9381     // shouldn't be necessary except that RFP cannot be live across
9382     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9383     MachineFunction &MF = DAG.getMachineFunction();
9384     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9385     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9386     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9387     Tys = DAG.getVTList(MVT::Other);
9388     SDValue Ops[] = {
9389       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9390     };
9391     MachineMemOperand *MMO =
9392       DAG.getMachineFunction()
9393       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9394                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9395
9396     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9397                                     Ops, Op.getValueType(), MMO);
9398     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9399                          MachinePointerInfo::getFixedStack(SSFI),
9400                          false, false, false, 0);
9401   }
9402
9403   return Result;
9404 }
9405
9406 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9407 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9408                                                SelectionDAG &DAG) const {
9409   // This algorithm is not obvious. Here it is what we're trying to output:
9410   /*
9411      movq       %rax,  %xmm0
9412      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9413      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9414      #ifdef __SSE3__
9415        haddpd   %xmm0, %xmm0
9416      #else
9417        pshufd   $0x4e, %xmm0, %xmm1
9418        addpd    %xmm1, %xmm0
9419      #endif
9420   */
9421
9422   SDLoc dl(Op);
9423   LLVMContext *Context = DAG.getContext();
9424
9425   // Build some magic constants.
9426   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9427   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9428   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9429
9430   SmallVector<Constant*,2> CV1;
9431   CV1.push_back(
9432     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9433                                       APInt(64, 0x4330000000000000ULL))));
9434   CV1.push_back(
9435     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9436                                       APInt(64, 0x4530000000000000ULL))));
9437   Constant *C1 = ConstantVector::get(CV1);
9438   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9439
9440   // Load the 64-bit value into an XMM register.
9441   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9442                             Op.getOperand(0));
9443   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9444                               MachinePointerInfo::getConstantPool(),
9445                               false, false, false, 16);
9446   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9447                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9448                               CLod0);
9449
9450   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9451                               MachinePointerInfo::getConstantPool(),
9452                               false, false, false, 16);
9453   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9454   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9455   SDValue Result;
9456
9457   if (Subtarget->hasSSE3()) {
9458     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9459     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9460   } else {
9461     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9462     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9463                                            S2F, 0x4E, DAG);
9464     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9465                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9466                          Sub);
9467   }
9468
9469   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9470                      DAG.getIntPtrConstant(0));
9471 }
9472
9473 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9474 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9475                                                SelectionDAG &DAG) const {
9476   SDLoc dl(Op);
9477   // FP constant to bias correct the final result.
9478   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9479                                    MVT::f64);
9480
9481   // Load the 32-bit value into an XMM register.
9482   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9483                              Op.getOperand(0));
9484
9485   // Zero out the upper parts of the register.
9486   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9487
9488   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9489                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9490                      DAG.getIntPtrConstant(0));
9491
9492   // Or the load with the bias.
9493   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9494                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9495                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9496                                                    MVT::v2f64, Load)),
9497                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9498                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9499                                                    MVT::v2f64, Bias)));
9500   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9501                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9502                    DAG.getIntPtrConstant(0));
9503
9504   // Subtract the bias.
9505   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9506
9507   // Handle final rounding.
9508   EVT DestVT = Op.getValueType();
9509
9510   if (DestVT.bitsLT(MVT::f64))
9511     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9512                        DAG.getIntPtrConstant(0));
9513   if (DestVT.bitsGT(MVT::f64))
9514     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9515
9516   // Handle final rounding.
9517   return Sub;
9518 }
9519
9520 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9521                                                SelectionDAG &DAG) const {
9522   SDValue N0 = Op.getOperand(0);
9523   MVT SVT = N0.getSimpleValueType();
9524   SDLoc dl(Op);
9525
9526   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9527           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9528          "Custom UINT_TO_FP is not supported!");
9529
9530   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9531   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9532                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9533 }
9534
9535 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9536                                            SelectionDAG &DAG) const {
9537   SDValue N0 = Op.getOperand(0);
9538   SDLoc dl(Op);
9539
9540   if (Op.getValueType().isVector())
9541     return lowerUINT_TO_FP_vec(Op, DAG);
9542
9543   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9544   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9545   // the optimization here.
9546   if (DAG.SignBitIsZero(N0))
9547     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9548
9549   MVT SrcVT = N0.getSimpleValueType();
9550   MVT DstVT = Op.getSimpleValueType();
9551   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9552     return LowerUINT_TO_FP_i64(Op, DAG);
9553   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9554     return LowerUINT_TO_FP_i32(Op, DAG);
9555   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9556     return SDValue();
9557
9558   // Make a 64-bit buffer, and use it to build an FILD.
9559   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9560   if (SrcVT == MVT::i32) {
9561     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9562     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9563                                      getPointerTy(), StackSlot, WordOff);
9564     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9565                                   StackSlot, MachinePointerInfo(),
9566                                   false, false, 0);
9567     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9568                                   OffsetSlot, MachinePointerInfo(),
9569                                   false, false, 0);
9570     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9571     return Fild;
9572   }
9573
9574   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9575   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9576                                StackSlot, MachinePointerInfo(),
9577                                false, false, 0);
9578   // For i64 source, we need to add the appropriate power of 2 if the input
9579   // was negative.  This is the same as the optimization in
9580   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9581   // we must be careful to do the computation in x87 extended precision, not
9582   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9583   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9584   MachineMemOperand *MMO =
9585     DAG.getMachineFunction()
9586     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9587                           MachineMemOperand::MOLoad, 8, 8);
9588
9589   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9590   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9591   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9592                                          MVT::i64, MMO);
9593
9594   APInt FF(32, 0x5F800000ULL);
9595
9596   // Check whether the sign bit is set.
9597   SDValue SignSet = DAG.getSetCC(dl,
9598                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9599                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9600                                  ISD::SETLT);
9601
9602   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9603   SDValue FudgePtr = DAG.getConstantPool(
9604                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9605                                          getPointerTy());
9606
9607   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9608   SDValue Zero = DAG.getIntPtrConstant(0);
9609   SDValue Four = DAG.getIntPtrConstant(4);
9610   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9611                                Zero, Four);
9612   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9613
9614   // Load the value out, extending it from f32 to f80.
9615   // FIXME: Avoid the extend by constructing the right constant pool?
9616   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9617                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9618                                  MVT::f32, false, false, 4);
9619   // Extend everything to 80 bits to force it to be done on x87.
9620   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9621   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9622 }
9623
9624 std::pair<SDValue,SDValue>
9625 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9626                                     bool IsSigned, bool IsReplace) const {
9627   SDLoc DL(Op);
9628
9629   EVT DstTy = Op.getValueType();
9630
9631   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9632     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9633     DstTy = MVT::i64;
9634   }
9635
9636   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9637          DstTy.getSimpleVT() >= MVT::i16 &&
9638          "Unknown FP_TO_INT to lower!");
9639
9640   // These are really Legal.
9641   if (DstTy == MVT::i32 &&
9642       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9643     return std::make_pair(SDValue(), SDValue());
9644   if (Subtarget->is64Bit() &&
9645       DstTy == MVT::i64 &&
9646       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9647     return std::make_pair(SDValue(), SDValue());
9648
9649   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9650   // stack slot, or into the FTOL runtime function.
9651   MachineFunction &MF = DAG.getMachineFunction();
9652   unsigned MemSize = DstTy.getSizeInBits()/8;
9653   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9654   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9655
9656   unsigned Opc;
9657   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9658     Opc = X86ISD::WIN_FTOL;
9659   else
9660     switch (DstTy.getSimpleVT().SimpleTy) {
9661     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9662     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9663     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9664     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9665     }
9666
9667   SDValue Chain = DAG.getEntryNode();
9668   SDValue Value = Op.getOperand(0);
9669   EVT TheVT = Op.getOperand(0).getValueType();
9670   // FIXME This causes a redundant load/store if the SSE-class value is already
9671   // in memory, such as if it is on the callstack.
9672   if (isScalarFPTypeInSSEReg(TheVT)) {
9673     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9674     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9675                          MachinePointerInfo::getFixedStack(SSFI),
9676                          false, false, 0);
9677     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9678     SDValue Ops[] = {
9679       Chain, StackSlot, DAG.getValueType(TheVT)
9680     };
9681
9682     MachineMemOperand *MMO =
9683       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9684                               MachineMemOperand::MOLoad, MemSize, MemSize);
9685     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9686     Chain = Value.getValue(1);
9687     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9688     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9689   }
9690
9691   MachineMemOperand *MMO =
9692     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9693                             MachineMemOperand::MOStore, MemSize, MemSize);
9694
9695   if (Opc != X86ISD::WIN_FTOL) {
9696     // Build the FP_TO_INT*_IN_MEM
9697     SDValue Ops[] = { Chain, Value, StackSlot };
9698     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9699                                            Ops, DstTy, MMO);
9700     return std::make_pair(FIST, StackSlot);
9701   } else {
9702     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9703       DAG.getVTList(MVT::Other, MVT::Glue),
9704       Chain, Value);
9705     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9706       MVT::i32, ftol.getValue(1));
9707     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9708       MVT::i32, eax.getValue(2));
9709     SDValue Ops[] = { eax, edx };
9710     SDValue pair = IsReplace
9711       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9712       : DAG.getMergeValues(Ops, DL);
9713     return std::make_pair(pair, SDValue());
9714   }
9715 }
9716
9717 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9718                               const X86Subtarget *Subtarget) {
9719   MVT VT = Op->getSimpleValueType(0);
9720   SDValue In = Op->getOperand(0);
9721   MVT InVT = In.getSimpleValueType();
9722   SDLoc dl(Op);
9723
9724   // Optimize vectors in AVX mode:
9725   //
9726   //   v8i16 -> v8i32
9727   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9728   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9729   //   Concat upper and lower parts.
9730   //
9731   //   v4i32 -> v4i64
9732   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9733   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9734   //   Concat upper and lower parts.
9735   //
9736
9737   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9738       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9739       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9740     return SDValue();
9741
9742   if (Subtarget->hasInt256())
9743     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9744
9745   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9746   SDValue Undef = DAG.getUNDEF(InVT);
9747   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9748   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9749   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9750
9751   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9752                              VT.getVectorNumElements()/2);
9753
9754   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9755   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9756
9757   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9758 }
9759
9760 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9761                                         SelectionDAG &DAG) {
9762   MVT VT = Op->getSimpleValueType(0);
9763   SDValue In = Op->getOperand(0);
9764   MVT InVT = In.getSimpleValueType();
9765   SDLoc DL(Op);
9766   unsigned int NumElts = VT.getVectorNumElements();
9767   if (NumElts != 8 && NumElts != 16)
9768     return SDValue();
9769
9770   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9771     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9772
9773   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9775   // Now we have only mask extension
9776   assert(InVT.getVectorElementType() == MVT::i1);
9777   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9778   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9779   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9780   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9781   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9782                            MachinePointerInfo::getConstantPool(),
9783                            false, false, false, Alignment);
9784
9785   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9786   if (VT.is512BitVector())
9787     return Brcst;
9788   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9789 }
9790
9791 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9792                                SelectionDAG &DAG) {
9793   if (Subtarget->hasFp256()) {
9794     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9795     if (Res.getNode())
9796       return Res;
9797   }
9798
9799   return SDValue();
9800 }
9801
9802 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9803                                 SelectionDAG &DAG) {
9804   SDLoc DL(Op);
9805   MVT VT = Op.getSimpleValueType();
9806   SDValue In = Op.getOperand(0);
9807   MVT SVT = In.getSimpleValueType();
9808
9809   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9810     return LowerZERO_EXTEND_AVX512(Op, DAG);
9811
9812   if (Subtarget->hasFp256()) {
9813     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9814     if (Res.getNode())
9815       return Res;
9816   }
9817
9818   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9819          VT.getVectorNumElements() != SVT.getVectorNumElements());
9820   return SDValue();
9821 }
9822
9823 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9824   SDLoc DL(Op);
9825   MVT VT = Op.getSimpleValueType();
9826   SDValue In = Op.getOperand(0);
9827   MVT InVT = In.getSimpleValueType();
9828
9829   if (VT == MVT::i1) {
9830     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9831            "Invalid scalar TRUNCATE operation");
9832     if (InVT == MVT::i32)
9833       return SDValue();
9834     if (InVT.getSizeInBits() == 64)
9835       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9836     else if (InVT.getSizeInBits() < 32)
9837       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9838     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9839   }
9840   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9841          "Invalid TRUNCATE operation");
9842
9843   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9844     if (VT.getVectorElementType().getSizeInBits() >=8)
9845       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9846
9847     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9848     unsigned NumElts = InVT.getVectorNumElements();
9849     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9850     if (InVT.getSizeInBits() < 512) {
9851       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9852       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9853       InVT = ExtVT;
9854     }
9855     
9856     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9857     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9858     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9859     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9860     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9861                            MachinePointerInfo::getConstantPool(),
9862                            false, false, false, Alignment);
9863     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9864     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9865     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9866   }
9867
9868   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9869     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9870     if (Subtarget->hasInt256()) {
9871       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9872       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9873       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9874                                 ShufMask);
9875       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9876                          DAG.getIntPtrConstant(0));
9877     }
9878
9879     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9880                                DAG.getIntPtrConstant(0));
9881     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9882                                DAG.getIntPtrConstant(2));
9883     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9884     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9885     static const int ShufMask[] = {0, 2, 4, 6};
9886     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9887   }
9888
9889   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9890     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9891     if (Subtarget->hasInt256()) {
9892       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9893
9894       SmallVector<SDValue,32> pshufbMask;
9895       for (unsigned i = 0; i < 2; ++i) {
9896         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9897         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9898         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9899         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9900         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9901         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9902         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9903         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9904         for (unsigned j = 0; j < 8; ++j)
9905           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9906       }
9907       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9908       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9909       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9910
9911       static const int ShufMask[] = {0,  2,  -1,  -1};
9912       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9913                                 &ShufMask[0]);
9914       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9915                        DAG.getIntPtrConstant(0));
9916       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9917     }
9918
9919     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9920                                DAG.getIntPtrConstant(0));
9921
9922     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9923                                DAG.getIntPtrConstant(4));
9924
9925     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9926     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9927
9928     // The PSHUFB mask:
9929     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9930                                    -1, -1, -1, -1, -1, -1, -1, -1};
9931
9932     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9933     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9934     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9935
9936     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9937     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9938
9939     // The MOVLHPS Mask:
9940     static const int ShufMask2[] = {0, 1, 4, 5};
9941     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9942     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9943   }
9944
9945   // Handle truncation of V256 to V128 using shuffles.
9946   if (!VT.is128BitVector() || !InVT.is256BitVector())
9947     return SDValue();
9948
9949   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9950
9951   unsigned NumElems = VT.getVectorNumElements();
9952   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9953
9954   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9955   // Prepare truncation shuffle mask
9956   for (unsigned i = 0; i != NumElems; ++i)
9957     MaskVec[i] = i * 2;
9958   SDValue V = DAG.getVectorShuffle(NVT, DL,
9959                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9960                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9961   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9962                      DAG.getIntPtrConstant(0));
9963 }
9964
9965 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9966                                            SelectionDAG &DAG) const {
9967   assert(!Op.getSimpleValueType().isVector());
9968
9969   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9970     /*IsSigned=*/ true, /*IsReplace=*/ false);
9971   SDValue FIST = Vals.first, StackSlot = Vals.second;
9972   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9973   if (!FIST.getNode()) return Op;
9974
9975   if (StackSlot.getNode())
9976     // Load the result.
9977     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9978                        FIST, StackSlot, MachinePointerInfo(),
9979                        false, false, false, 0);
9980
9981   // The node is the result.
9982   return FIST;
9983 }
9984
9985 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9986                                            SelectionDAG &DAG) const {
9987   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9988     /*IsSigned=*/ false, /*IsReplace=*/ false);
9989   SDValue FIST = Vals.first, StackSlot = Vals.second;
9990   assert(FIST.getNode() && "Unexpected failure");
9991
9992   if (StackSlot.getNode())
9993     // Load the result.
9994     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9995                        FIST, StackSlot, MachinePointerInfo(),
9996                        false, false, false, 0);
9997
9998   // The node is the result.
9999   return FIST;
10000 }
10001
10002 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
10003   SDLoc DL(Op);
10004   MVT VT = Op.getSimpleValueType();
10005   SDValue In = Op.getOperand(0);
10006   MVT SVT = In.getSimpleValueType();
10007
10008   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
10009
10010   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
10011                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
10012                                  In, DAG.getUNDEF(SVT)));
10013 }
10014
10015 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
10016   LLVMContext *Context = DAG.getContext();
10017   SDLoc dl(Op);
10018   MVT VT = Op.getSimpleValueType();
10019   MVT EltVT = VT;
10020   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10021   if (VT.isVector()) {
10022     EltVT = VT.getVectorElementType();
10023     NumElts = VT.getVectorNumElements();
10024   }
10025   Constant *C;
10026   if (EltVT == MVT::f64)
10027     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10028                                           APInt(64, ~(1ULL << 63))));
10029   else
10030     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10031                                           APInt(32, ~(1U << 31))));
10032   C = ConstantVector::getSplat(NumElts, C);
10033   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10034   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10035   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10036   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10037                              MachinePointerInfo::getConstantPool(),
10038                              false, false, false, Alignment);
10039   if (VT.isVector()) {
10040     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10041     return DAG.getNode(ISD::BITCAST, dl, VT,
10042                        DAG.getNode(ISD::AND, dl, ANDVT,
10043                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
10044                                                Op.getOperand(0)),
10045                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
10046   }
10047   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
10048 }
10049
10050 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
10051   LLVMContext *Context = DAG.getContext();
10052   SDLoc dl(Op);
10053   MVT VT = Op.getSimpleValueType();
10054   MVT EltVT = VT;
10055   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10056   if (VT.isVector()) {
10057     EltVT = VT.getVectorElementType();
10058     NumElts = VT.getVectorNumElements();
10059   }
10060   Constant *C;
10061   if (EltVT == MVT::f64)
10062     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10063                                           APInt(64, 1ULL << 63)));
10064   else
10065     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10066                                           APInt(32, 1U << 31)));
10067   C = ConstantVector::getSplat(NumElts, C);
10068   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10069   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10070   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10071   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10072                              MachinePointerInfo::getConstantPool(),
10073                              false, false, false, Alignment);
10074   if (VT.isVector()) {
10075     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
10076     return DAG.getNode(ISD::BITCAST, dl, VT,
10077                        DAG.getNode(ISD::XOR, dl, XORVT,
10078                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
10079                                                Op.getOperand(0)),
10080                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
10081   }
10082
10083   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
10084 }
10085
10086 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
10087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10088   LLVMContext *Context = DAG.getContext();
10089   SDValue Op0 = Op.getOperand(0);
10090   SDValue Op1 = Op.getOperand(1);
10091   SDLoc dl(Op);
10092   MVT VT = Op.getSimpleValueType();
10093   MVT SrcVT = Op1.getSimpleValueType();
10094
10095   // If second operand is smaller, extend it first.
10096   if (SrcVT.bitsLT(VT)) {
10097     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
10098     SrcVT = VT;
10099   }
10100   // And if it is bigger, shrink it first.
10101   if (SrcVT.bitsGT(VT)) {
10102     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
10103     SrcVT = VT;
10104   }
10105
10106   // At this point the operands and the result should have the same
10107   // type, and that won't be f80 since that is not custom lowered.
10108
10109   // First get the sign bit of second operand.
10110   SmallVector<Constant*,4> CV;
10111   if (SrcVT == MVT::f64) {
10112     const fltSemantics &Sem = APFloat::IEEEdouble;
10113     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
10114     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10115   } else {
10116     const fltSemantics &Sem = APFloat::IEEEsingle;
10117     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
10118     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10119     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10120     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10121   }
10122   Constant *C = ConstantVector::get(CV);
10123   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10124   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10125                               MachinePointerInfo::getConstantPool(),
10126                               false, false, false, 16);
10127   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10128
10129   // Shift sign bit right or left if the two operands have different types.
10130   if (SrcVT.bitsGT(VT)) {
10131     // Op0 is MVT::f32, Op1 is MVT::f64.
10132     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10133     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10134                           DAG.getConstant(32, MVT::i32));
10135     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10136     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10137                           DAG.getIntPtrConstant(0));
10138   }
10139
10140   // Clear first operand sign bit.
10141   CV.clear();
10142   if (VT == MVT::f64) {
10143     const fltSemantics &Sem = APFloat::IEEEdouble;
10144     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10145                                                    APInt(64, ~(1ULL << 63)))));
10146     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10147   } else {
10148     const fltSemantics &Sem = APFloat::IEEEsingle;
10149     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10150                                                    APInt(32, ~(1U << 31)))));
10151     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10152     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10153     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10154   }
10155   C = ConstantVector::get(CV);
10156   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10157   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10158                               MachinePointerInfo::getConstantPool(),
10159                               false, false, false, 16);
10160   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10161
10162   // Or the value with the sign bit.
10163   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10164 }
10165
10166 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10167   SDValue N0 = Op.getOperand(0);
10168   SDLoc dl(Op);
10169   MVT VT = Op.getSimpleValueType();
10170
10171   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10172   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10173                                   DAG.getConstant(1, VT));
10174   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10175 }
10176
10177 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10178 //
10179 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10180                                       SelectionDAG &DAG) {
10181   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10182
10183   if (!Subtarget->hasSSE41())
10184     return SDValue();
10185
10186   if (!Op->hasOneUse())
10187     return SDValue();
10188
10189   SDNode *N = Op.getNode();
10190   SDLoc DL(N);
10191
10192   SmallVector<SDValue, 8> Opnds;
10193   DenseMap<SDValue, unsigned> VecInMap;
10194   SmallVector<SDValue, 8> VecIns;
10195   EVT VT = MVT::Other;
10196
10197   // Recognize a special case where a vector is casted into wide integer to
10198   // test all 0s.
10199   Opnds.push_back(N->getOperand(0));
10200   Opnds.push_back(N->getOperand(1));
10201
10202   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10203     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10204     // BFS traverse all OR'd operands.
10205     if (I->getOpcode() == ISD::OR) {
10206       Opnds.push_back(I->getOperand(0));
10207       Opnds.push_back(I->getOperand(1));
10208       // Re-evaluate the number of nodes to be traversed.
10209       e += 2; // 2 more nodes (LHS and RHS) are pushed.
10210       continue;
10211     }
10212
10213     // Quit if a non-EXTRACT_VECTOR_ELT
10214     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10215       return SDValue();
10216
10217     // Quit if without a constant index.
10218     SDValue Idx = I->getOperand(1);
10219     if (!isa<ConstantSDNode>(Idx))
10220       return SDValue();
10221
10222     SDValue ExtractedFromVec = I->getOperand(0);
10223     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10224     if (M == VecInMap.end()) {
10225       VT = ExtractedFromVec.getValueType();
10226       // Quit if not 128/256-bit vector.
10227       if (!VT.is128BitVector() && !VT.is256BitVector())
10228         return SDValue();
10229       // Quit if not the same type.
10230       if (VecInMap.begin() != VecInMap.end() &&
10231           VT != VecInMap.begin()->first.getValueType())
10232         return SDValue();
10233       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10234       VecIns.push_back(ExtractedFromVec);
10235     }
10236     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10237   }
10238
10239   assert((VT.is128BitVector() || VT.is256BitVector()) &&
10240          "Not extracted from 128-/256-bit vector.");
10241
10242   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10243
10244   for (DenseMap<SDValue, unsigned>::const_iterator
10245         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10246     // Quit if not all elements are used.
10247     if (I->second != FullMask)
10248       return SDValue();
10249   }
10250
10251   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10252
10253   // Cast all vectors into TestVT for PTEST.
10254   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10255     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10256
10257   // If more than one full vectors are evaluated, OR them first before PTEST.
10258   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10259     // Each iteration will OR 2 nodes and append the result until there is only
10260     // 1 node left, i.e. the final OR'd value of all vectors.
10261     SDValue LHS = VecIns[Slot];
10262     SDValue RHS = VecIns[Slot + 1];
10263     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10264   }
10265
10266   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10267                      VecIns.back(), VecIns.back());
10268 }
10269
10270 /// \brief return true if \c Op has a use that doesn't just read flags.
10271 static bool hasNonFlagsUse(SDValue Op) {
10272   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10273        ++UI) {
10274     SDNode *User = *UI;
10275     unsigned UOpNo = UI.getOperandNo();
10276     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10277       // Look pass truncate.
10278       UOpNo = User->use_begin().getOperandNo();
10279       User = *User->use_begin();
10280     }
10281
10282     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10283         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10284       return true;
10285   }
10286   return false;
10287 }
10288
10289 /// Emit nodes that will be selected as "test Op0,Op0", or something
10290 /// equivalent.
10291 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10292                                     SelectionDAG &DAG) const {
10293   if (Op.getValueType() == MVT::i1)
10294     // KORTEST instruction should be selected
10295     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10296                        DAG.getConstant(0, Op.getValueType()));
10297
10298   // CF and OF aren't always set the way we want. Determine which
10299   // of these we need.
10300   bool NeedCF = false;
10301   bool NeedOF = false;
10302   switch (X86CC) {
10303   default: break;
10304   case X86::COND_A: case X86::COND_AE:
10305   case X86::COND_B: case X86::COND_BE:
10306     NeedCF = true;
10307     break;
10308   case X86::COND_G: case X86::COND_GE:
10309   case X86::COND_L: case X86::COND_LE:
10310   case X86::COND_O: case X86::COND_NO: {
10311     // Check if we really need to set the
10312     // Overflow flag. If NoSignedWrap is present
10313     // that is not actually needed.
10314     switch (Op->getOpcode()) {
10315     case ISD::ADD:
10316     case ISD::SUB:
10317     case ISD::MUL:
10318     case ISD::SHL: {
10319       const BinaryWithFlagsSDNode *BinNode =
10320           cast<BinaryWithFlagsSDNode>(Op.getNode());
10321       if (BinNode->hasNoSignedWrap())
10322         break;
10323     }
10324     default:
10325       NeedOF = true;
10326       break;
10327     }
10328     break;
10329   }
10330   }
10331   // See if we can use the EFLAGS value from the operand instead of
10332   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10333   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10334   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10335     // Emit a CMP with 0, which is the TEST pattern.
10336     //if (Op.getValueType() == MVT::i1)
10337     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10338     //                     DAG.getConstant(0, MVT::i1));
10339     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10340                        DAG.getConstant(0, Op.getValueType()));
10341   }
10342   unsigned Opcode = 0;
10343   unsigned NumOperands = 0;
10344
10345   // Truncate operations may prevent the merge of the SETCC instruction
10346   // and the arithmetic instruction before it. Attempt to truncate the operands
10347   // of the arithmetic instruction and use a reduced bit-width instruction.
10348   bool NeedTruncation = false;
10349   SDValue ArithOp = Op;
10350   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10351     SDValue Arith = Op->getOperand(0);
10352     // Both the trunc and the arithmetic op need to have one user each.
10353     if (Arith->hasOneUse())
10354       switch (Arith.getOpcode()) {
10355         default: break;
10356         case ISD::ADD:
10357         case ISD::SUB:
10358         case ISD::AND:
10359         case ISD::OR:
10360         case ISD::XOR: {
10361           NeedTruncation = true;
10362           ArithOp = Arith;
10363         }
10364       }
10365   }
10366
10367   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10368   // which may be the result of a CAST.  We use the variable 'Op', which is the
10369   // non-casted variable when we check for possible users.
10370   switch (ArithOp.getOpcode()) {
10371   case ISD::ADD:
10372     // Due to an isel shortcoming, be conservative if this add is likely to be
10373     // selected as part of a load-modify-store instruction. When the root node
10374     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10375     // uses of other nodes in the match, such as the ADD in this case. This
10376     // leads to the ADD being left around and reselected, with the result being
10377     // two adds in the output.  Alas, even if none our users are stores, that
10378     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10379     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10380     // climbing the DAG back to the root, and it doesn't seem to be worth the
10381     // effort.
10382     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10383          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10384       if (UI->getOpcode() != ISD::CopyToReg &&
10385           UI->getOpcode() != ISD::SETCC &&
10386           UI->getOpcode() != ISD::STORE)
10387         goto default_case;
10388
10389     if (ConstantSDNode *C =
10390         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10391       // An add of one will be selected as an INC.
10392       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10393         Opcode = X86ISD::INC;
10394         NumOperands = 1;
10395         break;
10396       }
10397
10398       // An add of negative one (subtract of one) will be selected as a DEC.
10399       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10400         Opcode = X86ISD::DEC;
10401         NumOperands = 1;
10402         break;
10403       }
10404     }
10405
10406     // Otherwise use a regular EFLAGS-setting add.
10407     Opcode = X86ISD::ADD;
10408     NumOperands = 2;
10409     break;
10410   case ISD::SHL:
10411   case ISD::SRL:
10412     // If we have a constant logical shift that's only used in a comparison
10413     // against zero turn it into an equivalent AND. This allows turning it into
10414     // a TEST instruction later.
10415     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10416         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10417       EVT VT = Op.getValueType();
10418       unsigned BitWidth = VT.getSizeInBits();
10419       unsigned ShAmt = Op->getConstantOperandVal(1);
10420       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10421         break;
10422       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10423                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10424                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10425       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10426         break;
10427       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10428                                 DAG.getConstant(Mask, VT));
10429       DAG.ReplaceAllUsesWith(Op, New);
10430       Op = New;
10431     }
10432     break;
10433
10434   case ISD::AND:
10435     // If the primary and result isn't used, don't bother using X86ISD::AND,
10436     // because a TEST instruction will be better.
10437     if (!hasNonFlagsUse(Op))
10438       break;
10439     // FALL THROUGH
10440   case ISD::SUB:
10441   case ISD::OR:
10442   case ISD::XOR:
10443     // Due to the ISEL shortcoming noted above, be conservative if this op is
10444     // likely to be selected as part of a load-modify-store instruction.
10445     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10446            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10447       if (UI->getOpcode() == ISD::STORE)
10448         goto default_case;
10449
10450     // Otherwise use a regular EFLAGS-setting instruction.
10451     switch (ArithOp.getOpcode()) {
10452     default: llvm_unreachable("unexpected operator!");
10453     case ISD::SUB: Opcode = X86ISD::SUB; break;
10454     case ISD::XOR: Opcode = X86ISD::XOR; break;
10455     case ISD::AND: Opcode = X86ISD::AND; break;
10456     case ISD::OR: {
10457       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10458         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10459         if (EFLAGS.getNode())
10460           return EFLAGS;
10461       }
10462       Opcode = X86ISD::OR;
10463       break;
10464     }
10465     }
10466
10467     NumOperands = 2;
10468     break;
10469   case X86ISD::ADD:
10470   case X86ISD::SUB:
10471   case X86ISD::INC:
10472   case X86ISD::DEC:
10473   case X86ISD::OR:
10474   case X86ISD::XOR:
10475   case X86ISD::AND:
10476     return SDValue(Op.getNode(), 1);
10477   default:
10478   default_case:
10479     break;
10480   }
10481
10482   // If we found that truncation is beneficial, perform the truncation and
10483   // update 'Op'.
10484   if (NeedTruncation) {
10485     EVT VT = Op.getValueType();
10486     SDValue WideVal = Op->getOperand(0);
10487     EVT WideVT = WideVal.getValueType();
10488     unsigned ConvertedOp = 0;
10489     // Use a target machine opcode to prevent further DAGCombine
10490     // optimizations that may separate the arithmetic operations
10491     // from the setcc node.
10492     switch (WideVal.getOpcode()) {
10493       default: break;
10494       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10495       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10496       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10497       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10498       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10499     }
10500
10501     if (ConvertedOp) {
10502       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10503       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10504         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10505         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10506         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10507       }
10508     }
10509   }
10510
10511   if (Opcode == 0)
10512     // Emit a CMP with 0, which is the TEST pattern.
10513     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10514                        DAG.getConstant(0, Op.getValueType()));
10515
10516   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10517   SmallVector<SDValue, 4> Ops;
10518   for (unsigned i = 0; i != NumOperands; ++i)
10519     Ops.push_back(Op.getOperand(i));
10520
10521   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10522   DAG.ReplaceAllUsesWith(Op, New);
10523   return SDValue(New.getNode(), 1);
10524 }
10525
10526 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10527 /// equivalent.
10528 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10529                                    SDLoc dl, SelectionDAG &DAG) const {
10530   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10531     if (C->getAPIntValue() == 0)
10532       return EmitTest(Op0, X86CC, dl, DAG);
10533
10534      if (Op0.getValueType() == MVT::i1)
10535        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10536   }
10537  
10538   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10539        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10540     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10541     // This avoids subregister aliasing issues. Keep the smaller reference 
10542     // if we're optimizing for size, however, as that'll allow better folding 
10543     // of memory operations.
10544     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10545         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10546              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10547         !Subtarget->isAtom()) {
10548       unsigned ExtendOp =
10549           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10550       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10551       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10552     }
10553     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10554     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10555     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10556                               Op0, Op1);
10557     return SDValue(Sub.getNode(), 1);
10558   }
10559   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10560 }
10561
10562 /// Convert a comparison if required by the subtarget.
10563 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10564                                                  SelectionDAG &DAG) const {
10565   // If the subtarget does not support the FUCOMI instruction, floating-point
10566   // comparisons have to be converted.
10567   if (Subtarget->hasCMov() ||
10568       Cmp.getOpcode() != X86ISD::CMP ||
10569       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10570       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10571     return Cmp;
10572
10573   // The instruction selector will select an FUCOM instruction instead of
10574   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10575   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10576   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10577   SDLoc dl(Cmp);
10578   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10579   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10580   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10581                             DAG.getConstant(8, MVT::i8));
10582   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10583   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10584 }
10585
10586 static bool isAllOnes(SDValue V) {
10587   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10588   return C && C->isAllOnesValue();
10589 }
10590
10591 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10592 /// if it's possible.
10593 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10594                                      SDLoc dl, SelectionDAG &DAG) const {
10595   SDValue Op0 = And.getOperand(0);
10596   SDValue Op1 = And.getOperand(1);
10597   if (Op0.getOpcode() == ISD::TRUNCATE)
10598     Op0 = Op0.getOperand(0);
10599   if (Op1.getOpcode() == ISD::TRUNCATE)
10600     Op1 = Op1.getOperand(0);
10601
10602   SDValue LHS, RHS;
10603   if (Op1.getOpcode() == ISD::SHL)
10604     std::swap(Op0, Op1);
10605   if (Op0.getOpcode() == ISD::SHL) {
10606     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10607       if (And00C->getZExtValue() == 1) {
10608         // If we looked past a truncate, check that it's only truncating away
10609         // known zeros.
10610         unsigned BitWidth = Op0.getValueSizeInBits();
10611         unsigned AndBitWidth = And.getValueSizeInBits();
10612         if (BitWidth > AndBitWidth) {
10613           APInt Zeros, Ones;
10614           DAG.computeKnownBits(Op0, Zeros, Ones);
10615           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10616             return SDValue();
10617         }
10618         LHS = Op1;
10619         RHS = Op0.getOperand(1);
10620       }
10621   } else if (Op1.getOpcode() == ISD::Constant) {
10622     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10623     uint64_t AndRHSVal = AndRHS->getZExtValue();
10624     SDValue AndLHS = Op0;
10625
10626     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10627       LHS = AndLHS.getOperand(0);
10628       RHS = AndLHS.getOperand(1);
10629     }
10630
10631     // Use BT if the immediate can't be encoded in a TEST instruction.
10632     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10633       LHS = AndLHS;
10634       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10635     }
10636   }
10637
10638   if (LHS.getNode()) {
10639     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10640     // instruction.  Since the shift amount is in-range-or-undefined, we know
10641     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10642     // the encoding for the i16 version is larger than the i32 version.
10643     // Also promote i16 to i32 for performance / code size reason.
10644     if (LHS.getValueType() == MVT::i8 ||
10645         LHS.getValueType() == MVT::i16)
10646       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10647
10648     // If the operand types disagree, extend the shift amount to match.  Since
10649     // BT ignores high bits (like shifts) we can use anyextend.
10650     if (LHS.getValueType() != RHS.getValueType())
10651       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10652
10653     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10654     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10655     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10656                        DAG.getConstant(Cond, MVT::i8), BT);
10657   }
10658
10659   return SDValue();
10660 }
10661
10662 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10663 /// mask CMPs.
10664 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10665                               SDValue &Op1) {
10666   unsigned SSECC;
10667   bool Swap = false;
10668
10669   // SSE Condition code mapping:
10670   //  0 - EQ
10671   //  1 - LT
10672   //  2 - LE
10673   //  3 - UNORD
10674   //  4 - NEQ
10675   //  5 - NLT
10676   //  6 - NLE
10677   //  7 - ORD
10678   switch (SetCCOpcode) {
10679   default: llvm_unreachable("Unexpected SETCC condition");
10680   case ISD::SETOEQ:
10681   case ISD::SETEQ:  SSECC = 0; break;
10682   case ISD::SETOGT:
10683   case ISD::SETGT:  Swap = true; // Fallthrough
10684   case ISD::SETLT:
10685   case ISD::SETOLT: SSECC = 1; break;
10686   case ISD::SETOGE:
10687   case ISD::SETGE:  Swap = true; // Fallthrough
10688   case ISD::SETLE:
10689   case ISD::SETOLE: SSECC = 2; break;
10690   case ISD::SETUO:  SSECC = 3; break;
10691   case ISD::SETUNE:
10692   case ISD::SETNE:  SSECC = 4; break;
10693   case ISD::SETULE: Swap = true; // Fallthrough
10694   case ISD::SETUGE: SSECC = 5; break;
10695   case ISD::SETULT: Swap = true; // Fallthrough
10696   case ISD::SETUGT: SSECC = 6; break;
10697   case ISD::SETO:   SSECC = 7; break;
10698   case ISD::SETUEQ:
10699   case ISD::SETONE: SSECC = 8; break;
10700   }
10701   if (Swap)
10702     std::swap(Op0, Op1);
10703
10704   return SSECC;
10705 }
10706
10707 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10708 // ones, and then concatenate the result back.
10709 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10710   MVT VT = Op.getSimpleValueType();
10711
10712   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10713          "Unsupported value type for operation");
10714
10715   unsigned NumElems = VT.getVectorNumElements();
10716   SDLoc dl(Op);
10717   SDValue CC = Op.getOperand(2);
10718
10719   // Extract the LHS vectors
10720   SDValue LHS = Op.getOperand(0);
10721   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10722   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10723
10724   // Extract the RHS vectors
10725   SDValue RHS = Op.getOperand(1);
10726   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10727   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10728
10729   // Issue the operation on the smaller types and concatenate the result back
10730   MVT EltVT = VT.getVectorElementType();
10731   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10732   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10733                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10734                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10735 }
10736
10737 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10738                                      const X86Subtarget *Subtarget) {
10739   SDValue Op0 = Op.getOperand(0);
10740   SDValue Op1 = Op.getOperand(1);
10741   SDValue CC = Op.getOperand(2);
10742   MVT VT = Op.getSimpleValueType();
10743   SDLoc dl(Op);
10744
10745   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10746          Op.getValueType().getScalarType() == MVT::i1 &&
10747          "Cannot set masked compare for this operation");
10748
10749   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10750   unsigned  Opc = 0;
10751   bool Unsigned = false;
10752   bool Swap = false;
10753   unsigned SSECC;
10754   switch (SetCCOpcode) {
10755   default: llvm_unreachable("Unexpected SETCC condition");
10756   case ISD::SETNE:  SSECC = 4; break;
10757   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10758   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10759   case ISD::SETLT:  Swap = true; //fall-through
10760   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10761   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10762   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10763   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10764   case ISD::SETULE: Unsigned = true; //fall-through
10765   case ISD::SETLE:  SSECC = 2; break;
10766   }
10767
10768   if (Swap)
10769     std::swap(Op0, Op1);
10770   if (Opc)
10771     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10772   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10773   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10774                      DAG.getConstant(SSECC, MVT::i8));
10775 }
10776
10777 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10778 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10779 /// return an empty value.
10780 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10781 {
10782   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10783   if (!BV)
10784     return SDValue();
10785
10786   MVT VT = Op1.getSimpleValueType();
10787   MVT EVT = VT.getVectorElementType();
10788   unsigned n = VT.getVectorNumElements();
10789   SmallVector<SDValue, 8> ULTOp1;
10790
10791   for (unsigned i = 0; i < n; ++i) {
10792     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10793     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10794       return SDValue();
10795
10796     // Avoid underflow.
10797     APInt Val = Elt->getAPIntValue();
10798     if (Val == 0)
10799       return SDValue();
10800
10801     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10802   }
10803
10804   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10805 }
10806
10807 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10808                            SelectionDAG &DAG) {
10809   SDValue Op0 = Op.getOperand(0);
10810   SDValue Op1 = Op.getOperand(1);
10811   SDValue CC = Op.getOperand(2);
10812   MVT VT = Op.getSimpleValueType();
10813   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10814   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10815   SDLoc dl(Op);
10816
10817   if (isFP) {
10818 #ifndef NDEBUG
10819     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10820     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10821 #endif
10822
10823     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10824     unsigned Opc = X86ISD::CMPP;
10825     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10826       assert(VT.getVectorNumElements() <= 16);
10827       Opc = X86ISD::CMPM;
10828     }
10829     // In the two special cases we can't handle, emit two comparisons.
10830     if (SSECC == 8) {
10831       unsigned CC0, CC1;
10832       unsigned CombineOpc;
10833       if (SetCCOpcode == ISD::SETUEQ) {
10834         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10835       } else {
10836         assert(SetCCOpcode == ISD::SETONE);
10837         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10838       }
10839
10840       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10841                                  DAG.getConstant(CC0, MVT::i8));
10842       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10843                                  DAG.getConstant(CC1, MVT::i8));
10844       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10845     }
10846     // Handle all other FP comparisons here.
10847     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10848                        DAG.getConstant(SSECC, MVT::i8));
10849   }
10850
10851   // Break 256-bit integer vector compare into smaller ones.
10852   if (VT.is256BitVector() && !Subtarget->hasInt256())
10853     return Lower256IntVSETCC(Op, DAG);
10854
10855   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10856   EVT OpVT = Op1.getValueType();
10857   if (Subtarget->hasAVX512()) {
10858     if (Op1.getValueType().is512BitVector() ||
10859         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10860       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10861
10862     // In AVX-512 architecture setcc returns mask with i1 elements,
10863     // But there is no compare instruction for i8 and i16 elements.
10864     // We are not talking about 512-bit operands in this case, these
10865     // types are illegal.
10866     if (MaskResult &&
10867         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10868          OpVT.getVectorElementType().getSizeInBits() >= 8))
10869       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10870                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10871   }
10872
10873   // We are handling one of the integer comparisons here.  Since SSE only has
10874   // GT and EQ comparisons for integer, swapping operands and multiple
10875   // operations may be required for some comparisons.
10876   unsigned Opc;
10877   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10878   bool Subus = false;
10879
10880   switch (SetCCOpcode) {
10881   default: llvm_unreachable("Unexpected SETCC condition");
10882   case ISD::SETNE:  Invert = true;
10883   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10884   case ISD::SETLT:  Swap = true;
10885   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10886   case ISD::SETGE:  Swap = true;
10887   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10888                     Invert = true; break;
10889   case ISD::SETULT: Swap = true;
10890   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10891                     FlipSigns = true; break;
10892   case ISD::SETUGE: Swap = true;
10893   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10894                     FlipSigns = true; Invert = true; break;
10895   }
10896
10897   // Special case: Use min/max operations for SETULE/SETUGE
10898   MVT VET = VT.getVectorElementType();
10899   bool hasMinMax =
10900        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10901     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10902
10903   if (hasMinMax) {
10904     switch (SetCCOpcode) {
10905     default: break;
10906     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10907     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10908     }
10909
10910     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10911   }
10912
10913   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10914   if (!MinMax && hasSubus) {
10915     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10916     // Op0 u<= Op1:
10917     //   t = psubus Op0, Op1
10918     //   pcmpeq t, <0..0>
10919     switch (SetCCOpcode) {
10920     default: break;
10921     case ISD::SETULT: {
10922       // If the comparison is against a constant we can turn this into a
10923       // setule.  With psubus, setule does not require a swap.  This is
10924       // beneficial because the constant in the register is no longer
10925       // destructed as the destination so it can be hoisted out of a loop.
10926       // Only do this pre-AVX since vpcmp* is no longer destructive.
10927       if (Subtarget->hasAVX())
10928         break;
10929       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10930       if (ULEOp1.getNode()) {
10931         Op1 = ULEOp1;
10932         Subus = true; Invert = false; Swap = false;
10933       }
10934       break;
10935     }
10936     // Psubus is better than flip-sign because it requires no inversion.
10937     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10938     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10939     }
10940
10941     if (Subus) {
10942       Opc = X86ISD::SUBUS;
10943       FlipSigns = false;
10944     }
10945   }
10946
10947   if (Swap)
10948     std::swap(Op0, Op1);
10949
10950   // Check that the operation in question is available (most are plain SSE2,
10951   // but PCMPGTQ and PCMPEQQ have different requirements).
10952   if (VT == MVT::v2i64) {
10953     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10954       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10955
10956       // First cast everything to the right type.
10957       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10958       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10959
10960       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10961       // bits of the inputs before performing those operations. The lower
10962       // compare is always unsigned.
10963       SDValue SB;
10964       if (FlipSigns) {
10965         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10966       } else {
10967         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10968         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10969         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10970                          Sign, Zero, Sign, Zero);
10971       }
10972       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10973       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10974
10975       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10976       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10977       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10978
10979       // Create masks for only the low parts/high parts of the 64 bit integers.
10980       static const int MaskHi[] = { 1, 1, 3, 3 };
10981       static const int MaskLo[] = { 0, 0, 2, 2 };
10982       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10983       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10984       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10985
10986       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10987       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10988
10989       if (Invert)
10990         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10991
10992       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10993     }
10994
10995     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10996       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10997       // pcmpeqd + pshufd + pand.
10998       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10999
11000       // First cast everything to the right type.
11001       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11002       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11003
11004       // Do the compare.
11005       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
11006
11007       // Make sure the lower and upper halves are both all-ones.
11008       static const int Mask[] = { 1, 0, 3, 2 };
11009       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
11010       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
11011
11012       if (Invert)
11013         Result = DAG.getNOT(dl, Result, MVT::v4i32);
11014
11015       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11016     }
11017   }
11018
11019   // Since SSE has no unsigned integer comparisons, we need to flip the sign
11020   // bits of the inputs before performing those operations.
11021   if (FlipSigns) {
11022     EVT EltVT = VT.getVectorElementType();
11023     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
11024     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
11025     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
11026   }
11027
11028   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
11029
11030   // If the logical-not of the result is required, perform that now.
11031   if (Invert)
11032     Result = DAG.getNOT(dl, Result, VT);
11033
11034   if (MinMax)
11035     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
11036
11037   if (Subus)
11038     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
11039                          getZeroVector(VT, Subtarget, DAG, dl));
11040
11041   return Result;
11042 }
11043
11044 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
11045
11046   MVT VT = Op.getSimpleValueType();
11047
11048   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
11049
11050   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
11051          && "SetCC type must be 8-bit or 1-bit integer");
11052   SDValue Op0 = Op.getOperand(0);
11053   SDValue Op1 = Op.getOperand(1);
11054   SDLoc dl(Op);
11055   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11056
11057   // Optimize to BT if possible.
11058   // Lower (X & (1 << N)) == 0 to BT(X, N).
11059   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
11060   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
11061   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
11062       Op1.getOpcode() == ISD::Constant &&
11063       cast<ConstantSDNode>(Op1)->isNullValue() &&
11064       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11065     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
11066     if (NewSetCC.getNode())
11067       return NewSetCC;
11068   }
11069
11070   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
11071   // these.
11072   if (Op1.getOpcode() == ISD::Constant &&
11073       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
11074        cast<ConstantSDNode>(Op1)->isNullValue()) &&
11075       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11076
11077     // If the input is a setcc, then reuse the input setcc or use a new one with
11078     // the inverted condition.
11079     if (Op0.getOpcode() == X86ISD::SETCC) {
11080       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
11081       bool Invert = (CC == ISD::SETNE) ^
11082         cast<ConstantSDNode>(Op1)->isNullValue();
11083       if (!Invert)
11084         return Op0;
11085
11086       CCode = X86::GetOppositeBranchCondition(CCode);
11087       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11088                                   DAG.getConstant(CCode, MVT::i8),
11089                                   Op0.getOperand(1));
11090       if (VT == MVT::i1)
11091         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11092       return SetCC;
11093     }
11094   }
11095   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11096       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11097       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11098
11099     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11100     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11101   }
11102
11103   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
11104   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
11105   if (X86CC == X86::COND_INVALID)
11106     return SDValue();
11107
11108   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
11109   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11110   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11111                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11112   if (VT == MVT::i1)
11113     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11114   return SetCC;
11115 }
11116
11117 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11118 static bool isX86LogicalCmp(SDValue Op) {
11119   unsigned Opc = Op.getNode()->getOpcode();
11120   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11121       Opc == X86ISD::SAHF)
11122     return true;
11123   if (Op.getResNo() == 1 &&
11124       (Opc == X86ISD::ADD ||
11125        Opc == X86ISD::SUB ||
11126        Opc == X86ISD::ADC ||
11127        Opc == X86ISD::SBB ||
11128        Opc == X86ISD::SMUL ||
11129        Opc == X86ISD::UMUL ||
11130        Opc == X86ISD::INC ||
11131        Opc == X86ISD::DEC ||
11132        Opc == X86ISD::OR ||
11133        Opc == X86ISD::XOR ||
11134        Opc == X86ISD::AND))
11135     return true;
11136
11137   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11138     return true;
11139
11140   return false;
11141 }
11142
11143 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11144   if (V.getOpcode() != ISD::TRUNCATE)
11145     return false;
11146
11147   SDValue VOp0 = V.getOperand(0);
11148   unsigned InBits = VOp0.getValueSizeInBits();
11149   unsigned Bits = V.getValueSizeInBits();
11150   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11151 }
11152
11153 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11154   bool addTest = true;
11155   SDValue Cond  = Op.getOperand(0);
11156   SDValue Op1 = Op.getOperand(1);
11157   SDValue Op2 = Op.getOperand(2);
11158   SDLoc DL(Op);
11159   EVT VT = Op1.getValueType();
11160   SDValue CC;
11161
11162   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11163   // are available. Otherwise fp cmovs get lowered into a less efficient branch
11164   // sequence later on.
11165   if (Cond.getOpcode() == ISD::SETCC &&
11166       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11167        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11168       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11169     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11170     int SSECC = translateX86FSETCC(
11171         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11172
11173     if (SSECC != 8) {
11174       if (Subtarget->hasAVX512()) {
11175         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11176                                   DAG.getConstant(SSECC, MVT::i8));
11177         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11178       }
11179       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11180                                 DAG.getConstant(SSECC, MVT::i8));
11181       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11182       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11183       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11184     }
11185   }
11186
11187   if (Cond.getOpcode() == ISD::SETCC) {
11188     SDValue NewCond = LowerSETCC(Cond, DAG);
11189     if (NewCond.getNode())
11190       Cond = NewCond;
11191   }
11192
11193   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11194   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11195   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11196   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11197   if (Cond.getOpcode() == X86ISD::SETCC &&
11198       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11199       isZero(Cond.getOperand(1).getOperand(1))) {
11200     SDValue Cmp = Cond.getOperand(1);
11201
11202     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11203
11204     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11205         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11206       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11207
11208       SDValue CmpOp0 = Cmp.getOperand(0);
11209       // Apply further optimizations for special cases
11210       // (select (x != 0), -1, 0) -> neg & sbb
11211       // (select (x == 0), 0, -1) -> neg & sbb
11212       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11213         if (YC->isNullValue() &&
11214             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11215           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11216           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11217                                     DAG.getConstant(0, CmpOp0.getValueType()),
11218                                     CmpOp0);
11219           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11220                                     DAG.getConstant(X86::COND_B, MVT::i8),
11221                                     SDValue(Neg.getNode(), 1));
11222           return Res;
11223         }
11224
11225       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11226                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11227       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11228
11229       SDValue Res =   // Res = 0 or -1.
11230         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11231                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11232
11233       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11234         Res = DAG.getNOT(DL, Res, Res.getValueType());
11235
11236       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11237       if (!N2C || !N2C->isNullValue())
11238         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11239       return Res;
11240     }
11241   }
11242
11243   // Look past (and (setcc_carry (cmp ...)), 1).
11244   if (Cond.getOpcode() == ISD::AND &&
11245       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11246     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11247     if (C && C->getAPIntValue() == 1)
11248       Cond = Cond.getOperand(0);
11249   }
11250
11251   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11252   // setting operand in place of the X86ISD::SETCC.
11253   unsigned CondOpcode = Cond.getOpcode();
11254   if (CondOpcode == X86ISD::SETCC ||
11255       CondOpcode == X86ISD::SETCC_CARRY) {
11256     CC = Cond.getOperand(0);
11257
11258     SDValue Cmp = Cond.getOperand(1);
11259     unsigned Opc = Cmp.getOpcode();
11260     MVT VT = Op.getSimpleValueType();
11261
11262     bool IllegalFPCMov = false;
11263     if (VT.isFloatingPoint() && !VT.isVector() &&
11264         !isScalarFPTypeInSSEReg(VT))  // FPStack?
11265       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11266
11267     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11268         Opc == X86ISD::BT) { // FIXME
11269       Cond = Cmp;
11270       addTest = false;
11271     }
11272   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11273              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11274              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11275               Cond.getOperand(0).getValueType() != MVT::i8)) {
11276     SDValue LHS = Cond.getOperand(0);
11277     SDValue RHS = Cond.getOperand(1);
11278     unsigned X86Opcode;
11279     unsigned X86Cond;
11280     SDVTList VTs;
11281     switch (CondOpcode) {
11282     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11283     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11284     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11285     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11286     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11287     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11288     default: llvm_unreachable("unexpected overflowing operator");
11289     }
11290     if (CondOpcode == ISD::UMULO)
11291       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11292                           MVT::i32);
11293     else
11294       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11295
11296     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11297
11298     if (CondOpcode == ISD::UMULO)
11299       Cond = X86Op.getValue(2);
11300     else
11301       Cond = X86Op.getValue(1);
11302
11303     CC = DAG.getConstant(X86Cond, MVT::i8);
11304     addTest = false;
11305   }
11306
11307   if (addTest) {
11308     // Look pass the truncate if the high bits are known zero.
11309     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11310         Cond = Cond.getOperand(0);
11311
11312     // We know the result of AND is compared against zero. Try to match
11313     // it to BT.
11314     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11315       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11316       if (NewSetCC.getNode()) {
11317         CC = NewSetCC.getOperand(0);
11318         Cond = NewSetCC.getOperand(1);
11319         addTest = false;
11320       }
11321     }
11322   }
11323
11324   if (addTest) {
11325     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11326     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11327   }
11328
11329   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11330   // a <  b ?  0 : -1 -> RES = setcc_carry
11331   // a >= b ? -1 :  0 -> RES = setcc_carry
11332   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11333   if (Cond.getOpcode() == X86ISD::SUB) {
11334     Cond = ConvertCmpIfNecessary(Cond, DAG);
11335     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11336
11337     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11338         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11339       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11340                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11341       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11342         return DAG.getNOT(DL, Res, Res.getValueType());
11343       return Res;
11344     }
11345   }
11346
11347   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11348   // widen the cmov and push the truncate through. This avoids introducing a new
11349   // branch during isel and doesn't add any extensions.
11350   if (Op.getValueType() == MVT::i8 &&
11351       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11352     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11353     if (T1.getValueType() == T2.getValueType() &&
11354         // Blacklist CopyFromReg to avoid partial register stalls.
11355         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11356       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11357       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11358       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11359     }
11360   }
11361
11362   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11363   // condition is true.
11364   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11365   SDValue Ops[] = { Op2, Op1, CC, Cond };
11366   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11367 }
11368
11369 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11370   MVT VT = Op->getSimpleValueType(0);
11371   SDValue In = Op->getOperand(0);
11372   MVT InVT = In.getSimpleValueType();
11373   SDLoc dl(Op);
11374
11375   unsigned int NumElts = VT.getVectorNumElements();
11376   if (NumElts != 8 && NumElts != 16)
11377     return SDValue();
11378
11379   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11380     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11381
11382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11383   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11384
11385   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11386   Constant *C = ConstantInt::get(*DAG.getContext(),
11387     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11388
11389   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11390   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11391   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11392                           MachinePointerInfo::getConstantPool(),
11393                           false, false, false, Alignment);
11394   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11395   if (VT.is512BitVector())
11396     return Brcst;
11397   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11398 }
11399
11400 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11401                                 SelectionDAG &DAG) {
11402   MVT VT = Op->getSimpleValueType(0);
11403   SDValue In = Op->getOperand(0);
11404   MVT InVT = In.getSimpleValueType();
11405   SDLoc dl(Op);
11406
11407   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11408     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11409
11410   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11411       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11412       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11413     return SDValue();
11414
11415   if (Subtarget->hasInt256())
11416     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11417
11418   // Optimize vectors in AVX mode
11419   // Sign extend  v8i16 to v8i32 and
11420   //              v4i32 to v4i64
11421   //
11422   // Divide input vector into two parts
11423   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11424   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11425   // concat the vectors to original VT
11426
11427   unsigned NumElems = InVT.getVectorNumElements();
11428   SDValue Undef = DAG.getUNDEF(InVT);
11429
11430   SmallVector<int,8> ShufMask1(NumElems, -1);
11431   for (unsigned i = 0; i != NumElems/2; ++i)
11432     ShufMask1[i] = i;
11433
11434   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11435
11436   SmallVector<int,8> ShufMask2(NumElems, -1);
11437   for (unsigned i = 0; i != NumElems/2; ++i)
11438     ShufMask2[i] = i + NumElems/2;
11439
11440   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11441
11442   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11443                                 VT.getVectorNumElements()/2);
11444
11445   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11446   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11447
11448   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11449 }
11450
11451 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11452 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11453 // from the AND / OR.
11454 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11455   Opc = Op.getOpcode();
11456   if (Opc != ISD::OR && Opc != ISD::AND)
11457     return false;
11458   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11459           Op.getOperand(0).hasOneUse() &&
11460           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11461           Op.getOperand(1).hasOneUse());
11462 }
11463
11464 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11465 // 1 and that the SETCC node has a single use.
11466 static bool isXor1OfSetCC(SDValue Op) {
11467   if (Op.getOpcode() != ISD::XOR)
11468     return false;
11469   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11470   if (N1C && N1C->getAPIntValue() == 1) {
11471     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11472       Op.getOperand(0).hasOneUse();
11473   }
11474   return false;
11475 }
11476
11477 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11478   bool addTest = true;
11479   SDValue Chain = Op.getOperand(0);
11480   SDValue Cond  = Op.getOperand(1);
11481   SDValue Dest  = Op.getOperand(2);
11482   SDLoc dl(Op);
11483   SDValue CC;
11484   bool Inverted = false;
11485
11486   if (Cond.getOpcode() == ISD::SETCC) {
11487     // Check for setcc([su]{add,sub,mul}o == 0).
11488     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11489         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11490         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11491         Cond.getOperand(0).getResNo() == 1 &&
11492         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11493          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11494          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11495          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11496          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11497          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11498       Inverted = true;
11499       Cond = Cond.getOperand(0);
11500     } else {
11501       SDValue NewCond = LowerSETCC(Cond, DAG);
11502       if (NewCond.getNode())
11503         Cond = NewCond;
11504     }
11505   }
11506 #if 0
11507   // FIXME: LowerXALUO doesn't handle these!!
11508   else if (Cond.getOpcode() == X86ISD::ADD  ||
11509            Cond.getOpcode() == X86ISD::SUB  ||
11510            Cond.getOpcode() == X86ISD::SMUL ||
11511            Cond.getOpcode() == X86ISD::UMUL)
11512     Cond = LowerXALUO(Cond, DAG);
11513 #endif
11514
11515   // Look pass (and (setcc_carry (cmp ...)), 1).
11516   if (Cond.getOpcode() == ISD::AND &&
11517       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11518     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11519     if (C && C->getAPIntValue() == 1)
11520       Cond = Cond.getOperand(0);
11521   }
11522
11523   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11524   // setting operand in place of the X86ISD::SETCC.
11525   unsigned CondOpcode = Cond.getOpcode();
11526   if (CondOpcode == X86ISD::SETCC ||
11527       CondOpcode == X86ISD::SETCC_CARRY) {
11528     CC = Cond.getOperand(0);
11529
11530     SDValue Cmp = Cond.getOperand(1);
11531     unsigned Opc = Cmp.getOpcode();
11532     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11533     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11534       Cond = Cmp;
11535       addTest = false;
11536     } else {
11537       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11538       default: break;
11539       case X86::COND_O:
11540       case X86::COND_B:
11541         // These can only come from an arithmetic instruction with overflow,
11542         // e.g. SADDO, UADDO.
11543         Cond = Cond.getNode()->getOperand(1);
11544         addTest = false;
11545         break;
11546       }
11547     }
11548   }
11549   CondOpcode = Cond.getOpcode();
11550   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11551       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11552       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11553        Cond.getOperand(0).getValueType() != MVT::i8)) {
11554     SDValue LHS = Cond.getOperand(0);
11555     SDValue RHS = Cond.getOperand(1);
11556     unsigned X86Opcode;
11557     unsigned X86Cond;
11558     SDVTList VTs;
11559     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11560     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11561     // X86ISD::INC).
11562     switch (CondOpcode) {
11563     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11564     case ISD::SADDO:
11565       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11566         if (C->isOne()) {
11567           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11568           break;
11569         }
11570       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11571     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11572     case ISD::SSUBO:
11573       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11574         if (C->isOne()) {
11575           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11576           break;
11577         }
11578       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11579     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11580     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11581     default: llvm_unreachable("unexpected overflowing operator");
11582     }
11583     if (Inverted)
11584       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11585     if (CondOpcode == ISD::UMULO)
11586       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11587                           MVT::i32);
11588     else
11589       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11590
11591     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11592
11593     if (CondOpcode == ISD::UMULO)
11594       Cond = X86Op.getValue(2);
11595     else
11596       Cond = X86Op.getValue(1);
11597
11598     CC = DAG.getConstant(X86Cond, MVT::i8);
11599     addTest = false;
11600   } else {
11601     unsigned CondOpc;
11602     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11603       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11604       if (CondOpc == ISD::OR) {
11605         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11606         // two branches instead of an explicit OR instruction with a
11607         // separate test.
11608         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11609             isX86LogicalCmp(Cmp)) {
11610           CC = Cond.getOperand(0).getOperand(0);
11611           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11612                               Chain, Dest, CC, Cmp);
11613           CC = Cond.getOperand(1).getOperand(0);
11614           Cond = Cmp;
11615           addTest = false;
11616         }
11617       } else { // ISD::AND
11618         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11619         // two branches instead of an explicit AND instruction with a
11620         // separate test. However, we only do this if this block doesn't
11621         // have a fall-through edge, because this requires an explicit
11622         // jmp when the condition is false.
11623         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11624             isX86LogicalCmp(Cmp) &&
11625             Op.getNode()->hasOneUse()) {
11626           X86::CondCode CCode =
11627             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11628           CCode = X86::GetOppositeBranchCondition(CCode);
11629           CC = DAG.getConstant(CCode, MVT::i8);
11630           SDNode *User = *Op.getNode()->use_begin();
11631           // Look for an unconditional branch following this conditional branch.
11632           // We need this because we need to reverse the successors in order
11633           // to implement FCMP_OEQ.
11634           if (User->getOpcode() == ISD::BR) {
11635             SDValue FalseBB = User->getOperand(1);
11636             SDNode *NewBR =
11637               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11638             assert(NewBR == User);
11639             (void)NewBR;
11640             Dest = FalseBB;
11641
11642             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11643                                 Chain, Dest, CC, Cmp);
11644             X86::CondCode CCode =
11645               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11646             CCode = X86::GetOppositeBranchCondition(CCode);
11647             CC = DAG.getConstant(CCode, MVT::i8);
11648             Cond = Cmp;
11649             addTest = false;
11650           }
11651         }
11652       }
11653     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11654       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11655       // It should be transformed during dag combiner except when the condition
11656       // is set by a arithmetics with overflow node.
11657       X86::CondCode CCode =
11658         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11659       CCode = X86::GetOppositeBranchCondition(CCode);
11660       CC = DAG.getConstant(CCode, MVT::i8);
11661       Cond = Cond.getOperand(0).getOperand(1);
11662       addTest = false;
11663     } else if (Cond.getOpcode() == ISD::SETCC &&
11664                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11665       // For FCMP_OEQ, we can emit
11666       // two branches instead of an explicit AND instruction with a
11667       // separate test. However, we only do this if this block doesn't
11668       // have a fall-through edge, because this requires an explicit
11669       // jmp when the condition is false.
11670       if (Op.getNode()->hasOneUse()) {
11671         SDNode *User = *Op.getNode()->use_begin();
11672         // Look for an unconditional branch following this conditional branch.
11673         // We need this because we need to reverse the successors in order
11674         // to implement FCMP_OEQ.
11675         if (User->getOpcode() == ISD::BR) {
11676           SDValue FalseBB = User->getOperand(1);
11677           SDNode *NewBR =
11678             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11679           assert(NewBR == User);
11680           (void)NewBR;
11681           Dest = FalseBB;
11682
11683           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11684                                     Cond.getOperand(0), Cond.getOperand(1));
11685           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11686           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11687           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11688                               Chain, Dest, CC, Cmp);
11689           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11690           Cond = Cmp;
11691           addTest = false;
11692         }
11693       }
11694     } else if (Cond.getOpcode() == ISD::SETCC &&
11695                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11696       // For FCMP_UNE, we can emit
11697       // two branches instead of an explicit AND instruction with a
11698       // separate test. However, we only do this if this block doesn't
11699       // have a fall-through edge, because this requires an explicit
11700       // jmp when the condition is false.
11701       if (Op.getNode()->hasOneUse()) {
11702         SDNode *User = *Op.getNode()->use_begin();
11703         // Look for an unconditional branch following this conditional branch.
11704         // We need this because we need to reverse the successors in order
11705         // to implement FCMP_UNE.
11706         if (User->getOpcode() == ISD::BR) {
11707           SDValue FalseBB = User->getOperand(1);
11708           SDNode *NewBR =
11709             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11710           assert(NewBR == User);
11711           (void)NewBR;
11712
11713           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11714                                     Cond.getOperand(0), Cond.getOperand(1));
11715           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11716           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11717           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11718                               Chain, Dest, CC, Cmp);
11719           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11720           Cond = Cmp;
11721           addTest = false;
11722           Dest = FalseBB;
11723         }
11724       }
11725     }
11726   }
11727
11728   if (addTest) {
11729     // Look pass the truncate if the high bits are known zero.
11730     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11731         Cond = Cond.getOperand(0);
11732
11733     // We know the result of AND is compared against zero. Try to match
11734     // it to BT.
11735     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11736       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11737       if (NewSetCC.getNode()) {
11738         CC = NewSetCC.getOperand(0);
11739         Cond = NewSetCC.getOperand(1);
11740         addTest = false;
11741       }
11742     }
11743   }
11744
11745   if (addTest) {
11746     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11747     CC = DAG.getConstant(X86Cond, MVT::i8);
11748     Cond = EmitTest(Cond, X86Cond, dl, DAG);
11749   }
11750   Cond = ConvertCmpIfNecessary(Cond, DAG);
11751   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11752                      Chain, Dest, CC, Cond);
11753 }
11754
11755 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11756 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11757 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11758 // that the guard pages used by the OS virtual memory manager are allocated in
11759 // correct sequence.
11760 SDValue
11761 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11762                                            SelectionDAG &DAG) const {
11763   MachineFunction &MF = DAG.getMachineFunction();
11764   bool SplitStack = MF.shouldSplitStack();
11765   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11766                SplitStack;
11767   SDLoc dl(Op);
11768
11769   if (!Lower) {
11770     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11771     SDNode* Node = Op.getNode();
11772
11773     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11774     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11775         " not tell us which reg is the stack pointer!");
11776     EVT VT = Node->getValueType(0);
11777     SDValue Tmp1 = SDValue(Node, 0);
11778     SDValue Tmp2 = SDValue(Node, 1);
11779     SDValue Tmp3 = Node->getOperand(2);
11780     SDValue Chain = Tmp1.getOperand(0);
11781
11782     // Chain the dynamic stack allocation so that it doesn't modify the stack
11783     // pointer when other instructions are using the stack.
11784     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11785         SDLoc(Node));
11786
11787     SDValue Size = Tmp2.getOperand(1);
11788     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11789     Chain = SP.getValue(1);
11790     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11791     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
11792     unsigned StackAlign = TFI.getStackAlignment();
11793     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11794     if (Align > StackAlign)
11795       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11796           DAG.getConstant(-(uint64_t)Align, VT));
11797     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11798
11799     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11800         DAG.getIntPtrConstant(0, true), SDValue(),
11801         SDLoc(Node));
11802
11803     SDValue Ops[2] = { Tmp1, Tmp2 };
11804     return DAG.getMergeValues(Ops, dl);
11805   }
11806
11807   // Get the inputs.
11808   SDValue Chain = Op.getOperand(0);
11809   SDValue Size  = Op.getOperand(1);
11810   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11811   EVT VT = Op.getNode()->getValueType(0);
11812
11813   bool Is64Bit = Subtarget->is64Bit();
11814   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11815
11816   if (SplitStack) {
11817     MachineRegisterInfo &MRI = MF.getRegInfo();
11818
11819     if (Is64Bit) {
11820       // The 64 bit implementation of segmented stacks needs to clobber both r10
11821       // r11. This makes it impossible to use it along with nested parameters.
11822       const Function *F = MF.getFunction();
11823
11824       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11825            I != E; ++I)
11826         if (I->hasNestAttr())
11827           report_fatal_error("Cannot use segmented stacks with functions that "
11828                              "have nested arguments.");
11829     }
11830
11831     const TargetRegisterClass *AddrRegClass =
11832       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11833     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11834     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11835     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11836                                 DAG.getRegister(Vreg, SPTy));
11837     SDValue Ops1[2] = { Value, Chain };
11838     return DAG.getMergeValues(Ops1, dl);
11839   } else {
11840     SDValue Flag;
11841     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11842
11843     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11844     Flag = Chain.getValue(1);
11845     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11846
11847     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11848
11849     const X86RegisterInfo *RegInfo =
11850       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
11851     unsigned SPReg = RegInfo->getStackRegister();
11852     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11853     Chain = SP.getValue(1);
11854
11855     if (Align) {
11856       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11857                        DAG.getConstant(-(uint64_t)Align, VT));
11858       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11859     }
11860
11861     SDValue Ops1[2] = { SP, Chain };
11862     return DAG.getMergeValues(Ops1, dl);
11863   }
11864 }
11865
11866 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11867   MachineFunction &MF = DAG.getMachineFunction();
11868   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11869
11870   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11871   SDLoc DL(Op);
11872
11873   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11874     // vastart just stores the address of the VarArgsFrameIndex slot into the
11875     // memory location argument.
11876     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11877                                    getPointerTy());
11878     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11879                         MachinePointerInfo(SV), false, false, 0);
11880   }
11881
11882   // __va_list_tag:
11883   //   gp_offset         (0 - 6 * 8)
11884   //   fp_offset         (48 - 48 + 8 * 16)
11885   //   overflow_arg_area (point to parameters coming in memory).
11886   //   reg_save_area
11887   SmallVector<SDValue, 8> MemOps;
11888   SDValue FIN = Op.getOperand(1);
11889   // Store gp_offset
11890   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11891                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11892                                                MVT::i32),
11893                                FIN, MachinePointerInfo(SV), false, false, 0);
11894   MemOps.push_back(Store);
11895
11896   // Store fp_offset
11897   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11898                     FIN, DAG.getIntPtrConstant(4));
11899   Store = DAG.getStore(Op.getOperand(0), DL,
11900                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11901                                        MVT::i32),
11902                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11903   MemOps.push_back(Store);
11904
11905   // Store ptr to overflow_arg_area
11906   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11907                     FIN, DAG.getIntPtrConstant(4));
11908   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11909                                     getPointerTy());
11910   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11911                        MachinePointerInfo(SV, 8),
11912                        false, false, 0);
11913   MemOps.push_back(Store);
11914
11915   // Store ptr to reg_save_area.
11916   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11917                     FIN, DAG.getIntPtrConstant(8));
11918   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11919                                     getPointerTy());
11920   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11921                        MachinePointerInfo(SV, 16), false, false, 0);
11922   MemOps.push_back(Store);
11923   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11924 }
11925
11926 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11927   assert(Subtarget->is64Bit() &&
11928          "LowerVAARG only handles 64-bit va_arg!");
11929   assert((Subtarget->isTargetLinux() ||
11930           Subtarget->isTargetDarwin()) &&
11931           "Unhandled target in LowerVAARG");
11932   assert(Op.getNode()->getNumOperands() == 4);
11933   SDValue Chain = Op.getOperand(0);
11934   SDValue SrcPtr = Op.getOperand(1);
11935   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11936   unsigned Align = Op.getConstantOperandVal(3);
11937   SDLoc dl(Op);
11938
11939   EVT ArgVT = Op.getNode()->getValueType(0);
11940   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11941   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11942   uint8_t ArgMode;
11943
11944   // Decide which area this value should be read from.
11945   // TODO: Implement the AMD64 ABI in its entirety. This simple
11946   // selection mechanism works only for the basic types.
11947   if (ArgVT == MVT::f80) {
11948     llvm_unreachable("va_arg for f80 not yet implemented");
11949   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11950     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11951   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11952     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11953   } else {
11954     llvm_unreachable("Unhandled argument type in LowerVAARG");
11955   }
11956
11957   if (ArgMode == 2) {
11958     // Sanity Check: Make sure using fp_offset makes sense.
11959     assert(!DAG.getTarget().Options.UseSoftFloat &&
11960            !(DAG.getMachineFunction()
11961                 .getFunction()->getAttributes()
11962                 .hasAttribute(AttributeSet::FunctionIndex,
11963                               Attribute::NoImplicitFloat)) &&
11964            Subtarget->hasSSE1());
11965   }
11966
11967   // Insert VAARG_64 node into the DAG
11968   // VAARG_64 returns two values: Variable Argument Address, Chain
11969   SmallVector<SDValue, 11> InstOps;
11970   InstOps.push_back(Chain);
11971   InstOps.push_back(SrcPtr);
11972   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11973   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11974   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11975   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11976   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11977                                           VTs, InstOps, MVT::i64,
11978                                           MachinePointerInfo(SV),
11979                                           /*Align=*/0,
11980                                           /*Volatile=*/false,
11981                                           /*ReadMem=*/true,
11982                                           /*WriteMem=*/true);
11983   Chain = VAARG.getValue(1);
11984
11985   // Load the next argument and return it
11986   return DAG.getLoad(ArgVT, dl,
11987                      Chain,
11988                      VAARG,
11989                      MachinePointerInfo(),
11990                      false, false, false, 0);
11991 }
11992
11993 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11994                            SelectionDAG &DAG) {
11995   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11996   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11997   SDValue Chain = Op.getOperand(0);
11998   SDValue DstPtr = Op.getOperand(1);
11999   SDValue SrcPtr = Op.getOperand(2);
12000   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
12001   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12002   SDLoc DL(Op);
12003
12004   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
12005                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
12006                        false,
12007                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
12008 }
12009
12010 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
12011 // amount is a constant. Takes immediate version of shift as input.
12012 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
12013                                           SDValue SrcOp, uint64_t ShiftAmt,
12014                                           SelectionDAG &DAG) {
12015   MVT ElementType = VT.getVectorElementType();
12016
12017   // Fold this packed shift into its first operand if ShiftAmt is 0.
12018   if (ShiftAmt == 0)
12019     return SrcOp;
12020
12021   // Check for ShiftAmt >= element width
12022   if (ShiftAmt >= ElementType.getSizeInBits()) {
12023     if (Opc == X86ISD::VSRAI)
12024       ShiftAmt = ElementType.getSizeInBits() - 1;
12025     else
12026       return DAG.getConstant(0, VT);
12027   }
12028
12029   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
12030          && "Unknown target vector shift-by-constant node");
12031
12032   // Fold this packed vector shift into a build vector if SrcOp is a
12033   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
12034   if (VT == SrcOp.getSimpleValueType() &&
12035       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
12036     SmallVector<SDValue, 8> Elts;
12037     unsigned NumElts = SrcOp->getNumOperands();
12038     ConstantSDNode *ND;
12039
12040     switch(Opc) {
12041     default: llvm_unreachable(nullptr);
12042     case X86ISD::VSHLI:
12043       for (unsigned i=0; i!=NumElts; ++i) {
12044         SDValue CurrentOp = SrcOp->getOperand(i);
12045         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12046           Elts.push_back(CurrentOp);
12047           continue;
12048         }
12049         ND = cast<ConstantSDNode>(CurrentOp);
12050         const APInt &C = ND->getAPIntValue();
12051         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
12052       }
12053       break;
12054     case X86ISD::VSRLI:
12055       for (unsigned i=0; i!=NumElts; ++i) {
12056         SDValue CurrentOp = SrcOp->getOperand(i);
12057         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12058           Elts.push_back(CurrentOp);
12059           continue;
12060         }
12061         ND = cast<ConstantSDNode>(CurrentOp);
12062         const APInt &C = ND->getAPIntValue();
12063         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
12064       }
12065       break;
12066     case X86ISD::VSRAI:
12067       for (unsigned i=0; i!=NumElts; ++i) {
12068         SDValue CurrentOp = SrcOp->getOperand(i);
12069         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12070           Elts.push_back(CurrentOp);
12071           continue;
12072         }
12073         ND = cast<ConstantSDNode>(CurrentOp);
12074         const APInt &C = ND->getAPIntValue();
12075         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
12076       }
12077       break;
12078     }
12079
12080     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
12081   }
12082
12083   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
12084 }
12085
12086 // getTargetVShiftNode - Handle vector element shifts where the shift amount
12087 // may or may not be a constant. Takes immediate version of shift as input.
12088 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
12089                                    SDValue SrcOp, SDValue ShAmt,
12090                                    SelectionDAG &DAG) {
12091   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
12092
12093   // Catch shift-by-constant.
12094   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12095     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12096                                       CShAmt->getZExtValue(), DAG);
12097
12098   // Change opcode to non-immediate version
12099   switch (Opc) {
12100     default: llvm_unreachable("Unknown target vector shift node");
12101     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12102     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12103     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12104   }
12105
12106   // Need to build a vector containing shift amount
12107   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12108   SDValue ShOps[4];
12109   ShOps[0] = ShAmt;
12110   ShOps[1] = DAG.getConstant(0, MVT::i32);
12111   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12112   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12113
12114   // The return type has to be a 128-bit type with the same element
12115   // type as the input type.
12116   MVT EltVT = VT.getVectorElementType();
12117   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12118
12119   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12120   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12121 }
12122
12123 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12124   SDLoc dl(Op);
12125   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12126   switch (IntNo) {
12127   default: return SDValue();    // Don't custom lower most intrinsics.
12128   // Comparison intrinsics.
12129   case Intrinsic::x86_sse_comieq_ss:
12130   case Intrinsic::x86_sse_comilt_ss:
12131   case Intrinsic::x86_sse_comile_ss:
12132   case Intrinsic::x86_sse_comigt_ss:
12133   case Intrinsic::x86_sse_comige_ss:
12134   case Intrinsic::x86_sse_comineq_ss:
12135   case Intrinsic::x86_sse_ucomieq_ss:
12136   case Intrinsic::x86_sse_ucomilt_ss:
12137   case Intrinsic::x86_sse_ucomile_ss:
12138   case Intrinsic::x86_sse_ucomigt_ss:
12139   case Intrinsic::x86_sse_ucomige_ss:
12140   case Intrinsic::x86_sse_ucomineq_ss:
12141   case Intrinsic::x86_sse2_comieq_sd:
12142   case Intrinsic::x86_sse2_comilt_sd:
12143   case Intrinsic::x86_sse2_comile_sd:
12144   case Intrinsic::x86_sse2_comigt_sd:
12145   case Intrinsic::x86_sse2_comige_sd:
12146   case Intrinsic::x86_sse2_comineq_sd:
12147   case Intrinsic::x86_sse2_ucomieq_sd:
12148   case Intrinsic::x86_sse2_ucomilt_sd:
12149   case Intrinsic::x86_sse2_ucomile_sd:
12150   case Intrinsic::x86_sse2_ucomigt_sd:
12151   case Intrinsic::x86_sse2_ucomige_sd:
12152   case Intrinsic::x86_sse2_ucomineq_sd: {
12153     unsigned Opc;
12154     ISD::CondCode CC;
12155     switch (IntNo) {
12156     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12157     case Intrinsic::x86_sse_comieq_ss:
12158     case Intrinsic::x86_sse2_comieq_sd:
12159       Opc = X86ISD::COMI;
12160       CC = ISD::SETEQ;
12161       break;
12162     case Intrinsic::x86_sse_comilt_ss:
12163     case Intrinsic::x86_sse2_comilt_sd:
12164       Opc = X86ISD::COMI;
12165       CC = ISD::SETLT;
12166       break;
12167     case Intrinsic::x86_sse_comile_ss:
12168     case Intrinsic::x86_sse2_comile_sd:
12169       Opc = X86ISD::COMI;
12170       CC = ISD::SETLE;
12171       break;
12172     case Intrinsic::x86_sse_comigt_ss:
12173     case Intrinsic::x86_sse2_comigt_sd:
12174       Opc = X86ISD::COMI;
12175       CC = ISD::SETGT;
12176       break;
12177     case Intrinsic::x86_sse_comige_ss:
12178     case Intrinsic::x86_sse2_comige_sd:
12179       Opc = X86ISD::COMI;
12180       CC = ISD::SETGE;
12181       break;
12182     case Intrinsic::x86_sse_comineq_ss:
12183     case Intrinsic::x86_sse2_comineq_sd:
12184       Opc = X86ISD::COMI;
12185       CC = ISD::SETNE;
12186       break;
12187     case Intrinsic::x86_sse_ucomieq_ss:
12188     case Intrinsic::x86_sse2_ucomieq_sd:
12189       Opc = X86ISD::UCOMI;
12190       CC = ISD::SETEQ;
12191       break;
12192     case Intrinsic::x86_sse_ucomilt_ss:
12193     case Intrinsic::x86_sse2_ucomilt_sd:
12194       Opc = X86ISD::UCOMI;
12195       CC = ISD::SETLT;
12196       break;
12197     case Intrinsic::x86_sse_ucomile_ss:
12198     case Intrinsic::x86_sse2_ucomile_sd:
12199       Opc = X86ISD::UCOMI;
12200       CC = ISD::SETLE;
12201       break;
12202     case Intrinsic::x86_sse_ucomigt_ss:
12203     case Intrinsic::x86_sse2_ucomigt_sd:
12204       Opc = X86ISD::UCOMI;
12205       CC = ISD::SETGT;
12206       break;
12207     case Intrinsic::x86_sse_ucomige_ss:
12208     case Intrinsic::x86_sse2_ucomige_sd:
12209       Opc = X86ISD::UCOMI;
12210       CC = ISD::SETGE;
12211       break;
12212     case Intrinsic::x86_sse_ucomineq_ss:
12213     case Intrinsic::x86_sse2_ucomineq_sd:
12214       Opc = X86ISD::UCOMI;
12215       CC = ISD::SETNE;
12216       break;
12217     }
12218
12219     SDValue LHS = Op.getOperand(1);
12220     SDValue RHS = Op.getOperand(2);
12221     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12222     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12223     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12224     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12225                                 DAG.getConstant(X86CC, MVT::i8), Cond);
12226     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12227   }
12228
12229   // Arithmetic intrinsics.
12230   case Intrinsic::x86_sse2_pmulu_dq:
12231   case Intrinsic::x86_avx2_pmulu_dq:
12232     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12233                        Op.getOperand(1), Op.getOperand(2));
12234
12235   case Intrinsic::x86_sse41_pmuldq:
12236   case Intrinsic::x86_avx2_pmul_dq:
12237     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12238                        Op.getOperand(1), Op.getOperand(2));
12239
12240   case Intrinsic::x86_sse2_pmulhu_w:
12241   case Intrinsic::x86_avx2_pmulhu_w:
12242     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12243                        Op.getOperand(1), Op.getOperand(2));
12244
12245   case Intrinsic::x86_sse2_pmulh_w:
12246   case Intrinsic::x86_avx2_pmulh_w:
12247     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12248                        Op.getOperand(1), Op.getOperand(2));
12249
12250   // SSE2/AVX2 sub with unsigned saturation intrinsics
12251   case Intrinsic::x86_sse2_psubus_b:
12252   case Intrinsic::x86_sse2_psubus_w:
12253   case Intrinsic::x86_avx2_psubus_b:
12254   case Intrinsic::x86_avx2_psubus_w:
12255     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12256                        Op.getOperand(1), Op.getOperand(2));
12257
12258   // SSE3/AVX horizontal add/sub intrinsics
12259   case Intrinsic::x86_sse3_hadd_ps:
12260   case Intrinsic::x86_sse3_hadd_pd:
12261   case Intrinsic::x86_avx_hadd_ps_256:
12262   case Intrinsic::x86_avx_hadd_pd_256:
12263   case Intrinsic::x86_sse3_hsub_ps:
12264   case Intrinsic::x86_sse3_hsub_pd:
12265   case Intrinsic::x86_avx_hsub_ps_256:
12266   case Intrinsic::x86_avx_hsub_pd_256:
12267   case Intrinsic::x86_ssse3_phadd_w_128:
12268   case Intrinsic::x86_ssse3_phadd_d_128:
12269   case Intrinsic::x86_avx2_phadd_w:
12270   case Intrinsic::x86_avx2_phadd_d:
12271   case Intrinsic::x86_ssse3_phsub_w_128:
12272   case Intrinsic::x86_ssse3_phsub_d_128:
12273   case Intrinsic::x86_avx2_phsub_w:
12274   case Intrinsic::x86_avx2_phsub_d: {
12275     unsigned Opcode;
12276     switch (IntNo) {
12277     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12278     case Intrinsic::x86_sse3_hadd_ps:
12279     case Intrinsic::x86_sse3_hadd_pd:
12280     case Intrinsic::x86_avx_hadd_ps_256:
12281     case Intrinsic::x86_avx_hadd_pd_256:
12282       Opcode = X86ISD::FHADD;
12283       break;
12284     case Intrinsic::x86_sse3_hsub_ps:
12285     case Intrinsic::x86_sse3_hsub_pd:
12286     case Intrinsic::x86_avx_hsub_ps_256:
12287     case Intrinsic::x86_avx_hsub_pd_256:
12288       Opcode = X86ISD::FHSUB;
12289       break;
12290     case Intrinsic::x86_ssse3_phadd_w_128:
12291     case Intrinsic::x86_ssse3_phadd_d_128:
12292     case Intrinsic::x86_avx2_phadd_w:
12293     case Intrinsic::x86_avx2_phadd_d:
12294       Opcode = X86ISD::HADD;
12295       break;
12296     case Intrinsic::x86_ssse3_phsub_w_128:
12297     case Intrinsic::x86_ssse3_phsub_d_128:
12298     case Intrinsic::x86_avx2_phsub_w:
12299     case Intrinsic::x86_avx2_phsub_d:
12300       Opcode = X86ISD::HSUB;
12301       break;
12302     }
12303     return DAG.getNode(Opcode, dl, Op.getValueType(),
12304                        Op.getOperand(1), Op.getOperand(2));
12305   }
12306
12307   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12308   case Intrinsic::x86_sse2_pmaxu_b:
12309   case Intrinsic::x86_sse41_pmaxuw:
12310   case Intrinsic::x86_sse41_pmaxud:
12311   case Intrinsic::x86_avx2_pmaxu_b:
12312   case Intrinsic::x86_avx2_pmaxu_w:
12313   case Intrinsic::x86_avx2_pmaxu_d:
12314   case Intrinsic::x86_sse2_pminu_b:
12315   case Intrinsic::x86_sse41_pminuw:
12316   case Intrinsic::x86_sse41_pminud:
12317   case Intrinsic::x86_avx2_pminu_b:
12318   case Intrinsic::x86_avx2_pminu_w:
12319   case Intrinsic::x86_avx2_pminu_d:
12320   case Intrinsic::x86_sse41_pmaxsb:
12321   case Intrinsic::x86_sse2_pmaxs_w:
12322   case Intrinsic::x86_sse41_pmaxsd:
12323   case Intrinsic::x86_avx2_pmaxs_b:
12324   case Intrinsic::x86_avx2_pmaxs_w:
12325   case Intrinsic::x86_avx2_pmaxs_d:
12326   case Intrinsic::x86_sse41_pminsb:
12327   case Intrinsic::x86_sse2_pmins_w:
12328   case Intrinsic::x86_sse41_pminsd:
12329   case Intrinsic::x86_avx2_pmins_b:
12330   case Intrinsic::x86_avx2_pmins_w:
12331   case Intrinsic::x86_avx2_pmins_d: {
12332     unsigned Opcode;
12333     switch (IntNo) {
12334     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12335     case Intrinsic::x86_sse2_pmaxu_b:
12336     case Intrinsic::x86_sse41_pmaxuw:
12337     case Intrinsic::x86_sse41_pmaxud:
12338     case Intrinsic::x86_avx2_pmaxu_b:
12339     case Intrinsic::x86_avx2_pmaxu_w:
12340     case Intrinsic::x86_avx2_pmaxu_d:
12341       Opcode = X86ISD::UMAX;
12342       break;
12343     case Intrinsic::x86_sse2_pminu_b:
12344     case Intrinsic::x86_sse41_pminuw:
12345     case Intrinsic::x86_sse41_pminud:
12346     case Intrinsic::x86_avx2_pminu_b:
12347     case Intrinsic::x86_avx2_pminu_w:
12348     case Intrinsic::x86_avx2_pminu_d:
12349       Opcode = X86ISD::UMIN;
12350       break;
12351     case Intrinsic::x86_sse41_pmaxsb:
12352     case Intrinsic::x86_sse2_pmaxs_w:
12353     case Intrinsic::x86_sse41_pmaxsd:
12354     case Intrinsic::x86_avx2_pmaxs_b:
12355     case Intrinsic::x86_avx2_pmaxs_w:
12356     case Intrinsic::x86_avx2_pmaxs_d:
12357       Opcode = X86ISD::SMAX;
12358       break;
12359     case Intrinsic::x86_sse41_pminsb:
12360     case Intrinsic::x86_sse2_pmins_w:
12361     case Intrinsic::x86_sse41_pminsd:
12362     case Intrinsic::x86_avx2_pmins_b:
12363     case Intrinsic::x86_avx2_pmins_w:
12364     case Intrinsic::x86_avx2_pmins_d:
12365       Opcode = X86ISD::SMIN;
12366       break;
12367     }
12368     return DAG.getNode(Opcode, dl, Op.getValueType(),
12369                        Op.getOperand(1), Op.getOperand(2));
12370   }
12371
12372   // SSE/SSE2/AVX floating point max/min intrinsics.
12373   case Intrinsic::x86_sse_max_ps:
12374   case Intrinsic::x86_sse2_max_pd:
12375   case Intrinsic::x86_avx_max_ps_256:
12376   case Intrinsic::x86_avx_max_pd_256:
12377   case Intrinsic::x86_sse_min_ps:
12378   case Intrinsic::x86_sse2_min_pd:
12379   case Intrinsic::x86_avx_min_ps_256:
12380   case Intrinsic::x86_avx_min_pd_256: {
12381     unsigned Opcode;
12382     switch (IntNo) {
12383     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12384     case Intrinsic::x86_sse_max_ps:
12385     case Intrinsic::x86_sse2_max_pd:
12386     case Intrinsic::x86_avx_max_ps_256:
12387     case Intrinsic::x86_avx_max_pd_256:
12388       Opcode = X86ISD::FMAX;
12389       break;
12390     case Intrinsic::x86_sse_min_ps:
12391     case Intrinsic::x86_sse2_min_pd:
12392     case Intrinsic::x86_avx_min_ps_256:
12393     case Intrinsic::x86_avx_min_pd_256:
12394       Opcode = X86ISD::FMIN;
12395       break;
12396     }
12397     return DAG.getNode(Opcode, dl, Op.getValueType(),
12398                        Op.getOperand(1), Op.getOperand(2));
12399   }
12400
12401   // AVX2 variable shift intrinsics
12402   case Intrinsic::x86_avx2_psllv_d:
12403   case Intrinsic::x86_avx2_psllv_q:
12404   case Intrinsic::x86_avx2_psllv_d_256:
12405   case Intrinsic::x86_avx2_psllv_q_256:
12406   case Intrinsic::x86_avx2_psrlv_d:
12407   case Intrinsic::x86_avx2_psrlv_q:
12408   case Intrinsic::x86_avx2_psrlv_d_256:
12409   case Intrinsic::x86_avx2_psrlv_q_256:
12410   case Intrinsic::x86_avx2_psrav_d:
12411   case Intrinsic::x86_avx2_psrav_d_256: {
12412     unsigned Opcode;
12413     switch (IntNo) {
12414     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12415     case Intrinsic::x86_avx2_psllv_d:
12416     case Intrinsic::x86_avx2_psllv_q:
12417     case Intrinsic::x86_avx2_psllv_d_256:
12418     case Intrinsic::x86_avx2_psllv_q_256:
12419       Opcode = ISD::SHL;
12420       break;
12421     case Intrinsic::x86_avx2_psrlv_d:
12422     case Intrinsic::x86_avx2_psrlv_q:
12423     case Intrinsic::x86_avx2_psrlv_d_256:
12424     case Intrinsic::x86_avx2_psrlv_q_256:
12425       Opcode = ISD::SRL;
12426       break;
12427     case Intrinsic::x86_avx2_psrav_d:
12428     case Intrinsic::x86_avx2_psrav_d_256:
12429       Opcode = ISD::SRA;
12430       break;
12431     }
12432     return DAG.getNode(Opcode, dl, Op.getValueType(),
12433                        Op.getOperand(1), Op.getOperand(2));
12434   }
12435
12436   case Intrinsic::x86_ssse3_pshuf_b_128:
12437   case Intrinsic::x86_avx2_pshuf_b:
12438     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12439                        Op.getOperand(1), Op.getOperand(2));
12440
12441   case Intrinsic::x86_ssse3_psign_b_128:
12442   case Intrinsic::x86_ssse3_psign_w_128:
12443   case Intrinsic::x86_ssse3_psign_d_128:
12444   case Intrinsic::x86_avx2_psign_b:
12445   case Intrinsic::x86_avx2_psign_w:
12446   case Intrinsic::x86_avx2_psign_d:
12447     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12448                        Op.getOperand(1), Op.getOperand(2));
12449
12450   case Intrinsic::x86_sse41_insertps:
12451     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12452                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12453
12454   case Intrinsic::x86_avx_vperm2f128_ps_256:
12455   case Intrinsic::x86_avx_vperm2f128_pd_256:
12456   case Intrinsic::x86_avx_vperm2f128_si_256:
12457   case Intrinsic::x86_avx2_vperm2i128:
12458     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12459                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12460
12461   case Intrinsic::x86_avx2_permd:
12462   case Intrinsic::x86_avx2_permps:
12463     // Operands intentionally swapped. Mask is last operand to intrinsic,
12464     // but second operand for node/instruction.
12465     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12466                        Op.getOperand(2), Op.getOperand(1));
12467
12468   case Intrinsic::x86_sse_sqrt_ps:
12469   case Intrinsic::x86_sse2_sqrt_pd:
12470   case Intrinsic::x86_avx_sqrt_ps_256:
12471   case Intrinsic::x86_avx_sqrt_pd_256:
12472     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12473
12474   // ptest and testp intrinsics. The intrinsic these come from are designed to
12475   // return an integer value, not just an instruction so lower it to the ptest
12476   // or testp pattern and a setcc for the result.
12477   case Intrinsic::x86_sse41_ptestz:
12478   case Intrinsic::x86_sse41_ptestc:
12479   case Intrinsic::x86_sse41_ptestnzc:
12480   case Intrinsic::x86_avx_ptestz_256:
12481   case Intrinsic::x86_avx_ptestc_256:
12482   case Intrinsic::x86_avx_ptestnzc_256:
12483   case Intrinsic::x86_avx_vtestz_ps:
12484   case Intrinsic::x86_avx_vtestc_ps:
12485   case Intrinsic::x86_avx_vtestnzc_ps:
12486   case Intrinsic::x86_avx_vtestz_pd:
12487   case Intrinsic::x86_avx_vtestc_pd:
12488   case Intrinsic::x86_avx_vtestnzc_pd:
12489   case Intrinsic::x86_avx_vtestz_ps_256:
12490   case Intrinsic::x86_avx_vtestc_ps_256:
12491   case Intrinsic::x86_avx_vtestnzc_ps_256:
12492   case Intrinsic::x86_avx_vtestz_pd_256:
12493   case Intrinsic::x86_avx_vtestc_pd_256:
12494   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12495     bool IsTestPacked = false;
12496     unsigned X86CC;
12497     switch (IntNo) {
12498     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12499     case Intrinsic::x86_avx_vtestz_ps:
12500     case Intrinsic::x86_avx_vtestz_pd:
12501     case Intrinsic::x86_avx_vtestz_ps_256:
12502     case Intrinsic::x86_avx_vtestz_pd_256:
12503       IsTestPacked = true; // Fallthrough
12504     case Intrinsic::x86_sse41_ptestz:
12505     case Intrinsic::x86_avx_ptestz_256:
12506       // ZF = 1
12507       X86CC = X86::COND_E;
12508       break;
12509     case Intrinsic::x86_avx_vtestc_ps:
12510     case Intrinsic::x86_avx_vtestc_pd:
12511     case Intrinsic::x86_avx_vtestc_ps_256:
12512     case Intrinsic::x86_avx_vtestc_pd_256:
12513       IsTestPacked = true; // Fallthrough
12514     case Intrinsic::x86_sse41_ptestc:
12515     case Intrinsic::x86_avx_ptestc_256:
12516       // CF = 1
12517       X86CC = X86::COND_B;
12518       break;
12519     case Intrinsic::x86_avx_vtestnzc_ps:
12520     case Intrinsic::x86_avx_vtestnzc_pd:
12521     case Intrinsic::x86_avx_vtestnzc_ps_256:
12522     case Intrinsic::x86_avx_vtestnzc_pd_256:
12523       IsTestPacked = true; // Fallthrough
12524     case Intrinsic::x86_sse41_ptestnzc:
12525     case Intrinsic::x86_avx_ptestnzc_256:
12526       // ZF and CF = 0
12527       X86CC = X86::COND_A;
12528       break;
12529     }
12530
12531     SDValue LHS = Op.getOperand(1);
12532     SDValue RHS = Op.getOperand(2);
12533     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12534     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12535     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12536     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12537     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12538   }
12539   case Intrinsic::x86_avx512_kortestz_w:
12540   case Intrinsic::x86_avx512_kortestc_w: {
12541     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12542     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12543     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12544     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12545     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12546     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12547     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12548   }
12549
12550   // SSE/AVX shift intrinsics
12551   case Intrinsic::x86_sse2_psll_w:
12552   case Intrinsic::x86_sse2_psll_d:
12553   case Intrinsic::x86_sse2_psll_q:
12554   case Intrinsic::x86_avx2_psll_w:
12555   case Intrinsic::x86_avx2_psll_d:
12556   case Intrinsic::x86_avx2_psll_q:
12557   case Intrinsic::x86_sse2_psrl_w:
12558   case Intrinsic::x86_sse2_psrl_d:
12559   case Intrinsic::x86_sse2_psrl_q:
12560   case Intrinsic::x86_avx2_psrl_w:
12561   case Intrinsic::x86_avx2_psrl_d:
12562   case Intrinsic::x86_avx2_psrl_q:
12563   case Intrinsic::x86_sse2_psra_w:
12564   case Intrinsic::x86_sse2_psra_d:
12565   case Intrinsic::x86_avx2_psra_w:
12566   case Intrinsic::x86_avx2_psra_d: {
12567     unsigned Opcode;
12568     switch (IntNo) {
12569     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12570     case Intrinsic::x86_sse2_psll_w:
12571     case Intrinsic::x86_sse2_psll_d:
12572     case Intrinsic::x86_sse2_psll_q:
12573     case Intrinsic::x86_avx2_psll_w:
12574     case Intrinsic::x86_avx2_psll_d:
12575     case Intrinsic::x86_avx2_psll_q:
12576       Opcode = X86ISD::VSHL;
12577       break;
12578     case Intrinsic::x86_sse2_psrl_w:
12579     case Intrinsic::x86_sse2_psrl_d:
12580     case Intrinsic::x86_sse2_psrl_q:
12581     case Intrinsic::x86_avx2_psrl_w:
12582     case Intrinsic::x86_avx2_psrl_d:
12583     case Intrinsic::x86_avx2_psrl_q:
12584       Opcode = X86ISD::VSRL;
12585       break;
12586     case Intrinsic::x86_sse2_psra_w:
12587     case Intrinsic::x86_sse2_psra_d:
12588     case Intrinsic::x86_avx2_psra_w:
12589     case Intrinsic::x86_avx2_psra_d:
12590       Opcode = X86ISD::VSRA;
12591       break;
12592     }
12593     return DAG.getNode(Opcode, dl, Op.getValueType(),
12594                        Op.getOperand(1), Op.getOperand(2));
12595   }
12596
12597   // SSE/AVX immediate shift intrinsics
12598   case Intrinsic::x86_sse2_pslli_w:
12599   case Intrinsic::x86_sse2_pslli_d:
12600   case Intrinsic::x86_sse2_pslli_q:
12601   case Intrinsic::x86_avx2_pslli_w:
12602   case Intrinsic::x86_avx2_pslli_d:
12603   case Intrinsic::x86_avx2_pslli_q:
12604   case Intrinsic::x86_sse2_psrli_w:
12605   case Intrinsic::x86_sse2_psrli_d:
12606   case Intrinsic::x86_sse2_psrli_q:
12607   case Intrinsic::x86_avx2_psrli_w:
12608   case Intrinsic::x86_avx2_psrli_d:
12609   case Intrinsic::x86_avx2_psrli_q:
12610   case Intrinsic::x86_sse2_psrai_w:
12611   case Intrinsic::x86_sse2_psrai_d:
12612   case Intrinsic::x86_avx2_psrai_w:
12613   case Intrinsic::x86_avx2_psrai_d: {
12614     unsigned Opcode;
12615     switch (IntNo) {
12616     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12617     case Intrinsic::x86_sse2_pslli_w:
12618     case Intrinsic::x86_sse2_pslli_d:
12619     case Intrinsic::x86_sse2_pslli_q:
12620     case Intrinsic::x86_avx2_pslli_w:
12621     case Intrinsic::x86_avx2_pslli_d:
12622     case Intrinsic::x86_avx2_pslli_q:
12623       Opcode = X86ISD::VSHLI;
12624       break;
12625     case Intrinsic::x86_sse2_psrli_w:
12626     case Intrinsic::x86_sse2_psrli_d:
12627     case Intrinsic::x86_sse2_psrli_q:
12628     case Intrinsic::x86_avx2_psrli_w:
12629     case Intrinsic::x86_avx2_psrli_d:
12630     case Intrinsic::x86_avx2_psrli_q:
12631       Opcode = X86ISD::VSRLI;
12632       break;
12633     case Intrinsic::x86_sse2_psrai_w:
12634     case Intrinsic::x86_sse2_psrai_d:
12635     case Intrinsic::x86_avx2_psrai_w:
12636     case Intrinsic::x86_avx2_psrai_d:
12637       Opcode = X86ISD::VSRAI;
12638       break;
12639     }
12640     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12641                                Op.getOperand(1), Op.getOperand(2), DAG);
12642   }
12643
12644   case Intrinsic::x86_sse42_pcmpistria128:
12645   case Intrinsic::x86_sse42_pcmpestria128:
12646   case Intrinsic::x86_sse42_pcmpistric128:
12647   case Intrinsic::x86_sse42_pcmpestric128:
12648   case Intrinsic::x86_sse42_pcmpistrio128:
12649   case Intrinsic::x86_sse42_pcmpestrio128:
12650   case Intrinsic::x86_sse42_pcmpistris128:
12651   case Intrinsic::x86_sse42_pcmpestris128:
12652   case Intrinsic::x86_sse42_pcmpistriz128:
12653   case Intrinsic::x86_sse42_pcmpestriz128: {
12654     unsigned Opcode;
12655     unsigned X86CC;
12656     switch (IntNo) {
12657     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12658     case Intrinsic::x86_sse42_pcmpistria128:
12659       Opcode = X86ISD::PCMPISTRI;
12660       X86CC = X86::COND_A;
12661       break;
12662     case Intrinsic::x86_sse42_pcmpestria128:
12663       Opcode = X86ISD::PCMPESTRI;
12664       X86CC = X86::COND_A;
12665       break;
12666     case Intrinsic::x86_sse42_pcmpistric128:
12667       Opcode = X86ISD::PCMPISTRI;
12668       X86CC = X86::COND_B;
12669       break;
12670     case Intrinsic::x86_sse42_pcmpestric128:
12671       Opcode = X86ISD::PCMPESTRI;
12672       X86CC = X86::COND_B;
12673       break;
12674     case Intrinsic::x86_sse42_pcmpistrio128:
12675       Opcode = X86ISD::PCMPISTRI;
12676       X86CC = X86::COND_O;
12677       break;
12678     case Intrinsic::x86_sse42_pcmpestrio128:
12679       Opcode = X86ISD::PCMPESTRI;
12680       X86CC = X86::COND_O;
12681       break;
12682     case Intrinsic::x86_sse42_pcmpistris128:
12683       Opcode = X86ISD::PCMPISTRI;
12684       X86CC = X86::COND_S;
12685       break;
12686     case Intrinsic::x86_sse42_pcmpestris128:
12687       Opcode = X86ISD::PCMPESTRI;
12688       X86CC = X86::COND_S;
12689       break;
12690     case Intrinsic::x86_sse42_pcmpistriz128:
12691       Opcode = X86ISD::PCMPISTRI;
12692       X86CC = X86::COND_E;
12693       break;
12694     case Intrinsic::x86_sse42_pcmpestriz128:
12695       Opcode = X86ISD::PCMPESTRI;
12696       X86CC = X86::COND_E;
12697       break;
12698     }
12699     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12700     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12701     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12702     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12703                                 DAG.getConstant(X86CC, MVT::i8),
12704                                 SDValue(PCMP.getNode(), 1));
12705     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12706   }
12707
12708   case Intrinsic::x86_sse42_pcmpistri128:
12709   case Intrinsic::x86_sse42_pcmpestri128: {
12710     unsigned Opcode;
12711     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12712       Opcode = X86ISD::PCMPISTRI;
12713     else
12714       Opcode = X86ISD::PCMPESTRI;
12715
12716     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12717     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12718     return DAG.getNode(Opcode, dl, VTs, NewOps);
12719   }
12720   case Intrinsic::x86_fma_vfmadd_ps:
12721   case Intrinsic::x86_fma_vfmadd_pd:
12722   case Intrinsic::x86_fma_vfmsub_ps:
12723   case Intrinsic::x86_fma_vfmsub_pd:
12724   case Intrinsic::x86_fma_vfnmadd_ps:
12725   case Intrinsic::x86_fma_vfnmadd_pd:
12726   case Intrinsic::x86_fma_vfnmsub_ps:
12727   case Intrinsic::x86_fma_vfnmsub_pd:
12728   case Intrinsic::x86_fma_vfmaddsub_ps:
12729   case Intrinsic::x86_fma_vfmaddsub_pd:
12730   case Intrinsic::x86_fma_vfmsubadd_ps:
12731   case Intrinsic::x86_fma_vfmsubadd_pd:
12732   case Intrinsic::x86_fma_vfmadd_ps_256:
12733   case Intrinsic::x86_fma_vfmadd_pd_256:
12734   case Intrinsic::x86_fma_vfmsub_ps_256:
12735   case Intrinsic::x86_fma_vfmsub_pd_256:
12736   case Intrinsic::x86_fma_vfnmadd_ps_256:
12737   case Intrinsic::x86_fma_vfnmadd_pd_256:
12738   case Intrinsic::x86_fma_vfnmsub_ps_256:
12739   case Intrinsic::x86_fma_vfnmsub_pd_256:
12740   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12741   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12742   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12743   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12744   case Intrinsic::x86_fma_vfmadd_ps_512:
12745   case Intrinsic::x86_fma_vfmadd_pd_512:
12746   case Intrinsic::x86_fma_vfmsub_ps_512:
12747   case Intrinsic::x86_fma_vfmsub_pd_512:
12748   case Intrinsic::x86_fma_vfnmadd_ps_512:
12749   case Intrinsic::x86_fma_vfnmadd_pd_512:
12750   case Intrinsic::x86_fma_vfnmsub_ps_512:
12751   case Intrinsic::x86_fma_vfnmsub_pd_512:
12752   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12753   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12754   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12755   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12756     unsigned Opc;
12757     switch (IntNo) {
12758     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12759     case Intrinsic::x86_fma_vfmadd_ps:
12760     case Intrinsic::x86_fma_vfmadd_pd:
12761     case Intrinsic::x86_fma_vfmadd_ps_256:
12762     case Intrinsic::x86_fma_vfmadd_pd_256:
12763     case Intrinsic::x86_fma_vfmadd_ps_512:
12764     case Intrinsic::x86_fma_vfmadd_pd_512:
12765       Opc = X86ISD::FMADD;
12766       break;
12767     case Intrinsic::x86_fma_vfmsub_ps:
12768     case Intrinsic::x86_fma_vfmsub_pd:
12769     case Intrinsic::x86_fma_vfmsub_ps_256:
12770     case Intrinsic::x86_fma_vfmsub_pd_256:
12771     case Intrinsic::x86_fma_vfmsub_ps_512:
12772     case Intrinsic::x86_fma_vfmsub_pd_512:
12773       Opc = X86ISD::FMSUB;
12774       break;
12775     case Intrinsic::x86_fma_vfnmadd_ps:
12776     case Intrinsic::x86_fma_vfnmadd_pd:
12777     case Intrinsic::x86_fma_vfnmadd_ps_256:
12778     case Intrinsic::x86_fma_vfnmadd_pd_256:
12779     case Intrinsic::x86_fma_vfnmadd_ps_512:
12780     case Intrinsic::x86_fma_vfnmadd_pd_512:
12781       Opc = X86ISD::FNMADD;
12782       break;
12783     case Intrinsic::x86_fma_vfnmsub_ps:
12784     case Intrinsic::x86_fma_vfnmsub_pd:
12785     case Intrinsic::x86_fma_vfnmsub_ps_256:
12786     case Intrinsic::x86_fma_vfnmsub_pd_256:
12787     case Intrinsic::x86_fma_vfnmsub_ps_512:
12788     case Intrinsic::x86_fma_vfnmsub_pd_512:
12789       Opc = X86ISD::FNMSUB;
12790       break;
12791     case Intrinsic::x86_fma_vfmaddsub_ps:
12792     case Intrinsic::x86_fma_vfmaddsub_pd:
12793     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12794     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12795     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12796     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12797       Opc = X86ISD::FMADDSUB;
12798       break;
12799     case Intrinsic::x86_fma_vfmsubadd_ps:
12800     case Intrinsic::x86_fma_vfmsubadd_pd:
12801     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12802     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12803     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12804     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12805       Opc = X86ISD::FMSUBADD;
12806       break;
12807     }
12808
12809     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12810                        Op.getOperand(2), Op.getOperand(3));
12811   }
12812   }
12813 }
12814
12815 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12816                               SDValue Src, SDValue Mask, SDValue Base,
12817                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12818                               const X86Subtarget * Subtarget) {
12819   SDLoc dl(Op);
12820   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12821   assert(C && "Invalid scale type");
12822   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12823   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12824                              Index.getSimpleValueType().getVectorNumElements());
12825   SDValue MaskInReg;
12826   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12827   if (MaskC)
12828     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12829   else
12830     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12831   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12832   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12833   SDValue Segment = DAG.getRegister(0, MVT::i32);
12834   if (Src.getOpcode() == ISD::UNDEF)
12835     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12836   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12837   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12838   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12839   return DAG.getMergeValues(RetOps, dl);
12840 }
12841
12842 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12843                                SDValue Src, SDValue Mask, SDValue Base,
12844                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12845   SDLoc dl(Op);
12846   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12847   assert(C && "Invalid scale type");
12848   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12849   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12850   SDValue Segment = DAG.getRegister(0, MVT::i32);
12851   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12852                              Index.getSimpleValueType().getVectorNumElements());
12853   SDValue MaskInReg;
12854   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12855   if (MaskC)
12856     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12857   else
12858     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12859   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12860   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12861   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12862   return SDValue(Res, 1);
12863 }
12864
12865 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12866                                SDValue Mask, SDValue Base, SDValue Index,
12867                                SDValue ScaleOp, SDValue Chain) {
12868   SDLoc dl(Op);
12869   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12870   assert(C && "Invalid scale type");
12871   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12872   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12873   SDValue Segment = DAG.getRegister(0, MVT::i32);
12874   EVT MaskVT =
12875     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12876   SDValue MaskInReg;
12877   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12878   if (MaskC)
12879     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12880   else
12881     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12882   //SDVTList VTs = DAG.getVTList(MVT::Other);
12883   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12884   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12885   return SDValue(Res, 0);
12886 }
12887
12888 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12889 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12890 // also used to custom lower READCYCLECOUNTER nodes.
12891 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12892                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12893                               SmallVectorImpl<SDValue> &Results) {
12894   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12895   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12896   SDValue LO, HI;
12897
12898   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12899   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12900   // and the EAX register is loaded with the low-order 32 bits.
12901   if (Subtarget->is64Bit()) {
12902     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12903     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12904                             LO.getValue(2));
12905   } else {
12906     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12907     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12908                             LO.getValue(2));
12909   }
12910   SDValue Chain = HI.getValue(1);
12911
12912   if (Opcode == X86ISD::RDTSCP_DAG) {
12913     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12914
12915     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12916     // the ECX register. Add 'ecx' explicitly to the chain.
12917     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12918                                      HI.getValue(2));
12919     // Explicitly store the content of ECX at the location passed in input
12920     // to the 'rdtscp' intrinsic.
12921     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12922                          MachinePointerInfo(), false, false, 0);
12923   }
12924
12925   if (Subtarget->is64Bit()) {
12926     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12927     // the EAX register is loaded with the low-order 32 bits.
12928     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12929                               DAG.getConstant(32, MVT::i8));
12930     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12931     Results.push_back(Chain);
12932     return;
12933   }
12934
12935   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12936   SDValue Ops[] = { LO, HI };
12937   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12938   Results.push_back(Pair);
12939   Results.push_back(Chain);
12940 }
12941
12942 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12943                                      SelectionDAG &DAG) {
12944   SmallVector<SDValue, 2> Results;
12945   SDLoc DL(Op);
12946   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12947                           Results);
12948   return DAG.getMergeValues(Results, DL);
12949 }
12950
12951 enum IntrinsicType {
12952   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12953 };
12954
12955 struct IntrinsicData {
12956   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12957     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12958   IntrinsicType Type;
12959   unsigned      Opc0;
12960   unsigned      Opc1;
12961 };
12962
12963 std::map < unsigned, IntrinsicData> IntrMap;
12964 static void InitIntinsicsMap() {
12965   static bool Initialized = false;
12966   if (Initialized) 
12967     return;
12968   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12969                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12970   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12971                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12972   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12973                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12974   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12975                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12976   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12977                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12978   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12979                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12980   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12981                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12982   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12983                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12984   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12985                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12986
12987   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12988                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12989   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12990                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12991   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12992                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12993   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12994                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12995   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12996                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12997   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12998                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12999   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
13000                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
13001   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
13002                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
13003    
13004   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
13005                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
13006                                                         X86::VGATHERPF1QPSm)));
13007   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
13008                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
13009                                                         X86::VGATHERPF1QPDm)));
13010   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
13011                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
13012                                                         X86::VGATHERPF1DPDm)));
13013   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
13014                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
13015                                                         X86::VGATHERPF1DPSm)));
13016   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
13017                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
13018                                                         X86::VSCATTERPF1QPSm)));
13019   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
13020                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
13021                                                         X86::VSCATTERPF1QPDm)));
13022   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
13023                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
13024                                                         X86::VSCATTERPF1DPDm)));
13025   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
13026                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
13027                                                         X86::VSCATTERPF1DPSm)));
13028   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
13029                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13030   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
13031                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13032   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
13033                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13034   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
13035                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13036   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
13037                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13038   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
13039                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13040   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
13041                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
13042   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
13043                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
13044   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
13045                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
13046   Initialized = true;
13047 }
13048
13049 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
13050                                       SelectionDAG &DAG) {
13051   InitIntinsicsMap();
13052   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13053   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
13054   if (itr == IntrMap.end())
13055     return SDValue();
13056
13057   SDLoc dl(Op);
13058   IntrinsicData Intr = itr->second;
13059   switch(Intr.Type) {
13060   case RDSEED:
13061   case RDRAND: {
13062     // Emit the node with the right value type.
13063     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
13064     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
13065
13066     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
13067     // Otherwise return the value from Rand, which is always 0, casted to i32.
13068     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
13069                       DAG.getConstant(1, Op->getValueType(1)),
13070                       DAG.getConstant(X86::COND_B, MVT::i32),
13071                       SDValue(Result.getNode(), 1) };
13072     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
13073                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
13074                                   Ops);
13075
13076     // Return { result, isValid, chain }.
13077     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
13078                        SDValue(Result.getNode(), 2));
13079   }
13080   case GATHER: {
13081   //gather(v1, mask, index, base, scale);
13082     SDValue Chain = Op.getOperand(0);
13083     SDValue Src   = Op.getOperand(2);
13084     SDValue Base  = Op.getOperand(3);
13085     SDValue Index = Op.getOperand(4);
13086     SDValue Mask  = Op.getOperand(5);
13087     SDValue Scale = Op.getOperand(6);
13088     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
13089                           Subtarget);
13090   }
13091   case SCATTER: {
13092   //scatter(base, mask, index, v1, scale);
13093     SDValue Chain = Op.getOperand(0);
13094     SDValue Base  = Op.getOperand(2);
13095     SDValue Mask  = Op.getOperand(3);
13096     SDValue Index = Op.getOperand(4);
13097     SDValue Src   = Op.getOperand(5);
13098     SDValue Scale = Op.getOperand(6);
13099     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13100   }
13101   case PREFETCH: {
13102     SDValue Hint = Op.getOperand(6);
13103     unsigned HintVal;
13104     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13105         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13106       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13107     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13108     SDValue Chain = Op.getOperand(0);
13109     SDValue Mask  = Op.getOperand(2);
13110     SDValue Index = Op.getOperand(3);
13111     SDValue Base  = Op.getOperand(4);
13112     SDValue Scale = Op.getOperand(5);
13113     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13114   }
13115   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13116   case RDTSC: {
13117     SmallVector<SDValue, 2> Results;
13118     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13119     return DAG.getMergeValues(Results, dl);
13120   }
13121   // XTEST intrinsics.
13122   case XTEST: {
13123     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13124     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13125     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13126                                 DAG.getConstant(X86::COND_NE, MVT::i8),
13127                                 InTrans);
13128     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13129     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13130                        Ret, SDValue(InTrans.getNode(), 1));
13131   }
13132   }
13133   llvm_unreachable("Unknown Intrinsic Type");
13134 }
13135
13136 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13137                                            SelectionDAG &DAG) const {
13138   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13139   MFI->setReturnAddressIsTaken(true);
13140
13141   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13142     return SDValue();
13143
13144   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13145   SDLoc dl(Op);
13146   EVT PtrVT = getPointerTy();
13147
13148   if (Depth > 0) {
13149     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13150     const X86RegisterInfo *RegInfo =
13151       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13152     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13153     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13154                        DAG.getNode(ISD::ADD, dl, PtrVT,
13155                                    FrameAddr, Offset),
13156                        MachinePointerInfo(), false, false, false, 0);
13157   }
13158
13159   // Just load the return address.
13160   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13161   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13162                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13163 }
13164
13165 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13166   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13167   MFI->setFrameAddressIsTaken(true);
13168
13169   EVT VT = Op.getValueType();
13170   SDLoc dl(Op);  // FIXME probably not meaningful
13171   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13172   const X86RegisterInfo *RegInfo =
13173     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13174   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13175   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13176           (FrameReg == X86::EBP && VT == MVT::i32)) &&
13177          "Invalid Frame Register!");
13178   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13179   while (Depth--)
13180     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13181                             MachinePointerInfo(),
13182                             false, false, false, 0);
13183   return FrameAddr;
13184 }
13185
13186 // FIXME? Maybe this could be a TableGen attribute on some registers and
13187 // this table could be generated automatically from RegInfo.
13188 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13189                                               EVT VT) const {
13190   unsigned Reg = StringSwitch<unsigned>(RegName)
13191                        .Case("esp", X86::ESP)
13192                        .Case("rsp", X86::RSP)
13193                        .Default(0);
13194   if (Reg)
13195     return Reg;
13196   report_fatal_error("Invalid register name global variable");
13197 }
13198
13199 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13200                                                      SelectionDAG &DAG) const {
13201   const X86RegisterInfo *RegInfo =
13202     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13203   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13204 }
13205
13206 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13207   SDValue Chain     = Op.getOperand(0);
13208   SDValue Offset    = Op.getOperand(1);
13209   SDValue Handler   = Op.getOperand(2);
13210   SDLoc dl      (Op);
13211
13212   EVT PtrVT = getPointerTy();
13213   const X86RegisterInfo *RegInfo =
13214     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13215   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13216   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13217           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13218          "Invalid Frame Register!");
13219   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13220   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13221
13222   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13223                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13224   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13225   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13226                        false, false, 0);
13227   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13228
13229   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13230                      DAG.getRegister(StoreAddrReg, PtrVT));
13231 }
13232
13233 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13234                                                SelectionDAG &DAG) const {
13235   SDLoc DL(Op);
13236   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13237                      DAG.getVTList(MVT::i32, MVT::Other),
13238                      Op.getOperand(0), Op.getOperand(1));
13239 }
13240
13241 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13242                                                 SelectionDAG &DAG) const {
13243   SDLoc DL(Op);
13244   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13245                      Op.getOperand(0), Op.getOperand(1));
13246 }
13247
13248 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13249   return Op.getOperand(0);
13250 }
13251
13252 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13253                                                 SelectionDAG &DAG) const {
13254   SDValue Root = Op.getOperand(0);
13255   SDValue Trmp = Op.getOperand(1); // trampoline
13256   SDValue FPtr = Op.getOperand(2); // nested function
13257   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13258   SDLoc dl (Op);
13259
13260   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13261   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13262
13263   if (Subtarget->is64Bit()) {
13264     SDValue OutChains[6];
13265
13266     // Large code-model.
13267     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
13268     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13269
13270     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13271     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13272
13273     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13274
13275     // Load the pointer to the nested function into R11.
13276     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13277     SDValue Addr = Trmp;
13278     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13279                                 Addr, MachinePointerInfo(TrmpAddr),
13280                                 false, false, 0);
13281
13282     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13283                        DAG.getConstant(2, MVT::i64));
13284     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13285                                 MachinePointerInfo(TrmpAddr, 2),
13286                                 false, false, 2);
13287
13288     // Load the 'nest' parameter value into R10.
13289     // R10 is specified in X86CallingConv.td
13290     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13291     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13292                        DAG.getConstant(10, MVT::i64));
13293     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13294                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13295                                 false, false, 0);
13296
13297     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13298                        DAG.getConstant(12, MVT::i64));
13299     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13300                                 MachinePointerInfo(TrmpAddr, 12),
13301                                 false, false, 2);
13302
13303     // Jump to the nested function.
13304     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13305     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13306                        DAG.getConstant(20, MVT::i64));
13307     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13308                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13309                                 false, false, 0);
13310
13311     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13312     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13313                        DAG.getConstant(22, MVT::i64));
13314     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13315                                 MachinePointerInfo(TrmpAddr, 22),
13316                                 false, false, 0);
13317
13318     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13319   } else {
13320     const Function *Func =
13321       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13322     CallingConv::ID CC = Func->getCallingConv();
13323     unsigned NestReg;
13324
13325     switch (CC) {
13326     default:
13327       llvm_unreachable("Unsupported calling convention");
13328     case CallingConv::C:
13329     case CallingConv::X86_StdCall: {
13330       // Pass 'nest' parameter in ECX.
13331       // Must be kept in sync with X86CallingConv.td
13332       NestReg = X86::ECX;
13333
13334       // Check that ECX wasn't needed by an 'inreg' parameter.
13335       FunctionType *FTy = Func->getFunctionType();
13336       const AttributeSet &Attrs = Func->getAttributes();
13337
13338       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13339         unsigned InRegCount = 0;
13340         unsigned Idx = 1;
13341
13342         for (FunctionType::param_iterator I = FTy->param_begin(),
13343              E = FTy->param_end(); I != E; ++I, ++Idx)
13344           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13345             // FIXME: should only count parameters that are lowered to integers.
13346             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13347
13348         if (InRegCount > 2) {
13349           report_fatal_error("Nest register in use - reduce number of inreg"
13350                              " parameters!");
13351         }
13352       }
13353       break;
13354     }
13355     case CallingConv::X86_FastCall:
13356     case CallingConv::X86_ThisCall:
13357     case CallingConv::Fast:
13358       // Pass 'nest' parameter in EAX.
13359       // Must be kept in sync with X86CallingConv.td
13360       NestReg = X86::EAX;
13361       break;
13362     }
13363
13364     SDValue OutChains[4];
13365     SDValue Addr, Disp;
13366
13367     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13368                        DAG.getConstant(10, MVT::i32));
13369     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13370
13371     // This is storing the opcode for MOV32ri.
13372     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13373     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13374     OutChains[0] = DAG.getStore(Root, dl,
13375                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13376                                 Trmp, MachinePointerInfo(TrmpAddr),
13377                                 false, false, 0);
13378
13379     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13380                        DAG.getConstant(1, MVT::i32));
13381     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13382                                 MachinePointerInfo(TrmpAddr, 1),
13383                                 false, false, 1);
13384
13385     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13386     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13387                        DAG.getConstant(5, MVT::i32));
13388     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13389                                 MachinePointerInfo(TrmpAddr, 5),
13390                                 false, false, 1);
13391
13392     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13393                        DAG.getConstant(6, MVT::i32));
13394     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13395                                 MachinePointerInfo(TrmpAddr, 6),
13396                                 false, false, 1);
13397
13398     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13399   }
13400 }
13401
13402 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13403                                             SelectionDAG &DAG) const {
13404   /*
13405    The rounding mode is in bits 11:10 of FPSR, and has the following
13406    settings:
13407      00 Round to nearest
13408      01 Round to -inf
13409      10 Round to +inf
13410      11 Round to 0
13411
13412   FLT_ROUNDS, on the other hand, expects the following:
13413     -1 Undefined
13414      0 Round to 0
13415      1 Round to nearest
13416      2 Round to +inf
13417      3 Round to -inf
13418
13419   To perform the conversion, we do:
13420     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13421   */
13422
13423   MachineFunction &MF = DAG.getMachineFunction();
13424   const TargetMachine &TM = MF.getTarget();
13425   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13426   unsigned StackAlignment = TFI.getStackAlignment();
13427   MVT VT = Op.getSimpleValueType();
13428   SDLoc DL(Op);
13429
13430   // Save FP Control Word to stack slot
13431   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13432   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13433
13434   MachineMemOperand *MMO =
13435    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13436                            MachineMemOperand::MOStore, 2, 2);
13437
13438   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13439   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13440                                           DAG.getVTList(MVT::Other),
13441                                           Ops, MVT::i16, MMO);
13442
13443   // Load FP Control Word from stack slot
13444   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13445                             MachinePointerInfo(), false, false, false, 0);
13446
13447   // Transform as necessary
13448   SDValue CWD1 =
13449     DAG.getNode(ISD::SRL, DL, MVT::i16,
13450                 DAG.getNode(ISD::AND, DL, MVT::i16,
13451                             CWD, DAG.getConstant(0x800, MVT::i16)),
13452                 DAG.getConstant(11, MVT::i8));
13453   SDValue CWD2 =
13454     DAG.getNode(ISD::SRL, DL, MVT::i16,
13455                 DAG.getNode(ISD::AND, DL, MVT::i16,
13456                             CWD, DAG.getConstant(0x400, MVT::i16)),
13457                 DAG.getConstant(9, MVT::i8));
13458
13459   SDValue RetVal =
13460     DAG.getNode(ISD::AND, DL, MVT::i16,
13461                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13462                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13463                             DAG.getConstant(1, MVT::i16)),
13464                 DAG.getConstant(3, MVT::i16));
13465
13466   return DAG.getNode((VT.getSizeInBits() < 16 ?
13467                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13468 }
13469
13470 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13471   MVT VT = Op.getSimpleValueType();
13472   EVT OpVT = VT;
13473   unsigned NumBits = VT.getSizeInBits();
13474   SDLoc dl(Op);
13475
13476   Op = Op.getOperand(0);
13477   if (VT == MVT::i8) {
13478     // Zero extend to i32 since there is not an i8 bsr.
13479     OpVT = MVT::i32;
13480     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13481   }
13482
13483   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13484   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13485   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13486
13487   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13488   SDValue Ops[] = {
13489     Op,
13490     DAG.getConstant(NumBits+NumBits-1, OpVT),
13491     DAG.getConstant(X86::COND_E, MVT::i8),
13492     Op.getValue(1)
13493   };
13494   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13495
13496   // Finally xor with NumBits-1.
13497   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13498
13499   if (VT == MVT::i8)
13500     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13501   return Op;
13502 }
13503
13504 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13505   MVT VT = Op.getSimpleValueType();
13506   EVT OpVT = VT;
13507   unsigned NumBits = VT.getSizeInBits();
13508   SDLoc dl(Op);
13509
13510   Op = Op.getOperand(0);
13511   if (VT == MVT::i8) {
13512     // Zero extend to i32 since there is not an i8 bsr.
13513     OpVT = MVT::i32;
13514     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13515   }
13516
13517   // Issue a bsr (scan bits in reverse).
13518   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13519   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13520
13521   // And xor with NumBits-1.
13522   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13523
13524   if (VT == MVT::i8)
13525     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13526   return Op;
13527 }
13528
13529 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13530   MVT VT = Op.getSimpleValueType();
13531   unsigned NumBits = VT.getSizeInBits();
13532   SDLoc dl(Op);
13533   Op = Op.getOperand(0);
13534
13535   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13536   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13537   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13538
13539   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13540   SDValue Ops[] = {
13541     Op,
13542     DAG.getConstant(NumBits, VT),
13543     DAG.getConstant(X86::COND_E, MVT::i8),
13544     Op.getValue(1)
13545   };
13546   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13547 }
13548
13549 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13550 // ones, and then concatenate the result back.
13551 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13552   MVT VT = Op.getSimpleValueType();
13553
13554   assert(VT.is256BitVector() && VT.isInteger() &&
13555          "Unsupported value type for operation");
13556
13557   unsigned NumElems = VT.getVectorNumElements();
13558   SDLoc dl(Op);
13559
13560   // Extract the LHS vectors
13561   SDValue LHS = Op.getOperand(0);
13562   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13563   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13564
13565   // Extract the RHS vectors
13566   SDValue RHS = Op.getOperand(1);
13567   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13568   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13569
13570   MVT EltVT = VT.getVectorElementType();
13571   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13572
13573   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13574                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13575                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13576 }
13577
13578 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13579   assert(Op.getSimpleValueType().is256BitVector() &&
13580          Op.getSimpleValueType().isInteger() &&
13581          "Only handle AVX 256-bit vector integer operation");
13582   return Lower256IntArith(Op, DAG);
13583 }
13584
13585 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13586   assert(Op.getSimpleValueType().is256BitVector() &&
13587          Op.getSimpleValueType().isInteger() &&
13588          "Only handle AVX 256-bit vector integer operation");
13589   return Lower256IntArith(Op, DAG);
13590 }
13591
13592 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13593                         SelectionDAG &DAG) {
13594   SDLoc dl(Op);
13595   MVT VT = Op.getSimpleValueType();
13596
13597   // Decompose 256-bit ops into smaller 128-bit ops.
13598   if (VT.is256BitVector() && !Subtarget->hasInt256())
13599     return Lower256IntArith(Op, DAG);
13600
13601   SDValue A = Op.getOperand(0);
13602   SDValue B = Op.getOperand(1);
13603
13604   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13605   if (VT == MVT::v4i32) {
13606     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13607            "Should not custom lower when pmuldq is available!");
13608
13609     // Extract the odd parts.
13610     static const int UnpackMask[] = { 1, -1, 3, -1 };
13611     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13612     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13613
13614     // Multiply the even parts.
13615     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13616     // Now multiply odd parts.
13617     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13618
13619     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13620     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13621
13622     // Merge the two vectors back together with a shuffle. This expands into 2
13623     // shuffles.
13624     static const int ShufMask[] = { 0, 4, 2, 6 };
13625     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13626   }
13627
13628   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13629          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13630
13631   //  Ahi = psrlqi(a, 32);
13632   //  Bhi = psrlqi(b, 32);
13633   //
13634   //  AloBlo = pmuludq(a, b);
13635   //  AloBhi = pmuludq(a, Bhi);
13636   //  AhiBlo = pmuludq(Ahi, b);
13637
13638   //  AloBhi = psllqi(AloBhi, 32);
13639   //  AhiBlo = psllqi(AhiBlo, 32);
13640   //  return AloBlo + AloBhi + AhiBlo;
13641
13642   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13643   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13644
13645   // Bit cast to 32-bit vectors for MULUDQ
13646   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13647                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13648   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13649   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13650   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13651   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13652
13653   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13654   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13655   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13656
13657   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13658   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13659
13660   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13661   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13662 }
13663
13664 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13665   assert(Subtarget->isTargetWin64() && "Unexpected target");
13666   EVT VT = Op.getValueType();
13667   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13668          "Unexpected return type for lowering");
13669
13670   RTLIB::Libcall LC;
13671   bool isSigned;
13672   switch (Op->getOpcode()) {
13673   default: llvm_unreachable("Unexpected request for libcall!");
13674   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13675   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13676   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13677   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13678   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13679   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13680   }
13681
13682   SDLoc dl(Op);
13683   SDValue InChain = DAG.getEntryNode();
13684
13685   TargetLowering::ArgListTy Args;
13686   TargetLowering::ArgListEntry Entry;
13687   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13688     EVT ArgVT = Op->getOperand(i).getValueType();
13689     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13690            "Unexpected argument type for lowering");
13691     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13692     Entry.Node = StackPtr;
13693     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13694                            false, false, 16);
13695     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13696     Entry.Ty = PointerType::get(ArgTy,0);
13697     Entry.isSExt = false;
13698     Entry.isZExt = false;
13699     Args.push_back(Entry);
13700   }
13701
13702   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13703                                          getPointerTy());
13704
13705   TargetLowering::CallLoweringInfo CLI(DAG);
13706   CLI.setDebugLoc(dl).setChain(InChain)
13707     .setCallee(getLibcallCallingConv(LC),
13708                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13709                Callee, &Args, 0)
13710     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13711
13712   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13713   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13714 }
13715
13716 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13717                              SelectionDAG &DAG) {
13718   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13719   EVT VT = Op0.getValueType();
13720   SDLoc dl(Op);
13721
13722   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13723          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13724
13725   // Get the high parts.
13726   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13727   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13728   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13729
13730   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13731   // ints.
13732   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13733   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13734   unsigned Opcode =
13735       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13736   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13737                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13738   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13739                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13740
13741   // Shuffle it back into the right order.
13742   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13743   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13744   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13745   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13746
13747   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13748   // unsigned multiply.
13749   if (IsSigned && !Subtarget->hasSSE41()) {
13750     SDValue ShAmt =
13751         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13752     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13753                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13754     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13755                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13756
13757     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13758     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13759   }
13760
13761   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13762 }
13763
13764 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13765                                          const X86Subtarget *Subtarget) {
13766   MVT VT = Op.getSimpleValueType();
13767   SDLoc dl(Op);
13768   SDValue R = Op.getOperand(0);
13769   SDValue Amt = Op.getOperand(1);
13770
13771   // Optimize shl/srl/sra with constant shift amount.
13772   if (isSplatVector(Amt.getNode())) {
13773     SDValue SclrAmt = Amt->getOperand(0);
13774     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13775       uint64_t ShiftAmt = C->getZExtValue();
13776
13777       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13778           (Subtarget->hasInt256() &&
13779            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13780           (Subtarget->hasAVX512() &&
13781            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13782         if (Op.getOpcode() == ISD::SHL)
13783           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13784                                             DAG);
13785         if (Op.getOpcode() == ISD::SRL)
13786           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13787                                             DAG);
13788         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13789           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13790                                             DAG);
13791       }
13792
13793       if (VT == MVT::v16i8) {
13794         if (Op.getOpcode() == ISD::SHL) {
13795           // Make a large shift.
13796           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13797                                                    MVT::v8i16, R, ShiftAmt,
13798                                                    DAG);
13799           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13800           // Zero out the rightmost bits.
13801           SmallVector<SDValue, 16> V(16,
13802                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13803                                                      MVT::i8));
13804           return DAG.getNode(ISD::AND, dl, VT, SHL,
13805                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13806         }
13807         if (Op.getOpcode() == ISD::SRL) {
13808           // Make a large shift.
13809           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13810                                                    MVT::v8i16, R, ShiftAmt,
13811                                                    DAG);
13812           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13813           // Zero out the leftmost bits.
13814           SmallVector<SDValue, 16> V(16,
13815                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13816                                                      MVT::i8));
13817           return DAG.getNode(ISD::AND, dl, VT, SRL,
13818                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13819         }
13820         if (Op.getOpcode() == ISD::SRA) {
13821           if (ShiftAmt == 7) {
13822             // R s>> 7  ===  R s< 0
13823             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13824             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13825           }
13826
13827           // R s>> a === ((R u>> a) ^ m) - m
13828           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13829           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13830                                                          MVT::i8));
13831           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13832           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13833           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13834           return Res;
13835         }
13836         llvm_unreachable("Unknown shift opcode.");
13837       }
13838
13839       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13840         if (Op.getOpcode() == ISD::SHL) {
13841           // Make a large shift.
13842           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13843                                                    MVT::v16i16, R, ShiftAmt,
13844                                                    DAG);
13845           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13846           // Zero out the rightmost bits.
13847           SmallVector<SDValue, 32> V(32,
13848                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13849                                                      MVT::i8));
13850           return DAG.getNode(ISD::AND, dl, VT, SHL,
13851                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13852         }
13853         if (Op.getOpcode() == ISD::SRL) {
13854           // Make a large shift.
13855           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13856                                                    MVT::v16i16, R, ShiftAmt,
13857                                                    DAG);
13858           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13859           // Zero out the leftmost bits.
13860           SmallVector<SDValue, 32> V(32,
13861                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13862                                                      MVT::i8));
13863           return DAG.getNode(ISD::AND, dl, VT, SRL,
13864                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13865         }
13866         if (Op.getOpcode() == ISD::SRA) {
13867           if (ShiftAmt == 7) {
13868             // R s>> 7  ===  R s< 0
13869             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13870             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13871           }
13872
13873           // R s>> a === ((R u>> a) ^ m) - m
13874           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13875           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13876                                                          MVT::i8));
13877           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13878           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13879           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13880           return Res;
13881         }
13882         llvm_unreachable("Unknown shift opcode.");
13883       }
13884     }
13885   }
13886
13887   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13888   if (!Subtarget->is64Bit() &&
13889       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13890       Amt.getOpcode() == ISD::BITCAST &&
13891       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13892     Amt = Amt.getOperand(0);
13893     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13894                      VT.getVectorNumElements();
13895     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13896     uint64_t ShiftAmt = 0;
13897     for (unsigned i = 0; i != Ratio; ++i) {
13898       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13899       if (!C)
13900         return SDValue();
13901       // 6 == Log2(64)
13902       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13903     }
13904     // Check remaining shift amounts.
13905     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13906       uint64_t ShAmt = 0;
13907       for (unsigned j = 0; j != Ratio; ++j) {
13908         ConstantSDNode *C =
13909           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13910         if (!C)
13911           return SDValue();
13912         // 6 == Log2(64)
13913         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13914       }
13915       if (ShAmt != ShiftAmt)
13916         return SDValue();
13917     }
13918     switch (Op.getOpcode()) {
13919     default:
13920       llvm_unreachable("Unknown shift opcode!");
13921     case ISD::SHL:
13922       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13923                                         DAG);
13924     case ISD::SRL:
13925       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13926                                         DAG);
13927     case ISD::SRA:
13928       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13929                                         DAG);
13930     }
13931   }
13932
13933   return SDValue();
13934 }
13935
13936 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13937                                         const X86Subtarget* Subtarget) {
13938   MVT VT = Op.getSimpleValueType();
13939   SDLoc dl(Op);
13940   SDValue R = Op.getOperand(0);
13941   SDValue Amt = Op.getOperand(1);
13942
13943   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13944       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13945       (Subtarget->hasInt256() &&
13946        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13947         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13948        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13949     SDValue BaseShAmt;
13950     EVT EltVT = VT.getVectorElementType();
13951
13952     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13953       unsigned NumElts = VT.getVectorNumElements();
13954       unsigned i, j;
13955       for (i = 0; i != NumElts; ++i) {
13956         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13957           continue;
13958         break;
13959       }
13960       for (j = i; j != NumElts; ++j) {
13961         SDValue Arg = Amt.getOperand(j);
13962         if (Arg.getOpcode() == ISD::UNDEF) continue;
13963         if (Arg != Amt.getOperand(i))
13964           break;
13965       }
13966       if (i != NumElts && j == NumElts)
13967         BaseShAmt = Amt.getOperand(i);
13968     } else {
13969       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13970         Amt = Amt.getOperand(0);
13971       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13972                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13973         SDValue InVec = Amt.getOperand(0);
13974         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13975           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13976           unsigned i = 0;
13977           for (; i != NumElts; ++i) {
13978             SDValue Arg = InVec.getOperand(i);
13979             if (Arg.getOpcode() == ISD::UNDEF) continue;
13980             BaseShAmt = Arg;
13981             break;
13982           }
13983         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13984            if (ConstantSDNode *C =
13985                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13986              unsigned SplatIdx =
13987                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13988              if (C->getZExtValue() == SplatIdx)
13989                BaseShAmt = InVec.getOperand(1);
13990            }
13991         }
13992         if (!BaseShAmt.getNode())
13993           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13994                                   DAG.getIntPtrConstant(0));
13995       }
13996     }
13997
13998     if (BaseShAmt.getNode()) {
13999       if (EltVT.bitsGT(MVT::i32))
14000         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
14001       else if (EltVT.bitsLT(MVT::i32))
14002         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
14003
14004       switch (Op.getOpcode()) {
14005       default:
14006         llvm_unreachable("Unknown shift opcode!");
14007       case ISD::SHL:
14008         switch (VT.SimpleTy) {
14009         default: return SDValue();
14010         case MVT::v2i64:
14011         case MVT::v4i32:
14012         case MVT::v8i16:
14013         case MVT::v4i64:
14014         case MVT::v8i32:
14015         case MVT::v16i16:
14016         case MVT::v16i32:
14017         case MVT::v8i64:
14018           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
14019         }
14020       case ISD::SRA:
14021         switch (VT.SimpleTy) {
14022         default: return SDValue();
14023         case MVT::v4i32:
14024         case MVT::v8i16:
14025         case MVT::v8i32:
14026         case MVT::v16i16:
14027         case MVT::v16i32:
14028         case MVT::v8i64:
14029           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
14030         }
14031       case ISD::SRL:
14032         switch (VT.SimpleTy) {
14033         default: return SDValue();
14034         case MVT::v2i64:
14035         case MVT::v4i32:
14036         case MVT::v8i16:
14037         case MVT::v4i64:
14038         case MVT::v8i32:
14039         case MVT::v16i16:
14040         case MVT::v16i32:
14041         case MVT::v8i64:
14042           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
14043         }
14044       }
14045     }
14046   }
14047
14048   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14049   if (!Subtarget->is64Bit() &&
14050       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
14051       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
14052       Amt.getOpcode() == ISD::BITCAST &&
14053       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14054     Amt = Amt.getOperand(0);
14055     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14056                      VT.getVectorNumElements();
14057     std::vector<SDValue> Vals(Ratio);
14058     for (unsigned i = 0; i != Ratio; ++i)
14059       Vals[i] = Amt.getOperand(i);
14060     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14061       for (unsigned j = 0; j != Ratio; ++j)
14062         if (Vals[j] != Amt.getOperand(i + j))
14063           return SDValue();
14064     }
14065     switch (Op.getOpcode()) {
14066     default:
14067       llvm_unreachable("Unknown shift opcode!");
14068     case ISD::SHL:
14069       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
14070     case ISD::SRL:
14071       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
14072     case ISD::SRA:
14073       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
14074     }
14075   }
14076
14077   return SDValue();
14078 }
14079
14080 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
14081                           SelectionDAG &DAG) {
14082
14083   MVT VT = Op.getSimpleValueType();
14084   SDLoc dl(Op);
14085   SDValue R = Op.getOperand(0);
14086   SDValue Amt = Op.getOperand(1);
14087   SDValue V;
14088
14089   if (!Subtarget->hasSSE2())
14090     return SDValue();
14091
14092   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14093   if (V.getNode())
14094     return V;
14095
14096   V = LowerScalarVariableShift(Op, DAG, Subtarget);
14097   if (V.getNode())
14098       return V;
14099
14100   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14101     return Op;
14102   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14103   if (Subtarget->hasInt256()) {
14104     if (Op.getOpcode() == ISD::SRL &&
14105         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14106          VT == MVT::v4i64 || VT == MVT::v8i32))
14107       return Op;
14108     if (Op.getOpcode() == ISD::SHL &&
14109         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14110          VT == MVT::v4i64 || VT == MVT::v8i32))
14111       return Op;
14112     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14113       return Op;
14114   }
14115
14116   // If possible, lower this packed shift into a vector multiply instead of
14117   // expanding it into a sequence of scalar shifts.
14118   // Do this only if the vector shift count is a constant build_vector.
14119   if (Op.getOpcode() == ISD::SHL && 
14120       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14121        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14122       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14123     SmallVector<SDValue, 8> Elts;
14124     EVT SVT = VT.getScalarType();
14125     unsigned SVTBits = SVT.getSizeInBits();
14126     const APInt &One = APInt(SVTBits, 1);
14127     unsigned NumElems = VT.getVectorNumElements();
14128
14129     for (unsigned i=0; i !=NumElems; ++i) {
14130       SDValue Op = Amt->getOperand(i);
14131       if (Op->getOpcode() == ISD::UNDEF) {
14132         Elts.push_back(Op);
14133         continue;
14134       }
14135
14136       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14137       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14138       uint64_t ShAmt = C.getZExtValue();
14139       if (ShAmt >= SVTBits) {
14140         Elts.push_back(DAG.getUNDEF(SVT));
14141         continue;
14142       }
14143       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14144     }
14145     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14146     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14147   }
14148
14149   // Lower SHL with variable shift amount.
14150   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14151     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14152
14153     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14154     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14155     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14156     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14157   }
14158
14159   // If possible, lower this shift as a sequence of two shifts by
14160   // constant plus a MOVSS/MOVSD instead of scalarizing it.
14161   // Example:
14162   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14163   //
14164   // Could be rewritten as:
14165   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14166   //
14167   // The advantage is that the two shifts from the example would be
14168   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14169   // the vector shift into four scalar shifts plus four pairs of vector
14170   // insert/extract.
14171   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14172       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14173     unsigned TargetOpcode = X86ISD::MOVSS;
14174     bool CanBeSimplified;
14175     // The splat value for the first packed shift (the 'X' from the example).
14176     SDValue Amt1 = Amt->getOperand(0);
14177     // The splat value for the second packed shift (the 'Y' from the example).
14178     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14179                                         Amt->getOperand(2);
14180
14181     // See if it is possible to replace this node with a sequence of
14182     // two shifts followed by a MOVSS/MOVSD
14183     if (VT == MVT::v4i32) {
14184       // Check if it is legal to use a MOVSS.
14185       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14186                         Amt2 == Amt->getOperand(3);
14187       if (!CanBeSimplified) {
14188         // Otherwise, check if we can still simplify this node using a MOVSD.
14189         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14190                           Amt->getOperand(2) == Amt->getOperand(3);
14191         TargetOpcode = X86ISD::MOVSD;
14192         Amt2 = Amt->getOperand(2);
14193       }
14194     } else {
14195       // Do similar checks for the case where the machine value type
14196       // is MVT::v8i16.
14197       CanBeSimplified = Amt1 == Amt->getOperand(1);
14198       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14199         CanBeSimplified = Amt2 == Amt->getOperand(i);
14200
14201       if (!CanBeSimplified) {
14202         TargetOpcode = X86ISD::MOVSD;
14203         CanBeSimplified = true;
14204         Amt2 = Amt->getOperand(4);
14205         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14206           CanBeSimplified = Amt1 == Amt->getOperand(i);
14207         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14208           CanBeSimplified = Amt2 == Amt->getOperand(j);
14209       }
14210     }
14211     
14212     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14213         isa<ConstantSDNode>(Amt2)) {
14214       // Replace this node with two shifts followed by a MOVSS/MOVSD.
14215       EVT CastVT = MVT::v4i32;
14216       SDValue Splat1 = 
14217         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14218       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14219       SDValue Splat2 = 
14220         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14221       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14222       if (TargetOpcode == X86ISD::MOVSD)
14223         CastVT = MVT::v2i64;
14224       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14225       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14226       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14227                                             BitCast1, DAG);
14228       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14229     }
14230   }
14231
14232   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14233     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14234
14235     // a = a << 5;
14236     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14237     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14238
14239     // Turn 'a' into a mask suitable for VSELECT
14240     SDValue VSelM = DAG.getConstant(0x80, VT);
14241     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14242     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14243
14244     SDValue CM1 = DAG.getConstant(0x0f, VT);
14245     SDValue CM2 = DAG.getConstant(0x3f, VT);
14246
14247     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14248     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14249     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14250     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14251     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14252
14253     // a += a
14254     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14255     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14256     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14257
14258     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14259     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14260     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14261     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14262     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14263
14264     // a += a
14265     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14266     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14267     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14268
14269     // return VSELECT(r, r+r, a);
14270     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14271                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14272     return R;
14273   }
14274
14275   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14276   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14277   // solution better.
14278   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14279     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14280     unsigned ExtOpc =
14281         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14282     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14283     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14284     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14285                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14286     }
14287
14288   // Decompose 256-bit shifts into smaller 128-bit shifts.
14289   if (VT.is256BitVector()) {
14290     unsigned NumElems = VT.getVectorNumElements();
14291     MVT EltVT = VT.getVectorElementType();
14292     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14293
14294     // Extract the two vectors
14295     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14296     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14297
14298     // Recreate the shift amount vectors
14299     SDValue Amt1, Amt2;
14300     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14301       // Constant shift amount
14302       SmallVector<SDValue, 4> Amt1Csts;
14303       SmallVector<SDValue, 4> Amt2Csts;
14304       for (unsigned i = 0; i != NumElems/2; ++i)
14305         Amt1Csts.push_back(Amt->getOperand(i));
14306       for (unsigned i = NumElems/2; i != NumElems; ++i)
14307         Amt2Csts.push_back(Amt->getOperand(i));
14308
14309       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14310       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14311     } else {
14312       // Variable shift amount
14313       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14314       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14315     }
14316
14317     // Issue new vector shifts for the smaller types
14318     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14319     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14320
14321     // Concatenate the result back
14322     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14323   }
14324
14325   return SDValue();
14326 }
14327
14328 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14329   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14330   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14331   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14332   // has only one use.
14333   SDNode *N = Op.getNode();
14334   SDValue LHS = N->getOperand(0);
14335   SDValue RHS = N->getOperand(1);
14336   unsigned BaseOp = 0;
14337   unsigned Cond = 0;
14338   SDLoc DL(Op);
14339   switch (Op.getOpcode()) {
14340   default: llvm_unreachable("Unknown ovf instruction!");
14341   case ISD::SADDO:
14342     // A subtract of one will be selected as a INC. Note that INC doesn't
14343     // set CF, so we can't do this for UADDO.
14344     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14345       if (C->isOne()) {
14346         BaseOp = X86ISD::INC;
14347         Cond = X86::COND_O;
14348         break;
14349       }
14350     BaseOp = X86ISD::ADD;
14351     Cond = X86::COND_O;
14352     break;
14353   case ISD::UADDO:
14354     BaseOp = X86ISD::ADD;
14355     Cond = X86::COND_B;
14356     break;
14357   case ISD::SSUBO:
14358     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14359     // set CF, so we can't do this for USUBO.
14360     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14361       if (C->isOne()) {
14362         BaseOp = X86ISD::DEC;
14363         Cond = X86::COND_O;
14364         break;
14365       }
14366     BaseOp = X86ISD::SUB;
14367     Cond = X86::COND_O;
14368     break;
14369   case ISD::USUBO:
14370     BaseOp = X86ISD::SUB;
14371     Cond = X86::COND_B;
14372     break;
14373   case ISD::SMULO:
14374     BaseOp = X86ISD::SMUL;
14375     Cond = X86::COND_O;
14376     break;
14377   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14378     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14379                                  MVT::i32);
14380     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14381
14382     SDValue SetCC =
14383       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14384                   DAG.getConstant(X86::COND_O, MVT::i32),
14385                   SDValue(Sum.getNode(), 2));
14386
14387     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14388   }
14389   }
14390
14391   // Also sets EFLAGS.
14392   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14393   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14394
14395   SDValue SetCC =
14396     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14397                 DAG.getConstant(Cond, MVT::i32),
14398                 SDValue(Sum.getNode(), 1));
14399
14400   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14401 }
14402
14403 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14404                                                   SelectionDAG &DAG) const {
14405   SDLoc dl(Op);
14406   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14407   MVT VT = Op.getSimpleValueType();
14408
14409   if (!Subtarget->hasSSE2() || !VT.isVector())
14410     return SDValue();
14411
14412   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14413                       ExtraVT.getScalarType().getSizeInBits();
14414
14415   switch (VT.SimpleTy) {
14416     default: return SDValue();
14417     case MVT::v8i32:
14418     case MVT::v16i16:
14419       if (!Subtarget->hasFp256())
14420         return SDValue();
14421       if (!Subtarget->hasInt256()) {
14422         // needs to be split
14423         unsigned NumElems = VT.getVectorNumElements();
14424
14425         // Extract the LHS vectors
14426         SDValue LHS = Op.getOperand(0);
14427         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14428         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14429
14430         MVT EltVT = VT.getVectorElementType();
14431         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14432
14433         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14434         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14435         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14436                                    ExtraNumElems/2);
14437         SDValue Extra = DAG.getValueType(ExtraVT);
14438
14439         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14440         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14441
14442         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14443       }
14444       // fall through
14445     case MVT::v4i32:
14446     case MVT::v8i16: {
14447       SDValue Op0 = Op.getOperand(0);
14448       SDValue Op00 = Op0.getOperand(0);
14449       SDValue Tmp1;
14450       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14451       if (Op0.getOpcode() == ISD::BITCAST &&
14452           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14453         // (sext (vzext x)) -> (vsext x)
14454         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14455         if (Tmp1.getNode()) {
14456           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14457           // This folding is only valid when the in-reg type is a vector of i8,
14458           // i16, or i32.
14459           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14460               ExtraEltVT == MVT::i32) {
14461             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14462             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14463                    "This optimization is invalid without a VZEXT.");
14464             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14465           }
14466           Op0 = Tmp1;
14467         }
14468       }
14469
14470       // If the above didn't work, then just use Shift-Left + Shift-Right.
14471       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14472                                         DAG);
14473       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14474                                         DAG);
14475     }
14476   }
14477 }
14478
14479 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14480                                  SelectionDAG &DAG) {
14481   SDLoc dl(Op);
14482   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14483     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14484   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14485     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14486
14487   // The only fence that needs an instruction is a sequentially-consistent
14488   // cross-thread fence.
14489   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14490     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14491     // no-sse2). There isn't any reason to disable it if the target processor
14492     // supports it.
14493     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14494       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14495
14496     SDValue Chain = Op.getOperand(0);
14497     SDValue Zero = DAG.getConstant(0, MVT::i32);
14498     SDValue Ops[] = {
14499       DAG.getRegister(X86::ESP, MVT::i32), // Base
14500       DAG.getTargetConstant(1, MVT::i8),   // Scale
14501       DAG.getRegister(0, MVT::i32),        // Index
14502       DAG.getTargetConstant(0, MVT::i32),  // Disp
14503       DAG.getRegister(0, MVT::i32),        // Segment.
14504       Zero,
14505       Chain
14506     };
14507     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14508     return SDValue(Res, 0);
14509   }
14510
14511   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14512   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14513 }
14514
14515 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14516                              SelectionDAG &DAG) {
14517   MVT T = Op.getSimpleValueType();
14518   SDLoc DL(Op);
14519   unsigned Reg = 0;
14520   unsigned size = 0;
14521   switch(T.SimpleTy) {
14522   default: llvm_unreachable("Invalid value type!");
14523   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14524   case MVT::i16: Reg = X86::AX;  size = 2; break;
14525   case MVT::i32: Reg = X86::EAX; size = 4; break;
14526   case MVT::i64:
14527     assert(Subtarget->is64Bit() && "Node not type legal!");
14528     Reg = X86::RAX; size = 8;
14529     break;
14530   }
14531   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14532                                     Op.getOperand(2), SDValue());
14533   SDValue Ops[] = { cpIn.getValue(0),
14534                     Op.getOperand(1),
14535                     Op.getOperand(3),
14536                     DAG.getTargetConstant(size, MVT::i8),
14537                     cpIn.getValue(1) };
14538   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14539   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14540   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14541                                            Ops, T, MMO);
14542   SDValue cpOut =
14543     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14544   return cpOut;
14545 }
14546
14547 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14548                             SelectionDAG &DAG) {
14549   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14550   MVT DstVT = Op.getSimpleValueType();
14551
14552   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14553     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14554     if (DstVT != MVT::f64)
14555       // This conversion needs to be expanded.
14556       return SDValue();
14557
14558     SDValue InVec = Op->getOperand(0);
14559     SDLoc dl(Op);
14560     unsigned NumElts = SrcVT.getVectorNumElements();
14561     EVT SVT = SrcVT.getVectorElementType();
14562
14563     // Widen the vector in input in the case of MVT::v2i32.
14564     // Example: from MVT::v2i32 to MVT::v4i32.
14565     SmallVector<SDValue, 16> Elts;
14566     for (unsigned i = 0, e = NumElts; i != e; ++i)
14567       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14568                                  DAG.getIntPtrConstant(i)));
14569
14570     // Explicitly mark the extra elements as Undef.
14571     SDValue Undef = DAG.getUNDEF(SVT);
14572     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14573       Elts.push_back(Undef);
14574
14575     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14576     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14577     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14578     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14579                        DAG.getIntPtrConstant(0));
14580   }
14581
14582   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14583          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14584   assert((DstVT == MVT::i64 ||
14585           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14586          "Unexpected custom BITCAST");
14587   // i64 <=> MMX conversions are Legal.
14588   if (SrcVT==MVT::i64 && DstVT.isVector())
14589     return Op;
14590   if (DstVT==MVT::i64 && SrcVT.isVector())
14591     return Op;
14592   // MMX <=> MMX conversions are Legal.
14593   if (SrcVT.isVector() && DstVT.isVector())
14594     return Op;
14595   // All other conversions need to be expanded.
14596   return SDValue();
14597 }
14598
14599 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14600   SDNode *Node = Op.getNode();
14601   SDLoc dl(Node);
14602   EVT T = Node->getValueType(0);
14603   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14604                               DAG.getConstant(0, T), Node->getOperand(2));
14605   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14606                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14607                        Node->getOperand(0),
14608                        Node->getOperand(1), negOp,
14609                        cast<AtomicSDNode>(Node)->getMemOperand(),
14610                        cast<AtomicSDNode>(Node)->getOrdering(),
14611                        cast<AtomicSDNode>(Node)->getSynchScope());
14612 }
14613
14614 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14615   SDNode *Node = Op.getNode();
14616   SDLoc dl(Node);
14617   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14618
14619   // Convert seq_cst store -> xchg
14620   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14621   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14622   //        (The only way to get a 16-byte store is cmpxchg16b)
14623   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14624   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14625       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14626     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14627                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14628                                  Node->getOperand(0),
14629                                  Node->getOperand(1), Node->getOperand(2),
14630                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14631                                  cast<AtomicSDNode>(Node)->getOrdering(),
14632                                  cast<AtomicSDNode>(Node)->getSynchScope());
14633     return Swap.getValue(1);
14634   }
14635   // Other atomic stores have a simple pattern.
14636   return Op;
14637 }
14638
14639 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14640   EVT VT = Op.getNode()->getSimpleValueType(0);
14641
14642   // Let legalize expand this if it isn't a legal type yet.
14643   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14644     return SDValue();
14645
14646   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14647
14648   unsigned Opc;
14649   bool ExtraOp = false;
14650   switch (Op.getOpcode()) {
14651   default: llvm_unreachable("Invalid code");
14652   case ISD::ADDC: Opc = X86ISD::ADD; break;
14653   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14654   case ISD::SUBC: Opc = X86ISD::SUB; break;
14655   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14656   }
14657
14658   if (!ExtraOp)
14659     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14660                        Op.getOperand(1));
14661   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14662                      Op.getOperand(1), Op.getOperand(2));
14663 }
14664
14665 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14666                             SelectionDAG &DAG) {
14667   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14668
14669   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14670   // which returns the values as { float, float } (in XMM0) or
14671   // { double, double } (which is returned in XMM0, XMM1).
14672   SDLoc dl(Op);
14673   SDValue Arg = Op.getOperand(0);
14674   EVT ArgVT = Arg.getValueType();
14675   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14676
14677   TargetLowering::ArgListTy Args;
14678   TargetLowering::ArgListEntry Entry;
14679
14680   Entry.Node = Arg;
14681   Entry.Ty = ArgTy;
14682   Entry.isSExt = false;
14683   Entry.isZExt = false;
14684   Args.push_back(Entry);
14685
14686   bool isF64 = ArgVT == MVT::f64;
14687   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14688   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14689   // the results are returned via SRet in memory.
14690   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14691   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14692   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14693
14694   Type *RetTy = isF64
14695     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14696     : (Type*)VectorType::get(ArgTy, 4);
14697
14698   TargetLowering::CallLoweringInfo CLI(DAG);
14699   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14700     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14701
14702   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14703
14704   if (isF64)
14705     // Returned in xmm0 and xmm1.
14706     return CallResult.first;
14707
14708   // Returned in bits 0:31 and 32:64 xmm0.
14709   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14710                                CallResult.first, DAG.getIntPtrConstant(0));
14711   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14712                                CallResult.first, DAG.getIntPtrConstant(1));
14713   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14714   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14715 }
14716
14717 /// LowerOperation - Provide custom lowering hooks for some operations.
14718 ///
14719 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14720   switch (Op.getOpcode()) {
14721   default: llvm_unreachable("Should not custom lower this!");
14722   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14723   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14724   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14725   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14726   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14727   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14728   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14729   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14730   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14731   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14732   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14733   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14734   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14735   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14736   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14737   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14738   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14739   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14740   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14741   case ISD::SHL_PARTS:
14742   case ISD::SRA_PARTS:
14743   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14744   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14745   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14746   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14747   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14748   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14749   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14750   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14751   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14752   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14753   case ISD::FABS:               return LowerFABS(Op, DAG);
14754   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14755   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14756   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14757   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14758   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14759   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14760   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14761   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14762   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14763   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14764   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14765   case ISD::INTRINSIC_VOID:
14766   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14767   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14768   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14769   case ISD::FRAME_TO_ARGS_OFFSET:
14770                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14771   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14772   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14773   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14774   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14775   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14776   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14777   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14778   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14779   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14780   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14781   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14782   case ISD::UMUL_LOHI:
14783   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14784   case ISD::SRA:
14785   case ISD::SRL:
14786   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14787   case ISD::SADDO:
14788   case ISD::UADDO:
14789   case ISD::SSUBO:
14790   case ISD::USUBO:
14791   case ISD::SMULO:
14792   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14793   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14794   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14795   case ISD::ADDC:
14796   case ISD::ADDE:
14797   case ISD::SUBC:
14798   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14799   case ISD::ADD:                return LowerADD(Op, DAG);
14800   case ISD::SUB:                return LowerSUB(Op, DAG);
14801   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14802   }
14803 }
14804
14805 static void ReplaceATOMIC_LOAD(SDNode *Node,
14806                                   SmallVectorImpl<SDValue> &Results,
14807                                   SelectionDAG &DAG) {
14808   SDLoc dl(Node);
14809   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14810
14811   // Convert wide load -> cmpxchg8b/cmpxchg16b
14812   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14813   //        (The only way to get a 16-byte load is cmpxchg16b)
14814   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14815   SDValue Zero = DAG.getConstant(0, VT);
14816   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14817                                Node->getOperand(0),
14818                                Node->getOperand(1), Zero, Zero,
14819                                cast<AtomicSDNode>(Node)->getMemOperand(),
14820                                cast<AtomicSDNode>(Node)->getOrdering(),
14821                                cast<AtomicSDNode>(Node)->getOrdering(),
14822                                cast<AtomicSDNode>(Node)->getSynchScope());
14823   Results.push_back(Swap.getValue(0));
14824   Results.push_back(Swap.getValue(1));
14825 }
14826
14827 static void
14828 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14829                         SelectionDAG &DAG, unsigned NewOp) {
14830   SDLoc dl(Node);
14831   assert (Node->getValueType(0) == MVT::i64 &&
14832           "Only know how to expand i64 atomics");
14833
14834   SDValue Chain = Node->getOperand(0);
14835   SDValue In1 = Node->getOperand(1);
14836   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14837                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14838   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14839                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14840   SDValue Ops[] = { Chain, In1, In2L, In2H };
14841   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14842   SDValue Result =
14843     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14844                             cast<MemSDNode>(Node)->getMemOperand());
14845   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14846   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14847   Results.push_back(Result.getValue(2));
14848 }
14849
14850 /// ReplaceNodeResults - Replace a node with an illegal result type
14851 /// with a new node built out of custom code.
14852 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14853                                            SmallVectorImpl<SDValue>&Results,
14854                                            SelectionDAG &DAG) const {
14855   SDLoc dl(N);
14856   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14857   switch (N->getOpcode()) {
14858   default:
14859     llvm_unreachable("Do not know how to custom type legalize this operation!");
14860   case ISD::SIGN_EXTEND_INREG:
14861   case ISD::ADDC:
14862   case ISD::ADDE:
14863   case ISD::SUBC:
14864   case ISD::SUBE:
14865     // We don't want to expand or promote these.
14866     return;
14867   case ISD::SDIV:
14868   case ISD::UDIV:
14869   case ISD::SREM:
14870   case ISD::UREM:
14871   case ISD::SDIVREM:
14872   case ISD::UDIVREM: {
14873     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14874     Results.push_back(V);
14875     return;
14876   }
14877   case ISD::FP_TO_SINT:
14878   case ISD::FP_TO_UINT: {
14879     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14880
14881     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14882       return;
14883
14884     std::pair<SDValue,SDValue> Vals =
14885         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14886     SDValue FIST = Vals.first, StackSlot = Vals.second;
14887     if (FIST.getNode()) {
14888       EVT VT = N->getValueType(0);
14889       // Return a load from the stack slot.
14890       if (StackSlot.getNode())
14891         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14892                                       MachinePointerInfo(),
14893                                       false, false, false, 0));
14894       else
14895         Results.push_back(FIST);
14896     }
14897     return;
14898   }
14899   case ISD::UINT_TO_FP: {
14900     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14901     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14902         N->getValueType(0) != MVT::v2f32)
14903       return;
14904     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14905                                  N->getOperand(0));
14906     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14907                                      MVT::f64);
14908     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14909     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14910                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14911     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14912     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14913     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14914     return;
14915   }
14916   case ISD::FP_ROUND: {
14917     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14918         return;
14919     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14920     Results.push_back(V);
14921     return;
14922   }
14923   case ISD::INTRINSIC_W_CHAIN: {
14924     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14925     switch (IntNo) {
14926     default : llvm_unreachable("Do not know how to custom type "
14927                                "legalize this intrinsic operation!");
14928     case Intrinsic::x86_rdtsc:
14929       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14930                                      Results);
14931     case Intrinsic::x86_rdtscp:
14932       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14933                                      Results);
14934     }
14935   }
14936   case ISD::READCYCLECOUNTER: {
14937     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14938                                    Results);
14939   }
14940   case ISD::ATOMIC_CMP_SWAP: {
14941     EVT T = N->getValueType(0);
14942     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14943     bool Regs64bit = T == MVT::i128;
14944     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14945     SDValue cpInL, cpInH;
14946     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14947                         DAG.getConstant(0, HalfT));
14948     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14949                         DAG.getConstant(1, HalfT));
14950     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14951                              Regs64bit ? X86::RAX : X86::EAX,
14952                              cpInL, SDValue());
14953     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14954                              Regs64bit ? X86::RDX : X86::EDX,
14955                              cpInH, cpInL.getValue(1));
14956     SDValue swapInL, swapInH;
14957     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14958                           DAG.getConstant(0, HalfT));
14959     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14960                           DAG.getConstant(1, HalfT));
14961     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14962                                Regs64bit ? X86::RBX : X86::EBX,
14963                                swapInL, cpInH.getValue(1));
14964     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14965                                Regs64bit ? X86::RCX : X86::ECX,
14966                                swapInH, swapInL.getValue(1));
14967     SDValue Ops[] = { swapInH.getValue(0),
14968                       N->getOperand(1),
14969                       swapInH.getValue(1) };
14970     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14971     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14972     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14973                                   X86ISD::LCMPXCHG8_DAG;
14974     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14975     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14976                                         Regs64bit ? X86::RAX : X86::EAX,
14977                                         HalfT, Result.getValue(1));
14978     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14979                                         Regs64bit ? X86::RDX : X86::EDX,
14980                                         HalfT, cpOutL.getValue(2));
14981     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14982     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14983     Results.push_back(cpOutH.getValue(1));
14984     return;
14985   }
14986   case ISD::ATOMIC_LOAD_ADD:
14987   case ISD::ATOMIC_LOAD_AND:
14988   case ISD::ATOMIC_LOAD_NAND:
14989   case ISD::ATOMIC_LOAD_OR:
14990   case ISD::ATOMIC_LOAD_SUB:
14991   case ISD::ATOMIC_LOAD_XOR:
14992   case ISD::ATOMIC_LOAD_MAX:
14993   case ISD::ATOMIC_LOAD_MIN:
14994   case ISD::ATOMIC_LOAD_UMAX:
14995   case ISD::ATOMIC_LOAD_UMIN:
14996   case ISD::ATOMIC_SWAP: {
14997     unsigned Opc;
14998     switch (N->getOpcode()) {
14999     default: llvm_unreachable("Unexpected opcode");
15000     case ISD::ATOMIC_LOAD_ADD:
15001       Opc = X86ISD::ATOMADD64_DAG;
15002       break;
15003     case ISD::ATOMIC_LOAD_AND:
15004       Opc = X86ISD::ATOMAND64_DAG;
15005       break;
15006     case ISD::ATOMIC_LOAD_NAND:
15007       Opc = X86ISD::ATOMNAND64_DAG;
15008       break;
15009     case ISD::ATOMIC_LOAD_OR:
15010       Opc = X86ISD::ATOMOR64_DAG;
15011       break;
15012     case ISD::ATOMIC_LOAD_SUB:
15013       Opc = X86ISD::ATOMSUB64_DAG;
15014       break;
15015     case ISD::ATOMIC_LOAD_XOR:
15016       Opc = X86ISD::ATOMXOR64_DAG;
15017       break;
15018     case ISD::ATOMIC_LOAD_MAX:
15019       Opc = X86ISD::ATOMMAX64_DAG;
15020       break;
15021     case ISD::ATOMIC_LOAD_MIN:
15022       Opc = X86ISD::ATOMMIN64_DAG;
15023       break;
15024     case ISD::ATOMIC_LOAD_UMAX:
15025       Opc = X86ISD::ATOMUMAX64_DAG;
15026       break;
15027     case ISD::ATOMIC_LOAD_UMIN:
15028       Opc = X86ISD::ATOMUMIN64_DAG;
15029       break;
15030     case ISD::ATOMIC_SWAP:
15031       Opc = X86ISD::ATOMSWAP64_DAG;
15032       break;
15033     }
15034     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
15035     return;
15036   }
15037   case ISD::ATOMIC_LOAD: {
15038     ReplaceATOMIC_LOAD(N, Results, DAG);
15039     return;
15040   }
15041   case ISD::BITCAST: {
15042     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15043     EVT DstVT = N->getValueType(0);
15044     EVT SrcVT = N->getOperand(0)->getValueType(0);
15045
15046     if (SrcVT != MVT::f64 ||
15047         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
15048       return;
15049
15050     unsigned NumElts = DstVT.getVectorNumElements();
15051     EVT SVT = DstVT.getVectorElementType();
15052     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15053     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
15054                                    MVT::v2f64, N->getOperand(0));
15055     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
15056
15057     SmallVector<SDValue, 8> Elts;
15058     for (unsigned i = 0, e = NumElts; i != e; ++i)
15059       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
15060                                    ToVecInt, DAG.getIntPtrConstant(i)));
15061
15062     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
15063   }
15064   }
15065 }
15066
15067 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
15068   switch (Opcode) {
15069   default: return nullptr;
15070   case X86ISD::BSF:                return "X86ISD::BSF";
15071   case X86ISD::BSR:                return "X86ISD::BSR";
15072   case X86ISD::SHLD:               return "X86ISD::SHLD";
15073   case X86ISD::SHRD:               return "X86ISD::SHRD";
15074   case X86ISD::FAND:               return "X86ISD::FAND";
15075   case X86ISD::FANDN:              return "X86ISD::FANDN";
15076   case X86ISD::FOR:                return "X86ISD::FOR";
15077   case X86ISD::FXOR:               return "X86ISD::FXOR";
15078   case X86ISD::FSRL:               return "X86ISD::FSRL";
15079   case X86ISD::FILD:               return "X86ISD::FILD";
15080   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
15081   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
15082   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
15083   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
15084   case X86ISD::FLD:                return "X86ISD::FLD";
15085   case X86ISD::FST:                return "X86ISD::FST";
15086   case X86ISD::CALL:               return "X86ISD::CALL";
15087   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
15088   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
15089   case X86ISD::BT:                 return "X86ISD::BT";
15090   case X86ISD::CMP:                return "X86ISD::CMP";
15091   case X86ISD::COMI:               return "X86ISD::COMI";
15092   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
15093   case X86ISD::CMPM:               return "X86ISD::CMPM";
15094   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
15095   case X86ISD::SETCC:              return "X86ISD::SETCC";
15096   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
15097   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
15098   case X86ISD::CMOV:               return "X86ISD::CMOV";
15099   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
15100   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
15101   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
15102   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
15103   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
15104   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
15105   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
15106   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
15107   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
15108   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
15109   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
15110   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
15111   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
15112   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
15113   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
15114   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
15115   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
15116   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
15117   case X86ISD::HADD:               return "X86ISD::HADD";
15118   case X86ISD::HSUB:               return "X86ISD::HSUB";
15119   case X86ISD::FHADD:              return "X86ISD::FHADD";
15120   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
15121   case X86ISD::UMAX:               return "X86ISD::UMAX";
15122   case X86ISD::UMIN:               return "X86ISD::UMIN";
15123   case X86ISD::SMAX:               return "X86ISD::SMAX";
15124   case X86ISD::SMIN:               return "X86ISD::SMIN";
15125   case X86ISD::FMAX:               return "X86ISD::FMAX";
15126   case X86ISD::FMIN:               return "X86ISD::FMIN";
15127   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
15128   case X86ISD::FMINC:              return "X86ISD::FMINC";
15129   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
15130   case X86ISD::FRCP:               return "X86ISD::FRCP";
15131   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
15132   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
15133   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
15134   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
15135   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
15136   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
15137   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
15138   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
15139   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
15140   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
15141   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
15142   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
15143   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
15144   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
15145   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
15146   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
15147   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
15148   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
15149   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
15150   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
15151   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
15152   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
15153   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
15154   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
15155   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
15156   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
15157   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
15158   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
15159   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
15160   case X86ISD::VSHL:               return "X86ISD::VSHL";
15161   case X86ISD::VSRL:               return "X86ISD::VSRL";
15162   case X86ISD::VSRA:               return "X86ISD::VSRA";
15163   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
15164   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
15165   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
15166   case X86ISD::CMPP:               return "X86ISD::CMPP";
15167   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
15168   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
15169   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
15170   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
15171   case X86ISD::ADD:                return "X86ISD::ADD";
15172   case X86ISD::SUB:                return "X86ISD::SUB";
15173   case X86ISD::ADC:                return "X86ISD::ADC";
15174   case X86ISD::SBB:                return "X86ISD::SBB";
15175   case X86ISD::SMUL:               return "X86ISD::SMUL";
15176   case X86ISD::UMUL:               return "X86ISD::UMUL";
15177   case X86ISD::INC:                return "X86ISD::INC";
15178   case X86ISD::DEC:                return "X86ISD::DEC";
15179   case X86ISD::OR:                 return "X86ISD::OR";
15180   case X86ISD::XOR:                return "X86ISD::XOR";
15181   case X86ISD::AND:                return "X86ISD::AND";
15182   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
15183   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
15184   case X86ISD::PTEST:              return "X86ISD::PTEST";
15185   case X86ISD::TESTP:              return "X86ISD::TESTP";
15186   case X86ISD::TESTM:              return "X86ISD::TESTM";
15187   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
15188   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
15189   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
15190   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
15191   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
15192   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
15193   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
15194   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
15195   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
15196   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
15197   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
15198   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
15199   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
15200   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
15201   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
15202   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
15203   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
15204   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
15205   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
15206   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
15207   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
15208   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
15209   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
15210   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
15211   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
15212   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
15213   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
15214   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
15215   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
15216   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
15217   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15218   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
15219   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
15220   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
15221   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
15222   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
15223   case X86ISD::SAHF:               return "X86ISD::SAHF";
15224   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
15225   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
15226   case X86ISD::FMADD:              return "X86ISD::FMADD";
15227   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
15228   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
15229   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
15230   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
15231   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
15232   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
15233   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
15234   case X86ISD::XTEST:              return "X86ISD::XTEST";
15235   }
15236 }
15237
15238 // isLegalAddressingMode - Return true if the addressing mode represented
15239 // by AM is legal for this target, for a load/store of the specified type.
15240 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15241                                               Type *Ty) const {
15242   // X86 supports extremely general addressing modes.
15243   CodeModel::Model M = getTargetMachine().getCodeModel();
15244   Reloc::Model R = getTargetMachine().getRelocationModel();
15245
15246   // X86 allows a sign-extended 32-bit immediate field as a displacement.
15247   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15248     return false;
15249
15250   if (AM.BaseGV) {
15251     unsigned GVFlags =
15252       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15253
15254     // If a reference to this global requires an extra load, we can't fold it.
15255     if (isGlobalStubReference(GVFlags))
15256       return false;
15257
15258     // If BaseGV requires a register for the PIC base, we cannot also have a
15259     // BaseReg specified.
15260     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15261       return false;
15262
15263     // If lower 4G is not available, then we must use rip-relative addressing.
15264     if ((M != CodeModel::Small || R != Reloc::Static) &&
15265         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15266       return false;
15267   }
15268
15269   switch (AM.Scale) {
15270   case 0:
15271   case 1:
15272   case 2:
15273   case 4:
15274   case 8:
15275     // These scales always work.
15276     break;
15277   case 3:
15278   case 5:
15279   case 9:
15280     // These scales are formed with basereg+scalereg.  Only accept if there is
15281     // no basereg yet.
15282     if (AM.HasBaseReg)
15283       return false;
15284     break;
15285   default:  // Other stuff never works.
15286     return false;
15287   }
15288
15289   return true;
15290 }
15291
15292 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15293   unsigned Bits = Ty->getScalarSizeInBits();
15294
15295   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15296   // particularly cheaper than those without.
15297   if (Bits == 8)
15298     return false;
15299
15300   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15301   // variable shifts just as cheap as scalar ones.
15302   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15303     return false;
15304
15305   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15306   // fully general vector.
15307   return true;
15308 }
15309
15310 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15311   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15312     return false;
15313   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15314   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15315   return NumBits1 > NumBits2;
15316 }
15317
15318 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15319   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15320     return false;
15321
15322   if (!isTypeLegal(EVT::getEVT(Ty1)))
15323     return false;
15324
15325   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15326
15327   // Assuming the caller doesn't have a zeroext or signext return parameter,
15328   // truncation all the way down to i1 is valid.
15329   return true;
15330 }
15331
15332 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15333   return isInt<32>(Imm);
15334 }
15335
15336 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15337   // Can also use sub to handle negated immediates.
15338   return isInt<32>(Imm);
15339 }
15340
15341 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15342   if (!VT1.isInteger() || !VT2.isInteger())
15343     return false;
15344   unsigned NumBits1 = VT1.getSizeInBits();
15345   unsigned NumBits2 = VT2.getSizeInBits();
15346   return NumBits1 > NumBits2;
15347 }
15348
15349 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15350   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15351   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15352 }
15353
15354 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15355   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15356   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15357 }
15358
15359 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15360   EVT VT1 = Val.getValueType();
15361   if (isZExtFree(VT1, VT2))
15362     return true;
15363
15364   if (Val.getOpcode() != ISD::LOAD)
15365     return false;
15366
15367   if (!VT1.isSimple() || !VT1.isInteger() ||
15368       !VT2.isSimple() || !VT2.isInteger())
15369     return false;
15370
15371   switch (VT1.getSimpleVT().SimpleTy) {
15372   default: break;
15373   case MVT::i8:
15374   case MVT::i16:
15375   case MVT::i32:
15376     // X86 has 8, 16, and 32-bit zero-extending loads.
15377     return true;
15378   }
15379
15380   return false;
15381 }
15382
15383 bool
15384 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15385   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15386     return false;
15387
15388   VT = VT.getScalarType();
15389
15390   if (!VT.isSimple())
15391     return false;
15392
15393   switch (VT.getSimpleVT().SimpleTy) {
15394   case MVT::f32:
15395   case MVT::f64:
15396     return true;
15397   default:
15398     break;
15399   }
15400
15401   return false;
15402 }
15403
15404 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15405   // i16 instructions are longer (0x66 prefix) and potentially slower.
15406   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15407 }
15408
15409 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15410 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15411 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15412 /// are assumed to be legal.
15413 bool
15414 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15415                                       EVT VT) const {
15416   if (!VT.isSimple())
15417     return false;
15418
15419   MVT SVT = VT.getSimpleVT();
15420
15421   // Very little shuffling can be done for 64-bit vectors right now.
15422   if (VT.getSizeInBits() == 64)
15423     return false;
15424
15425   // If this is a single-input shuffle with no 128 bit lane crossings we can
15426   // lower it into pshufb.
15427   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15428       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15429     bool isLegal = true;
15430     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15431       if (M[I] >= (int)SVT.getVectorNumElements() ||
15432           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15433         isLegal = false;
15434         break;
15435       }
15436     }
15437     if (isLegal)
15438       return true;
15439   }
15440
15441   // FIXME: blends, shifts.
15442   return (SVT.getVectorNumElements() == 2 ||
15443           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15444           isMOVLMask(M, SVT) ||
15445           isSHUFPMask(M, SVT) ||
15446           isPSHUFDMask(M, SVT) ||
15447           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15448           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15449           isPALIGNRMask(M, SVT, Subtarget) ||
15450           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15451           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15452           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15453           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15454           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15455 }
15456
15457 bool
15458 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15459                                           EVT VT) const {
15460   if (!VT.isSimple())
15461     return false;
15462
15463   MVT SVT = VT.getSimpleVT();
15464   unsigned NumElts = SVT.getVectorNumElements();
15465   // FIXME: This collection of masks seems suspect.
15466   if (NumElts == 2)
15467     return true;
15468   if (NumElts == 4 && SVT.is128BitVector()) {
15469     return (isMOVLMask(Mask, SVT)  ||
15470             isCommutedMOVLMask(Mask, SVT, true) ||
15471             isSHUFPMask(Mask, SVT) ||
15472             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15473   }
15474   return false;
15475 }
15476
15477 //===----------------------------------------------------------------------===//
15478 //                           X86 Scheduler Hooks
15479 //===----------------------------------------------------------------------===//
15480
15481 /// Utility function to emit xbegin specifying the start of an RTM region.
15482 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15483                                      const TargetInstrInfo *TII) {
15484   DebugLoc DL = MI->getDebugLoc();
15485
15486   const BasicBlock *BB = MBB->getBasicBlock();
15487   MachineFunction::iterator I = MBB;
15488   ++I;
15489
15490   // For the v = xbegin(), we generate
15491   //
15492   // thisMBB:
15493   //  xbegin sinkMBB
15494   //
15495   // mainMBB:
15496   //  eax = -1
15497   //
15498   // sinkMBB:
15499   //  v = eax
15500
15501   MachineBasicBlock *thisMBB = MBB;
15502   MachineFunction *MF = MBB->getParent();
15503   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15504   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15505   MF->insert(I, mainMBB);
15506   MF->insert(I, sinkMBB);
15507
15508   // Transfer the remainder of BB and its successor edges to sinkMBB.
15509   sinkMBB->splice(sinkMBB->begin(), MBB,
15510                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15511   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15512
15513   // thisMBB:
15514   //  xbegin sinkMBB
15515   //  # fallthrough to mainMBB
15516   //  # abortion to sinkMBB
15517   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15518   thisMBB->addSuccessor(mainMBB);
15519   thisMBB->addSuccessor(sinkMBB);
15520
15521   // mainMBB:
15522   //  EAX = -1
15523   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15524   mainMBB->addSuccessor(sinkMBB);
15525
15526   // sinkMBB:
15527   // EAX is live into the sinkMBB
15528   sinkMBB->addLiveIn(X86::EAX);
15529   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15530           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15531     .addReg(X86::EAX);
15532
15533   MI->eraseFromParent();
15534   return sinkMBB;
15535 }
15536
15537 // Get CMPXCHG opcode for the specified data type.
15538 static unsigned getCmpXChgOpcode(EVT VT) {
15539   switch (VT.getSimpleVT().SimpleTy) {
15540   case MVT::i8:  return X86::LCMPXCHG8;
15541   case MVT::i16: return X86::LCMPXCHG16;
15542   case MVT::i32: return X86::LCMPXCHG32;
15543   case MVT::i64: return X86::LCMPXCHG64;
15544   default:
15545     break;
15546   }
15547   llvm_unreachable("Invalid operand size!");
15548 }
15549
15550 // Get LOAD opcode for the specified data type.
15551 static unsigned getLoadOpcode(EVT VT) {
15552   switch (VT.getSimpleVT().SimpleTy) {
15553   case MVT::i8:  return X86::MOV8rm;
15554   case MVT::i16: return X86::MOV16rm;
15555   case MVT::i32: return X86::MOV32rm;
15556   case MVT::i64: return X86::MOV64rm;
15557   default:
15558     break;
15559   }
15560   llvm_unreachable("Invalid operand size!");
15561 }
15562
15563 // Get opcode of the non-atomic one from the specified atomic instruction.
15564 static unsigned getNonAtomicOpcode(unsigned Opc) {
15565   switch (Opc) {
15566   case X86::ATOMAND8:  return X86::AND8rr;
15567   case X86::ATOMAND16: return X86::AND16rr;
15568   case X86::ATOMAND32: return X86::AND32rr;
15569   case X86::ATOMAND64: return X86::AND64rr;
15570   case X86::ATOMOR8:   return X86::OR8rr;
15571   case X86::ATOMOR16:  return X86::OR16rr;
15572   case X86::ATOMOR32:  return X86::OR32rr;
15573   case X86::ATOMOR64:  return X86::OR64rr;
15574   case X86::ATOMXOR8:  return X86::XOR8rr;
15575   case X86::ATOMXOR16: return X86::XOR16rr;
15576   case X86::ATOMXOR32: return X86::XOR32rr;
15577   case X86::ATOMXOR64: return X86::XOR64rr;
15578   }
15579   llvm_unreachable("Unhandled atomic-load-op opcode!");
15580 }
15581
15582 // Get opcode of the non-atomic one from the specified atomic instruction with
15583 // extra opcode.
15584 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15585                                                unsigned &ExtraOpc) {
15586   switch (Opc) {
15587   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15588   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15589   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15590   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15591   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15592   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15593   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15594   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15595   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15596   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15597   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15598   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15599   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15600   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15601   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15602   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15603   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15604   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15605   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15606   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15607   }
15608   llvm_unreachable("Unhandled atomic-load-op opcode!");
15609 }
15610
15611 // Get opcode of the non-atomic one from the specified atomic instruction for
15612 // 64-bit data type on 32-bit target.
15613 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15614   switch (Opc) {
15615   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15616   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15617   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15618   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15619   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15620   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15621   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15622   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15623   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15624   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15625   }
15626   llvm_unreachable("Unhandled atomic-load-op opcode!");
15627 }
15628
15629 // Get opcode of the non-atomic one from the specified atomic instruction for
15630 // 64-bit data type on 32-bit target with extra opcode.
15631 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15632                                                    unsigned &HiOpc,
15633                                                    unsigned &ExtraOpc) {
15634   switch (Opc) {
15635   case X86::ATOMNAND6432:
15636     ExtraOpc = X86::NOT32r;
15637     HiOpc = X86::AND32rr;
15638     return X86::AND32rr;
15639   }
15640   llvm_unreachable("Unhandled atomic-load-op opcode!");
15641 }
15642
15643 // Get pseudo CMOV opcode from the specified data type.
15644 static unsigned getPseudoCMOVOpc(EVT VT) {
15645   switch (VT.getSimpleVT().SimpleTy) {
15646   case MVT::i8:  return X86::CMOV_GR8;
15647   case MVT::i16: return X86::CMOV_GR16;
15648   case MVT::i32: return X86::CMOV_GR32;
15649   default:
15650     break;
15651   }
15652   llvm_unreachable("Unknown CMOV opcode!");
15653 }
15654
15655 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15656 // They will be translated into a spin-loop or compare-exchange loop from
15657 //
15658 //    ...
15659 //    dst = atomic-fetch-op MI.addr, MI.val
15660 //    ...
15661 //
15662 // to
15663 //
15664 //    ...
15665 //    t1 = LOAD MI.addr
15666 // loop:
15667 //    t4 = phi(t1, t3 / loop)
15668 //    t2 = OP MI.val, t4
15669 //    EAX = t4
15670 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15671 //    t3 = EAX
15672 //    JNE loop
15673 // sink:
15674 //    dst = t3
15675 //    ...
15676 MachineBasicBlock *
15677 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15678                                        MachineBasicBlock *MBB) const {
15679   MachineFunction *MF = MBB->getParent();
15680   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15681   DebugLoc DL = MI->getDebugLoc();
15682
15683   MachineRegisterInfo &MRI = MF->getRegInfo();
15684
15685   const BasicBlock *BB = MBB->getBasicBlock();
15686   MachineFunction::iterator I = MBB;
15687   ++I;
15688
15689   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15690          "Unexpected number of operands");
15691
15692   assert(MI->hasOneMemOperand() &&
15693          "Expected atomic-load-op to have one memoperand");
15694
15695   // Memory Reference
15696   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15697   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15698
15699   unsigned DstReg, SrcReg;
15700   unsigned MemOpndSlot;
15701
15702   unsigned CurOp = 0;
15703
15704   DstReg = MI->getOperand(CurOp++).getReg();
15705   MemOpndSlot = CurOp;
15706   CurOp += X86::AddrNumOperands;
15707   SrcReg = MI->getOperand(CurOp++).getReg();
15708
15709   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15710   MVT::SimpleValueType VT = *RC->vt_begin();
15711   unsigned t1 = MRI.createVirtualRegister(RC);
15712   unsigned t2 = MRI.createVirtualRegister(RC);
15713   unsigned t3 = MRI.createVirtualRegister(RC);
15714   unsigned t4 = MRI.createVirtualRegister(RC);
15715   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15716
15717   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15718   unsigned LOADOpc = getLoadOpcode(VT);
15719
15720   // For the atomic load-arith operator, we generate
15721   //
15722   //  thisMBB:
15723   //    t1 = LOAD [MI.addr]
15724   //  mainMBB:
15725   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15726   //    t1 = OP MI.val, EAX
15727   //    EAX = t4
15728   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15729   //    t3 = EAX
15730   //    JNE mainMBB
15731   //  sinkMBB:
15732   //    dst = t3
15733
15734   MachineBasicBlock *thisMBB = MBB;
15735   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15736   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15737   MF->insert(I, mainMBB);
15738   MF->insert(I, sinkMBB);
15739
15740   MachineInstrBuilder MIB;
15741
15742   // Transfer the remainder of BB and its successor edges to sinkMBB.
15743   sinkMBB->splice(sinkMBB->begin(), MBB,
15744                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15745   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15746
15747   // thisMBB:
15748   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15749   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15750     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15751     if (NewMO.isReg())
15752       NewMO.setIsKill(false);
15753     MIB.addOperand(NewMO);
15754   }
15755   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15756     unsigned flags = (*MMOI)->getFlags();
15757     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15758     MachineMemOperand *MMO =
15759       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15760                                (*MMOI)->getSize(),
15761                                (*MMOI)->getBaseAlignment(),
15762                                (*MMOI)->getTBAAInfo(),
15763                                (*MMOI)->getRanges());
15764     MIB.addMemOperand(MMO);
15765   }
15766
15767   thisMBB->addSuccessor(mainMBB);
15768
15769   // mainMBB:
15770   MachineBasicBlock *origMainMBB = mainMBB;
15771
15772   // Add a PHI.
15773   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15774                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15775
15776   unsigned Opc = MI->getOpcode();
15777   switch (Opc) {
15778   default:
15779     llvm_unreachable("Unhandled atomic-load-op opcode!");
15780   case X86::ATOMAND8:
15781   case X86::ATOMAND16:
15782   case X86::ATOMAND32:
15783   case X86::ATOMAND64:
15784   case X86::ATOMOR8:
15785   case X86::ATOMOR16:
15786   case X86::ATOMOR32:
15787   case X86::ATOMOR64:
15788   case X86::ATOMXOR8:
15789   case X86::ATOMXOR16:
15790   case X86::ATOMXOR32:
15791   case X86::ATOMXOR64: {
15792     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15793     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15794       .addReg(t4);
15795     break;
15796   }
15797   case X86::ATOMNAND8:
15798   case X86::ATOMNAND16:
15799   case X86::ATOMNAND32:
15800   case X86::ATOMNAND64: {
15801     unsigned Tmp = MRI.createVirtualRegister(RC);
15802     unsigned NOTOpc;
15803     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15804     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15805       .addReg(t4);
15806     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15807     break;
15808   }
15809   case X86::ATOMMAX8:
15810   case X86::ATOMMAX16:
15811   case X86::ATOMMAX32:
15812   case X86::ATOMMAX64:
15813   case X86::ATOMMIN8:
15814   case X86::ATOMMIN16:
15815   case X86::ATOMMIN32:
15816   case X86::ATOMMIN64:
15817   case X86::ATOMUMAX8:
15818   case X86::ATOMUMAX16:
15819   case X86::ATOMUMAX32:
15820   case X86::ATOMUMAX64:
15821   case X86::ATOMUMIN8:
15822   case X86::ATOMUMIN16:
15823   case X86::ATOMUMIN32:
15824   case X86::ATOMUMIN64: {
15825     unsigned CMPOpc;
15826     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15827
15828     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15829       .addReg(SrcReg)
15830       .addReg(t4);
15831
15832     if (Subtarget->hasCMov()) {
15833       if (VT != MVT::i8) {
15834         // Native support
15835         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15836           .addReg(SrcReg)
15837           .addReg(t4);
15838       } else {
15839         // Promote i8 to i32 to use CMOV32
15840         const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
15841         const TargetRegisterClass *RC32 =
15842           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15843         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15844         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15845         unsigned Tmp = MRI.createVirtualRegister(RC32);
15846
15847         unsigned Undef = MRI.createVirtualRegister(RC32);
15848         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15849
15850         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15851           .addReg(Undef)
15852           .addReg(SrcReg)
15853           .addImm(X86::sub_8bit);
15854         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15855           .addReg(Undef)
15856           .addReg(t4)
15857           .addImm(X86::sub_8bit);
15858
15859         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15860           .addReg(SrcReg32)
15861           .addReg(AccReg32);
15862
15863         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15864           .addReg(Tmp, 0, X86::sub_8bit);
15865       }
15866     } else {
15867       // Use pseudo select and lower them.
15868       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15869              "Invalid atomic-load-op transformation!");
15870       unsigned SelOpc = getPseudoCMOVOpc(VT);
15871       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15872       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15873       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15874               .addReg(SrcReg).addReg(t4)
15875               .addImm(CC);
15876       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15877       // Replace the original PHI node as mainMBB is changed after CMOV
15878       // lowering.
15879       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15880         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15881       Phi->eraseFromParent();
15882     }
15883     break;
15884   }
15885   }
15886
15887   // Copy PhyReg back from virtual register.
15888   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15889     .addReg(t4);
15890
15891   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15892   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15893     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15894     if (NewMO.isReg())
15895       NewMO.setIsKill(false);
15896     MIB.addOperand(NewMO);
15897   }
15898   MIB.addReg(t2);
15899   MIB.setMemRefs(MMOBegin, MMOEnd);
15900
15901   // Copy PhyReg back to virtual register.
15902   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15903     .addReg(PhyReg);
15904
15905   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15906
15907   mainMBB->addSuccessor(origMainMBB);
15908   mainMBB->addSuccessor(sinkMBB);
15909
15910   // sinkMBB:
15911   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15912           TII->get(TargetOpcode::COPY), DstReg)
15913     .addReg(t3);
15914
15915   MI->eraseFromParent();
15916   return sinkMBB;
15917 }
15918
15919 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15920 // instructions. They will be translated into a spin-loop or compare-exchange
15921 // loop from
15922 //
15923 //    ...
15924 //    dst = atomic-fetch-op MI.addr, MI.val
15925 //    ...
15926 //
15927 // to
15928 //
15929 //    ...
15930 //    t1L = LOAD [MI.addr + 0]
15931 //    t1H = LOAD [MI.addr + 4]
15932 // loop:
15933 //    t4L = phi(t1L, t3L / loop)
15934 //    t4H = phi(t1H, t3H / loop)
15935 //    t2L = OP MI.val.lo, t4L
15936 //    t2H = OP MI.val.hi, t4H
15937 //    EAX = t4L
15938 //    EDX = t4H
15939 //    EBX = t2L
15940 //    ECX = t2H
15941 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15942 //    t3L = EAX
15943 //    t3H = EDX
15944 //    JNE loop
15945 // sink:
15946 //    dstL = t3L
15947 //    dstH = t3H
15948 //    ...
15949 MachineBasicBlock *
15950 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15951                                            MachineBasicBlock *MBB) const {
15952   MachineFunction *MF = MBB->getParent();
15953   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15954   DebugLoc DL = MI->getDebugLoc();
15955
15956   MachineRegisterInfo &MRI = MF->getRegInfo();
15957
15958   const BasicBlock *BB = MBB->getBasicBlock();
15959   MachineFunction::iterator I = MBB;
15960   ++I;
15961
15962   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15963          "Unexpected number of operands");
15964
15965   assert(MI->hasOneMemOperand() &&
15966          "Expected atomic-load-op32 to have one memoperand");
15967
15968   // Memory Reference
15969   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15970   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15971
15972   unsigned DstLoReg, DstHiReg;
15973   unsigned SrcLoReg, SrcHiReg;
15974   unsigned MemOpndSlot;
15975
15976   unsigned CurOp = 0;
15977
15978   DstLoReg = MI->getOperand(CurOp++).getReg();
15979   DstHiReg = MI->getOperand(CurOp++).getReg();
15980   MemOpndSlot = CurOp;
15981   CurOp += X86::AddrNumOperands;
15982   SrcLoReg = MI->getOperand(CurOp++).getReg();
15983   SrcHiReg = MI->getOperand(CurOp++).getReg();
15984
15985   const TargetRegisterClass *RC = &X86::GR32RegClass;
15986   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15987
15988   unsigned t1L = MRI.createVirtualRegister(RC);
15989   unsigned t1H = MRI.createVirtualRegister(RC);
15990   unsigned t2L = MRI.createVirtualRegister(RC);
15991   unsigned t2H = MRI.createVirtualRegister(RC);
15992   unsigned t3L = MRI.createVirtualRegister(RC);
15993   unsigned t3H = MRI.createVirtualRegister(RC);
15994   unsigned t4L = MRI.createVirtualRegister(RC);
15995   unsigned t4H = MRI.createVirtualRegister(RC);
15996
15997   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15998   unsigned LOADOpc = X86::MOV32rm;
15999
16000   // For the atomic load-arith operator, we generate
16001   //
16002   //  thisMBB:
16003   //    t1L = LOAD [MI.addr + 0]
16004   //    t1H = LOAD [MI.addr + 4]
16005   //  mainMBB:
16006   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
16007   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
16008   //    t2L = OP MI.val.lo, t4L
16009   //    t2H = OP MI.val.hi, t4H
16010   //    EBX = t2L
16011   //    ECX = t2H
16012   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16013   //    t3L = EAX
16014   //    t3H = EDX
16015   //    JNE loop
16016   //  sinkMBB:
16017   //    dstL = t3L
16018   //    dstH = t3H
16019
16020   MachineBasicBlock *thisMBB = MBB;
16021   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16022   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16023   MF->insert(I, mainMBB);
16024   MF->insert(I, sinkMBB);
16025
16026   MachineInstrBuilder MIB;
16027
16028   // Transfer the remainder of BB and its successor edges to sinkMBB.
16029   sinkMBB->splice(sinkMBB->begin(), MBB,
16030                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16031   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16032
16033   // thisMBB:
16034   // Lo
16035   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
16036   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16037     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16038     if (NewMO.isReg())
16039       NewMO.setIsKill(false);
16040     MIB.addOperand(NewMO);
16041   }
16042   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16043     unsigned flags = (*MMOI)->getFlags();
16044     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16045     MachineMemOperand *MMO =
16046       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16047                                (*MMOI)->getSize(),
16048                                (*MMOI)->getBaseAlignment(),
16049                                (*MMOI)->getTBAAInfo(),
16050                                (*MMOI)->getRanges());
16051     MIB.addMemOperand(MMO);
16052   };
16053   MachineInstr *LowMI = MIB;
16054
16055   // Hi
16056   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
16057   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16058     if (i == X86::AddrDisp) {
16059       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
16060     } else {
16061       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16062       if (NewMO.isReg())
16063         NewMO.setIsKill(false);
16064       MIB.addOperand(NewMO);
16065     }
16066   }
16067   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
16068
16069   thisMBB->addSuccessor(mainMBB);
16070
16071   // mainMBB:
16072   MachineBasicBlock *origMainMBB = mainMBB;
16073
16074   // Add PHIs.
16075   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
16076                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16077   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
16078                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16079
16080   unsigned Opc = MI->getOpcode();
16081   switch (Opc) {
16082   default:
16083     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
16084   case X86::ATOMAND6432:
16085   case X86::ATOMOR6432:
16086   case X86::ATOMXOR6432:
16087   case X86::ATOMADD6432:
16088   case X86::ATOMSUB6432: {
16089     unsigned HiOpc;
16090     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16091     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
16092       .addReg(SrcLoReg);
16093     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
16094       .addReg(SrcHiReg);
16095     break;
16096   }
16097   case X86::ATOMNAND6432: {
16098     unsigned HiOpc, NOTOpc;
16099     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
16100     unsigned TmpL = MRI.createVirtualRegister(RC);
16101     unsigned TmpH = MRI.createVirtualRegister(RC);
16102     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16103       .addReg(t4L);
16104     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16105       .addReg(t4H);
16106     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16107     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16108     break;
16109   }
16110   case X86::ATOMMAX6432:
16111   case X86::ATOMMIN6432:
16112   case X86::ATOMUMAX6432:
16113   case X86::ATOMUMIN6432: {
16114     unsigned HiOpc;
16115     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16116     unsigned cL = MRI.createVirtualRegister(RC8);
16117     unsigned cH = MRI.createVirtualRegister(RC8);
16118     unsigned cL32 = MRI.createVirtualRegister(RC);
16119     unsigned cH32 = MRI.createVirtualRegister(RC);
16120     unsigned cc = MRI.createVirtualRegister(RC);
16121     // cl := cmp src_lo, lo
16122     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16123       .addReg(SrcLoReg).addReg(t4L);
16124     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16125     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16126     // ch := cmp src_hi, hi
16127     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16128       .addReg(SrcHiReg).addReg(t4H);
16129     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16130     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16131     // cc := if (src_hi == hi) ? cl : ch;
16132     if (Subtarget->hasCMov()) {
16133       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16134         .addReg(cH32).addReg(cL32);
16135     } else {
16136       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16137               .addReg(cH32).addReg(cL32)
16138               .addImm(X86::COND_E);
16139       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16140     }
16141     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16142     if (Subtarget->hasCMov()) {
16143       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16144         .addReg(SrcLoReg).addReg(t4L);
16145       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16146         .addReg(SrcHiReg).addReg(t4H);
16147     } else {
16148       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16149               .addReg(SrcLoReg).addReg(t4L)
16150               .addImm(X86::COND_NE);
16151       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16152       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16153       // 2nd CMOV lowering.
16154       mainMBB->addLiveIn(X86::EFLAGS);
16155       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16156               .addReg(SrcHiReg).addReg(t4H)
16157               .addImm(X86::COND_NE);
16158       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16159       // Replace the original PHI node as mainMBB is changed after CMOV
16160       // lowering.
16161       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16162         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16163       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16164         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16165       PhiL->eraseFromParent();
16166       PhiH->eraseFromParent();
16167     }
16168     break;
16169   }
16170   case X86::ATOMSWAP6432: {
16171     unsigned HiOpc;
16172     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16173     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16174     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16175     break;
16176   }
16177   }
16178
16179   // Copy EDX:EAX back from HiReg:LoReg
16180   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16181   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16182   // Copy ECX:EBX from t1H:t1L
16183   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16184   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16185
16186   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16187   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16188     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16189     if (NewMO.isReg())
16190       NewMO.setIsKill(false);
16191     MIB.addOperand(NewMO);
16192   }
16193   MIB.setMemRefs(MMOBegin, MMOEnd);
16194
16195   // Copy EDX:EAX back to t3H:t3L
16196   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16197   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16198
16199   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16200
16201   mainMBB->addSuccessor(origMainMBB);
16202   mainMBB->addSuccessor(sinkMBB);
16203
16204   // sinkMBB:
16205   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16206           TII->get(TargetOpcode::COPY), DstLoReg)
16207     .addReg(t3L);
16208   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16209           TII->get(TargetOpcode::COPY), DstHiReg)
16210     .addReg(t3H);
16211
16212   MI->eraseFromParent();
16213   return sinkMBB;
16214 }
16215
16216 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16217 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16218 // in the .td file.
16219 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16220                                        const TargetInstrInfo *TII) {
16221   unsigned Opc;
16222   switch (MI->getOpcode()) {
16223   default: llvm_unreachable("illegal opcode!");
16224   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16225   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16226   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16227   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16228   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16229   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16230   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16231   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16232   }
16233
16234   DebugLoc dl = MI->getDebugLoc();
16235   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16236
16237   unsigned NumArgs = MI->getNumOperands();
16238   for (unsigned i = 1; i < NumArgs; ++i) {
16239     MachineOperand &Op = MI->getOperand(i);
16240     if (!(Op.isReg() && Op.isImplicit()))
16241       MIB.addOperand(Op);
16242   }
16243   if (MI->hasOneMemOperand())
16244     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16245
16246   BuildMI(*BB, MI, dl,
16247     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16248     .addReg(X86::XMM0);
16249
16250   MI->eraseFromParent();
16251   return BB;
16252 }
16253
16254 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16255 // defs in an instruction pattern
16256 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16257                                        const TargetInstrInfo *TII) {
16258   unsigned Opc;
16259   switch (MI->getOpcode()) {
16260   default: llvm_unreachable("illegal opcode!");
16261   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16262   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16263   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16264   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16265   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16266   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16267   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16268   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16269   }
16270
16271   DebugLoc dl = MI->getDebugLoc();
16272   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16273
16274   unsigned NumArgs = MI->getNumOperands(); // remove the results
16275   for (unsigned i = 1; i < NumArgs; ++i) {
16276     MachineOperand &Op = MI->getOperand(i);
16277     if (!(Op.isReg() && Op.isImplicit()))
16278       MIB.addOperand(Op);
16279   }
16280   if (MI->hasOneMemOperand())
16281     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16282
16283   BuildMI(*BB, MI, dl,
16284     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16285     .addReg(X86::ECX);
16286
16287   MI->eraseFromParent();
16288   return BB;
16289 }
16290
16291 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16292                                        const TargetInstrInfo *TII,
16293                                        const X86Subtarget* Subtarget) {
16294   DebugLoc dl = MI->getDebugLoc();
16295
16296   // Address into RAX/EAX, other two args into ECX, EDX.
16297   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16298   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16299   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16300   for (int i = 0; i < X86::AddrNumOperands; ++i)
16301     MIB.addOperand(MI->getOperand(i));
16302
16303   unsigned ValOps = X86::AddrNumOperands;
16304   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16305     .addReg(MI->getOperand(ValOps).getReg());
16306   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16307     .addReg(MI->getOperand(ValOps+1).getReg());
16308
16309   // The instruction doesn't actually take any operands though.
16310   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16311
16312   MI->eraseFromParent(); // The pseudo is gone now.
16313   return BB;
16314 }
16315
16316 MachineBasicBlock *
16317 X86TargetLowering::EmitVAARG64WithCustomInserter(
16318                    MachineInstr *MI,
16319                    MachineBasicBlock *MBB) const {
16320   // Emit va_arg instruction on X86-64.
16321
16322   // Operands to this pseudo-instruction:
16323   // 0  ) Output        : destination address (reg)
16324   // 1-5) Input         : va_list address (addr, i64mem)
16325   // 6  ) ArgSize       : Size (in bytes) of vararg type
16326   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16327   // 8  ) Align         : Alignment of type
16328   // 9  ) EFLAGS (implicit-def)
16329
16330   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16331   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16332
16333   unsigned DestReg = MI->getOperand(0).getReg();
16334   MachineOperand &Base = MI->getOperand(1);
16335   MachineOperand &Scale = MI->getOperand(2);
16336   MachineOperand &Index = MI->getOperand(3);
16337   MachineOperand &Disp = MI->getOperand(4);
16338   MachineOperand &Segment = MI->getOperand(5);
16339   unsigned ArgSize = MI->getOperand(6).getImm();
16340   unsigned ArgMode = MI->getOperand(7).getImm();
16341   unsigned Align = MI->getOperand(8).getImm();
16342
16343   // Memory Reference
16344   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16345   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16346   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16347
16348   // Machine Information
16349   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16350   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16351   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16352   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16353   DebugLoc DL = MI->getDebugLoc();
16354
16355   // struct va_list {
16356   //   i32   gp_offset
16357   //   i32   fp_offset
16358   //   i64   overflow_area (address)
16359   //   i64   reg_save_area (address)
16360   // }
16361   // sizeof(va_list) = 24
16362   // alignment(va_list) = 8
16363
16364   unsigned TotalNumIntRegs = 6;
16365   unsigned TotalNumXMMRegs = 8;
16366   bool UseGPOffset = (ArgMode == 1);
16367   bool UseFPOffset = (ArgMode == 2);
16368   unsigned MaxOffset = TotalNumIntRegs * 8 +
16369                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16370
16371   /* Align ArgSize to a multiple of 8 */
16372   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16373   bool NeedsAlign = (Align > 8);
16374
16375   MachineBasicBlock *thisMBB = MBB;
16376   MachineBasicBlock *overflowMBB;
16377   MachineBasicBlock *offsetMBB;
16378   MachineBasicBlock *endMBB;
16379
16380   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16381   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16382   unsigned OffsetReg = 0;
16383
16384   if (!UseGPOffset && !UseFPOffset) {
16385     // If we only pull from the overflow region, we don't create a branch.
16386     // We don't need to alter control flow.
16387     OffsetDestReg = 0; // unused
16388     OverflowDestReg = DestReg;
16389
16390     offsetMBB = nullptr;
16391     overflowMBB = thisMBB;
16392     endMBB = thisMBB;
16393   } else {
16394     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16395     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16396     // If not, pull from overflow_area. (branch to overflowMBB)
16397     //
16398     //       thisMBB
16399     //         |     .
16400     //         |        .
16401     //     offsetMBB   overflowMBB
16402     //         |        .
16403     //         |     .
16404     //        endMBB
16405
16406     // Registers for the PHI in endMBB
16407     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16408     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16409
16410     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16411     MachineFunction *MF = MBB->getParent();
16412     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16413     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16414     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16415
16416     MachineFunction::iterator MBBIter = MBB;
16417     ++MBBIter;
16418
16419     // Insert the new basic blocks
16420     MF->insert(MBBIter, offsetMBB);
16421     MF->insert(MBBIter, overflowMBB);
16422     MF->insert(MBBIter, endMBB);
16423
16424     // Transfer the remainder of MBB and its successor edges to endMBB.
16425     endMBB->splice(endMBB->begin(), thisMBB,
16426                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16427     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16428
16429     // Make offsetMBB and overflowMBB successors of thisMBB
16430     thisMBB->addSuccessor(offsetMBB);
16431     thisMBB->addSuccessor(overflowMBB);
16432
16433     // endMBB is a successor of both offsetMBB and overflowMBB
16434     offsetMBB->addSuccessor(endMBB);
16435     overflowMBB->addSuccessor(endMBB);
16436
16437     // Load the offset value into a register
16438     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16439     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16440       .addOperand(Base)
16441       .addOperand(Scale)
16442       .addOperand(Index)
16443       .addDisp(Disp, UseFPOffset ? 4 : 0)
16444       .addOperand(Segment)
16445       .setMemRefs(MMOBegin, MMOEnd);
16446
16447     // Check if there is enough room left to pull this argument.
16448     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16449       .addReg(OffsetReg)
16450       .addImm(MaxOffset + 8 - ArgSizeA8);
16451
16452     // Branch to "overflowMBB" if offset >= max
16453     // Fall through to "offsetMBB" otherwise
16454     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16455       .addMBB(overflowMBB);
16456   }
16457
16458   // In offsetMBB, emit code to use the reg_save_area.
16459   if (offsetMBB) {
16460     assert(OffsetReg != 0);
16461
16462     // Read the reg_save_area address.
16463     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16464     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16465       .addOperand(Base)
16466       .addOperand(Scale)
16467       .addOperand(Index)
16468       .addDisp(Disp, 16)
16469       .addOperand(Segment)
16470       .setMemRefs(MMOBegin, MMOEnd);
16471
16472     // Zero-extend the offset
16473     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16474       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16475         .addImm(0)
16476         .addReg(OffsetReg)
16477         .addImm(X86::sub_32bit);
16478
16479     // Add the offset to the reg_save_area to get the final address.
16480     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16481       .addReg(OffsetReg64)
16482       .addReg(RegSaveReg);
16483
16484     // Compute the offset for the next argument
16485     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16486     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16487       .addReg(OffsetReg)
16488       .addImm(UseFPOffset ? 16 : 8);
16489
16490     // Store it back into the va_list.
16491     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16492       .addOperand(Base)
16493       .addOperand(Scale)
16494       .addOperand(Index)
16495       .addDisp(Disp, UseFPOffset ? 4 : 0)
16496       .addOperand(Segment)
16497       .addReg(NextOffsetReg)
16498       .setMemRefs(MMOBegin, MMOEnd);
16499
16500     // Jump to endMBB
16501     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16502       .addMBB(endMBB);
16503   }
16504
16505   //
16506   // Emit code to use overflow area
16507   //
16508
16509   // Load the overflow_area address into a register.
16510   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16511   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16512     .addOperand(Base)
16513     .addOperand(Scale)
16514     .addOperand(Index)
16515     .addDisp(Disp, 8)
16516     .addOperand(Segment)
16517     .setMemRefs(MMOBegin, MMOEnd);
16518
16519   // If we need to align it, do so. Otherwise, just copy the address
16520   // to OverflowDestReg.
16521   if (NeedsAlign) {
16522     // Align the overflow address
16523     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16524     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16525
16526     // aligned_addr = (addr + (align-1)) & ~(align-1)
16527     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16528       .addReg(OverflowAddrReg)
16529       .addImm(Align-1);
16530
16531     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16532       .addReg(TmpReg)
16533       .addImm(~(uint64_t)(Align-1));
16534   } else {
16535     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16536       .addReg(OverflowAddrReg);
16537   }
16538
16539   // Compute the next overflow address after this argument.
16540   // (the overflow address should be kept 8-byte aligned)
16541   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16542   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16543     .addReg(OverflowDestReg)
16544     .addImm(ArgSizeA8);
16545
16546   // Store the new overflow address.
16547   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16548     .addOperand(Base)
16549     .addOperand(Scale)
16550     .addOperand(Index)
16551     .addDisp(Disp, 8)
16552     .addOperand(Segment)
16553     .addReg(NextAddrReg)
16554     .setMemRefs(MMOBegin, MMOEnd);
16555
16556   // If we branched, emit the PHI to the front of endMBB.
16557   if (offsetMBB) {
16558     BuildMI(*endMBB, endMBB->begin(), DL,
16559             TII->get(X86::PHI), DestReg)
16560       .addReg(OffsetDestReg).addMBB(offsetMBB)
16561       .addReg(OverflowDestReg).addMBB(overflowMBB);
16562   }
16563
16564   // Erase the pseudo instruction
16565   MI->eraseFromParent();
16566
16567   return endMBB;
16568 }
16569
16570 MachineBasicBlock *
16571 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16572                                                  MachineInstr *MI,
16573                                                  MachineBasicBlock *MBB) const {
16574   // Emit code to save XMM registers to the stack. The ABI says that the
16575   // number of registers to save is given in %al, so it's theoretically
16576   // possible to do an indirect jump trick to avoid saving all of them,
16577   // however this code takes a simpler approach and just executes all
16578   // of the stores if %al is non-zero. It's less code, and it's probably
16579   // easier on the hardware branch predictor, and stores aren't all that
16580   // expensive anyway.
16581
16582   // Create the new basic blocks. One block contains all the XMM stores,
16583   // and one block is the final destination regardless of whether any
16584   // stores were performed.
16585   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16586   MachineFunction *F = MBB->getParent();
16587   MachineFunction::iterator MBBIter = MBB;
16588   ++MBBIter;
16589   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16590   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16591   F->insert(MBBIter, XMMSaveMBB);
16592   F->insert(MBBIter, EndMBB);
16593
16594   // Transfer the remainder of MBB and its successor edges to EndMBB.
16595   EndMBB->splice(EndMBB->begin(), MBB,
16596                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16597   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16598
16599   // The original block will now fall through to the XMM save block.
16600   MBB->addSuccessor(XMMSaveMBB);
16601   // The XMMSaveMBB will fall through to the end block.
16602   XMMSaveMBB->addSuccessor(EndMBB);
16603
16604   // Now add the instructions.
16605   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16606   DebugLoc DL = MI->getDebugLoc();
16607
16608   unsigned CountReg = MI->getOperand(0).getReg();
16609   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16610   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16611
16612   if (!Subtarget->isTargetWin64()) {
16613     // If %al is 0, branch around the XMM save block.
16614     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16615     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16616     MBB->addSuccessor(EndMBB);
16617   }
16618
16619   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16620   // that was just emitted, but clearly shouldn't be "saved".
16621   assert((MI->getNumOperands() <= 3 ||
16622           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16623           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16624          && "Expected last argument to be EFLAGS");
16625   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16626   // In the XMM save block, save all the XMM argument registers.
16627   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16628     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16629     MachineMemOperand *MMO =
16630       F->getMachineMemOperand(
16631           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16632         MachineMemOperand::MOStore,
16633         /*Size=*/16, /*Align=*/16);
16634     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16635       .addFrameIndex(RegSaveFrameIndex)
16636       .addImm(/*Scale=*/1)
16637       .addReg(/*IndexReg=*/0)
16638       .addImm(/*Disp=*/Offset)
16639       .addReg(/*Segment=*/0)
16640       .addReg(MI->getOperand(i).getReg())
16641       .addMemOperand(MMO);
16642   }
16643
16644   MI->eraseFromParent();   // The pseudo instruction is gone now.
16645
16646   return EndMBB;
16647 }
16648
16649 // The EFLAGS operand of SelectItr might be missing a kill marker
16650 // because there were multiple uses of EFLAGS, and ISel didn't know
16651 // which to mark. Figure out whether SelectItr should have had a
16652 // kill marker, and set it if it should. Returns the correct kill
16653 // marker value.
16654 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16655                                      MachineBasicBlock* BB,
16656                                      const TargetRegisterInfo* TRI) {
16657   // Scan forward through BB for a use/def of EFLAGS.
16658   MachineBasicBlock::iterator miI(std::next(SelectItr));
16659   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16660     const MachineInstr& mi = *miI;
16661     if (mi.readsRegister(X86::EFLAGS))
16662       return false;
16663     if (mi.definesRegister(X86::EFLAGS))
16664       break; // Should have kill-flag - update below.
16665   }
16666
16667   // If we hit the end of the block, check whether EFLAGS is live into a
16668   // successor.
16669   if (miI == BB->end()) {
16670     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16671                                           sEnd = BB->succ_end();
16672          sItr != sEnd; ++sItr) {
16673       MachineBasicBlock* succ = *sItr;
16674       if (succ->isLiveIn(X86::EFLAGS))
16675         return false;
16676     }
16677   }
16678
16679   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16680   // out. SelectMI should have a kill flag on EFLAGS.
16681   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16682   return true;
16683 }
16684
16685 MachineBasicBlock *
16686 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16687                                      MachineBasicBlock *BB) const {
16688   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16689   DebugLoc DL = MI->getDebugLoc();
16690
16691   // To "insert" a SELECT_CC instruction, we actually have to insert the
16692   // diamond control-flow pattern.  The incoming instruction knows the
16693   // destination vreg to set, the condition code register to branch on, the
16694   // true/false values to select between, and a branch opcode to use.
16695   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16696   MachineFunction::iterator It = BB;
16697   ++It;
16698
16699   //  thisMBB:
16700   //  ...
16701   //   TrueVal = ...
16702   //   cmpTY ccX, r1, r2
16703   //   bCC copy1MBB
16704   //   fallthrough --> copy0MBB
16705   MachineBasicBlock *thisMBB = BB;
16706   MachineFunction *F = BB->getParent();
16707   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16708   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16709   F->insert(It, copy0MBB);
16710   F->insert(It, sinkMBB);
16711
16712   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16713   // live into the sink and copy blocks.
16714   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16715   if (!MI->killsRegister(X86::EFLAGS) &&
16716       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16717     copy0MBB->addLiveIn(X86::EFLAGS);
16718     sinkMBB->addLiveIn(X86::EFLAGS);
16719   }
16720
16721   // Transfer the remainder of BB and its successor edges to sinkMBB.
16722   sinkMBB->splice(sinkMBB->begin(), BB,
16723                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16724   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16725
16726   // Add the true and fallthrough blocks as its successors.
16727   BB->addSuccessor(copy0MBB);
16728   BB->addSuccessor(sinkMBB);
16729
16730   // Create the conditional branch instruction.
16731   unsigned Opc =
16732     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16733   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16734
16735   //  copy0MBB:
16736   //   %FalseValue = ...
16737   //   # fallthrough to sinkMBB
16738   copy0MBB->addSuccessor(sinkMBB);
16739
16740   //  sinkMBB:
16741   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16742   //  ...
16743   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16744           TII->get(X86::PHI), MI->getOperand(0).getReg())
16745     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16746     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16747
16748   MI->eraseFromParent();   // The pseudo instruction is gone now.
16749   return sinkMBB;
16750 }
16751
16752 MachineBasicBlock *
16753 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16754                                         bool Is64Bit) const {
16755   MachineFunction *MF = BB->getParent();
16756   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16757   DebugLoc DL = MI->getDebugLoc();
16758   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16759
16760   assert(MF->shouldSplitStack());
16761
16762   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16763   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16764
16765   // BB:
16766   //  ... [Till the alloca]
16767   // If stacklet is not large enough, jump to mallocMBB
16768   //
16769   // bumpMBB:
16770   //  Allocate by subtracting from RSP
16771   //  Jump to continueMBB
16772   //
16773   // mallocMBB:
16774   //  Allocate by call to runtime
16775   //
16776   // continueMBB:
16777   //  ...
16778   //  [rest of original BB]
16779   //
16780
16781   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16782   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16783   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16784
16785   MachineRegisterInfo &MRI = MF->getRegInfo();
16786   const TargetRegisterClass *AddrRegClass =
16787     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16788
16789   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16790     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16791     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16792     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16793     sizeVReg = MI->getOperand(1).getReg(),
16794     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16795
16796   MachineFunction::iterator MBBIter = BB;
16797   ++MBBIter;
16798
16799   MF->insert(MBBIter, bumpMBB);
16800   MF->insert(MBBIter, mallocMBB);
16801   MF->insert(MBBIter, continueMBB);
16802
16803   continueMBB->splice(continueMBB->begin(), BB,
16804                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16805   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16806
16807   // Add code to the main basic block to check if the stack limit has been hit,
16808   // and if so, jump to mallocMBB otherwise to bumpMBB.
16809   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16810   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16811     .addReg(tmpSPVReg).addReg(sizeVReg);
16812   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16813     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16814     .addReg(SPLimitVReg);
16815   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16816
16817   // bumpMBB simply decreases the stack pointer, since we know the current
16818   // stacklet has enough space.
16819   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16820     .addReg(SPLimitVReg);
16821   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16822     .addReg(SPLimitVReg);
16823   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16824
16825   // Calls into a routine in libgcc to allocate more space from the heap.
16826   const uint32_t *RegMask =
16827     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16828   if (Is64Bit) {
16829     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16830       .addReg(sizeVReg);
16831     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16832       .addExternalSymbol("__morestack_allocate_stack_space")
16833       .addRegMask(RegMask)
16834       .addReg(X86::RDI, RegState::Implicit)
16835       .addReg(X86::RAX, RegState::ImplicitDefine);
16836   } else {
16837     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16838       .addImm(12);
16839     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16840     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16841       .addExternalSymbol("__morestack_allocate_stack_space")
16842       .addRegMask(RegMask)
16843       .addReg(X86::EAX, RegState::ImplicitDefine);
16844   }
16845
16846   if (!Is64Bit)
16847     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16848       .addImm(16);
16849
16850   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16851     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16852   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16853
16854   // Set up the CFG correctly.
16855   BB->addSuccessor(bumpMBB);
16856   BB->addSuccessor(mallocMBB);
16857   mallocMBB->addSuccessor(continueMBB);
16858   bumpMBB->addSuccessor(continueMBB);
16859
16860   // Take care of the PHI nodes.
16861   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16862           MI->getOperand(0).getReg())
16863     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16864     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16865
16866   // Delete the original pseudo instruction.
16867   MI->eraseFromParent();
16868
16869   // And we're done.
16870   return continueMBB;
16871 }
16872
16873 MachineBasicBlock *
16874 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16875                                         MachineBasicBlock *BB) const {
16876   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16877   DebugLoc DL = MI->getDebugLoc();
16878
16879   assert(!Subtarget->isTargetMacho());
16880
16881   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16882   // non-trivial part is impdef of ESP.
16883
16884   if (Subtarget->isTargetWin64()) {
16885     if (Subtarget->isTargetCygMing()) {
16886       // ___chkstk(Mingw64):
16887       // Clobbers R10, R11, RAX and EFLAGS.
16888       // Updates RSP.
16889       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16890         .addExternalSymbol("___chkstk")
16891         .addReg(X86::RAX, RegState::Implicit)
16892         .addReg(X86::RSP, RegState::Implicit)
16893         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16894         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16895         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16896     } else {
16897       // __chkstk(MSVCRT): does not update stack pointer.
16898       // Clobbers R10, R11 and EFLAGS.
16899       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16900         .addExternalSymbol("__chkstk")
16901         .addReg(X86::RAX, RegState::Implicit)
16902         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16903       // RAX has the offset to be subtracted from RSP.
16904       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16905         .addReg(X86::RSP)
16906         .addReg(X86::RAX);
16907     }
16908   } else {
16909     const char *StackProbeSymbol =
16910       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16911
16912     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16913       .addExternalSymbol(StackProbeSymbol)
16914       .addReg(X86::EAX, RegState::Implicit)
16915       .addReg(X86::ESP, RegState::Implicit)
16916       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16917       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16918       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16919   }
16920
16921   MI->eraseFromParent();   // The pseudo instruction is gone now.
16922   return BB;
16923 }
16924
16925 MachineBasicBlock *
16926 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16927                                       MachineBasicBlock *BB) const {
16928   // This is pretty easy.  We're taking the value that we received from
16929   // our load from the relocation, sticking it in either RDI (x86-64)
16930   // or EAX and doing an indirect call.  The return value will then
16931   // be in the normal return register.
16932   MachineFunction *F = BB->getParent();
16933   const X86InstrInfo *TII
16934     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
16935   DebugLoc DL = MI->getDebugLoc();
16936
16937   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16938   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16939
16940   // Get a register mask for the lowered call.
16941   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16942   // proper register mask.
16943   const uint32_t *RegMask =
16944     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16945   if (Subtarget->is64Bit()) {
16946     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16947                                       TII->get(X86::MOV64rm), X86::RDI)
16948     .addReg(X86::RIP)
16949     .addImm(0).addReg(0)
16950     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16951                       MI->getOperand(3).getTargetFlags())
16952     .addReg(0);
16953     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16954     addDirectMem(MIB, X86::RDI);
16955     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16956   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
16957     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16958                                       TII->get(X86::MOV32rm), X86::EAX)
16959     .addReg(0)
16960     .addImm(0).addReg(0)
16961     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16962                       MI->getOperand(3).getTargetFlags())
16963     .addReg(0);
16964     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16965     addDirectMem(MIB, X86::EAX);
16966     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16967   } else {
16968     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16969                                       TII->get(X86::MOV32rm), X86::EAX)
16970     .addReg(TII->getGlobalBaseReg(F))
16971     .addImm(0).addReg(0)
16972     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16973                       MI->getOperand(3).getTargetFlags())
16974     .addReg(0);
16975     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16976     addDirectMem(MIB, X86::EAX);
16977     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16978   }
16979
16980   MI->eraseFromParent(); // The pseudo instruction is gone now.
16981   return BB;
16982 }
16983
16984 MachineBasicBlock *
16985 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16986                                     MachineBasicBlock *MBB) const {
16987   DebugLoc DL = MI->getDebugLoc();
16988   MachineFunction *MF = MBB->getParent();
16989   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16990   MachineRegisterInfo &MRI = MF->getRegInfo();
16991
16992   const BasicBlock *BB = MBB->getBasicBlock();
16993   MachineFunction::iterator I = MBB;
16994   ++I;
16995
16996   // Memory Reference
16997   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16998   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16999
17000   unsigned DstReg;
17001   unsigned MemOpndSlot = 0;
17002
17003   unsigned CurOp = 0;
17004
17005   DstReg = MI->getOperand(CurOp++).getReg();
17006   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17007   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17008   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17009   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17010
17011   MemOpndSlot = CurOp;
17012
17013   MVT PVT = getPointerTy();
17014   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17015          "Invalid Pointer Size!");
17016
17017   // For v = setjmp(buf), we generate
17018   //
17019   // thisMBB:
17020   //  buf[LabelOffset] = restoreMBB
17021   //  SjLjSetup restoreMBB
17022   //
17023   // mainMBB:
17024   //  v_main = 0
17025   //
17026   // sinkMBB:
17027   //  v = phi(main, restore)
17028   //
17029   // restoreMBB:
17030   //  v_restore = 1
17031
17032   MachineBasicBlock *thisMBB = MBB;
17033   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17034   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17035   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17036   MF->insert(I, mainMBB);
17037   MF->insert(I, sinkMBB);
17038   MF->push_back(restoreMBB);
17039
17040   MachineInstrBuilder MIB;
17041
17042   // Transfer the remainder of BB and its successor edges to sinkMBB.
17043   sinkMBB->splice(sinkMBB->begin(), MBB,
17044                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17045   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17046
17047   // thisMBB:
17048   unsigned PtrStoreOpc = 0;
17049   unsigned LabelReg = 0;
17050   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17051   Reloc::Model RM = MF->getTarget().getRelocationModel();
17052   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17053                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17054
17055   // Prepare IP either in reg or imm.
17056   if (!UseImmLabel) {
17057     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17058     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17059     LabelReg = MRI.createVirtualRegister(PtrRC);
17060     if (Subtarget->is64Bit()) {
17061       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17062               .addReg(X86::RIP)
17063               .addImm(0)
17064               .addReg(0)
17065               .addMBB(restoreMBB)
17066               .addReg(0);
17067     } else {
17068       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17069       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17070               .addReg(XII->getGlobalBaseReg(MF))
17071               .addImm(0)
17072               .addReg(0)
17073               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17074               .addReg(0);
17075     }
17076   } else
17077     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17078   // Store IP
17079   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17080   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17081     if (i == X86::AddrDisp)
17082       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17083     else
17084       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17085   }
17086   if (!UseImmLabel)
17087     MIB.addReg(LabelReg);
17088   else
17089     MIB.addMBB(restoreMBB);
17090   MIB.setMemRefs(MMOBegin, MMOEnd);
17091   // Setup
17092   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17093           .addMBB(restoreMBB);
17094
17095   const X86RegisterInfo *RegInfo =
17096     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17097   MIB.addRegMask(RegInfo->getNoPreservedMask());
17098   thisMBB->addSuccessor(mainMBB);
17099   thisMBB->addSuccessor(restoreMBB);
17100
17101   // mainMBB:
17102   //  EAX = 0
17103   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17104   mainMBB->addSuccessor(sinkMBB);
17105
17106   // sinkMBB:
17107   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17108           TII->get(X86::PHI), DstReg)
17109     .addReg(mainDstReg).addMBB(mainMBB)
17110     .addReg(restoreDstReg).addMBB(restoreMBB);
17111
17112   // restoreMBB:
17113   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17114   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17115   restoreMBB->addSuccessor(sinkMBB);
17116
17117   MI->eraseFromParent();
17118   return sinkMBB;
17119 }
17120
17121 MachineBasicBlock *
17122 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17123                                      MachineBasicBlock *MBB) const {
17124   DebugLoc DL = MI->getDebugLoc();
17125   MachineFunction *MF = MBB->getParent();
17126   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17127   MachineRegisterInfo &MRI = MF->getRegInfo();
17128
17129   // Memory Reference
17130   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17131   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17132
17133   MVT PVT = getPointerTy();
17134   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17135          "Invalid Pointer Size!");
17136
17137   const TargetRegisterClass *RC =
17138     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17139   unsigned Tmp = MRI.createVirtualRegister(RC);
17140   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17141   const X86RegisterInfo *RegInfo =
17142     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17143   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17144   unsigned SP = RegInfo->getStackRegister();
17145
17146   MachineInstrBuilder MIB;
17147
17148   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17149   const int64_t SPOffset = 2 * PVT.getStoreSize();
17150
17151   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17152   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17153
17154   // Reload FP
17155   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17156   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17157     MIB.addOperand(MI->getOperand(i));
17158   MIB.setMemRefs(MMOBegin, MMOEnd);
17159   // Reload IP
17160   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17161   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17162     if (i == X86::AddrDisp)
17163       MIB.addDisp(MI->getOperand(i), LabelOffset);
17164     else
17165       MIB.addOperand(MI->getOperand(i));
17166   }
17167   MIB.setMemRefs(MMOBegin, MMOEnd);
17168   // Reload SP
17169   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17170   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17171     if (i == X86::AddrDisp)
17172       MIB.addDisp(MI->getOperand(i), SPOffset);
17173     else
17174       MIB.addOperand(MI->getOperand(i));
17175   }
17176   MIB.setMemRefs(MMOBegin, MMOEnd);
17177   // Jump
17178   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17179
17180   MI->eraseFromParent();
17181   return MBB;
17182 }
17183
17184 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17185 // accumulator loops. Writing back to the accumulator allows the coalescer
17186 // to remove extra copies in the loop.   
17187 MachineBasicBlock *
17188 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17189                                  MachineBasicBlock *MBB) const {
17190   MachineOperand &AddendOp = MI->getOperand(3);
17191
17192   // Bail out early if the addend isn't a register - we can't switch these.
17193   if (!AddendOp.isReg())
17194     return MBB;
17195
17196   MachineFunction &MF = *MBB->getParent();
17197   MachineRegisterInfo &MRI = MF.getRegInfo();
17198
17199   // Check whether the addend is defined by a PHI:
17200   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17201   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17202   if (!AddendDef.isPHI())
17203     return MBB;
17204
17205   // Look for the following pattern:
17206   // loop:
17207   //   %addend = phi [%entry, 0], [%loop, %result]
17208   //   ...
17209   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17210
17211   // Replace with:
17212   //   loop:
17213   //   %addend = phi [%entry, 0], [%loop, %result]
17214   //   ...
17215   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17216
17217   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17218     assert(AddendDef.getOperand(i).isReg());
17219     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17220     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17221     if (&PHISrcInst == MI) {
17222       // Found a matching instruction.
17223       unsigned NewFMAOpc = 0;
17224       switch (MI->getOpcode()) {
17225         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17226         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17227         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17228         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17229         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17230         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17231         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17232         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17233         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17234         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17235         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17236         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17237         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17238         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17239         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17240         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17241         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17242         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17243         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17244         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17245         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17246         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17247         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17248         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17249         default: llvm_unreachable("Unrecognized FMA variant.");
17250       }
17251
17252       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17253       MachineInstrBuilder MIB =
17254         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17255         .addOperand(MI->getOperand(0))
17256         .addOperand(MI->getOperand(3))
17257         .addOperand(MI->getOperand(2))
17258         .addOperand(MI->getOperand(1));
17259       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17260       MI->eraseFromParent();
17261     }
17262   }
17263
17264   return MBB;
17265 }
17266
17267 MachineBasicBlock *
17268 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17269                                                MachineBasicBlock *BB) const {
17270   switch (MI->getOpcode()) {
17271   default: llvm_unreachable("Unexpected instr type to insert");
17272   case X86::TAILJMPd64:
17273   case X86::TAILJMPr64:
17274   case X86::TAILJMPm64:
17275     llvm_unreachable("TAILJMP64 would not be touched here.");
17276   case X86::TCRETURNdi64:
17277   case X86::TCRETURNri64:
17278   case X86::TCRETURNmi64:
17279     return BB;
17280   case X86::WIN_ALLOCA:
17281     return EmitLoweredWinAlloca(MI, BB);
17282   case X86::SEG_ALLOCA_32:
17283     return EmitLoweredSegAlloca(MI, BB, false);
17284   case X86::SEG_ALLOCA_64:
17285     return EmitLoweredSegAlloca(MI, BB, true);
17286   case X86::TLSCall_32:
17287   case X86::TLSCall_64:
17288     return EmitLoweredTLSCall(MI, BB);
17289   case X86::CMOV_GR8:
17290   case X86::CMOV_FR32:
17291   case X86::CMOV_FR64:
17292   case X86::CMOV_V4F32:
17293   case X86::CMOV_V2F64:
17294   case X86::CMOV_V2I64:
17295   case X86::CMOV_V8F32:
17296   case X86::CMOV_V4F64:
17297   case X86::CMOV_V4I64:
17298   case X86::CMOV_V16F32:
17299   case X86::CMOV_V8F64:
17300   case X86::CMOV_V8I64:
17301   case X86::CMOV_GR16:
17302   case X86::CMOV_GR32:
17303   case X86::CMOV_RFP32:
17304   case X86::CMOV_RFP64:
17305   case X86::CMOV_RFP80:
17306     return EmitLoweredSelect(MI, BB);
17307
17308   case X86::FP32_TO_INT16_IN_MEM:
17309   case X86::FP32_TO_INT32_IN_MEM:
17310   case X86::FP32_TO_INT64_IN_MEM:
17311   case X86::FP64_TO_INT16_IN_MEM:
17312   case X86::FP64_TO_INT32_IN_MEM:
17313   case X86::FP64_TO_INT64_IN_MEM:
17314   case X86::FP80_TO_INT16_IN_MEM:
17315   case X86::FP80_TO_INT32_IN_MEM:
17316   case X86::FP80_TO_INT64_IN_MEM: {
17317     MachineFunction *F = BB->getParent();
17318     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17319     DebugLoc DL = MI->getDebugLoc();
17320
17321     // Change the floating point control register to use "round towards zero"
17322     // mode when truncating to an integer value.
17323     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17324     addFrameReference(BuildMI(*BB, MI, DL,
17325                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17326
17327     // Load the old value of the high byte of the control word...
17328     unsigned OldCW =
17329       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17330     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17331                       CWFrameIdx);
17332
17333     // Set the high part to be round to zero...
17334     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17335       .addImm(0xC7F);
17336
17337     // Reload the modified control word now...
17338     addFrameReference(BuildMI(*BB, MI, DL,
17339                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17340
17341     // Restore the memory image of control word to original value
17342     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17343       .addReg(OldCW);
17344
17345     // Get the X86 opcode to use.
17346     unsigned Opc;
17347     switch (MI->getOpcode()) {
17348     default: llvm_unreachable("illegal opcode!");
17349     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17350     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17351     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17352     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17353     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17354     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17355     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17356     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17357     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17358     }
17359
17360     X86AddressMode AM;
17361     MachineOperand &Op = MI->getOperand(0);
17362     if (Op.isReg()) {
17363       AM.BaseType = X86AddressMode::RegBase;
17364       AM.Base.Reg = Op.getReg();
17365     } else {
17366       AM.BaseType = X86AddressMode::FrameIndexBase;
17367       AM.Base.FrameIndex = Op.getIndex();
17368     }
17369     Op = MI->getOperand(1);
17370     if (Op.isImm())
17371       AM.Scale = Op.getImm();
17372     Op = MI->getOperand(2);
17373     if (Op.isImm())
17374       AM.IndexReg = Op.getImm();
17375     Op = MI->getOperand(3);
17376     if (Op.isGlobal()) {
17377       AM.GV = Op.getGlobal();
17378     } else {
17379       AM.Disp = Op.getImm();
17380     }
17381     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17382                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17383
17384     // Reload the original control word now.
17385     addFrameReference(BuildMI(*BB, MI, DL,
17386                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17387
17388     MI->eraseFromParent();   // The pseudo instruction is gone now.
17389     return BB;
17390   }
17391     // String/text processing lowering.
17392   case X86::PCMPISTRM128REG:
17393   case X86::VPCMPISTRM128REG:
17394   case X86::PCMPISTRM128MEM:
17395   case X86::VPCMPISTRM128MEM:
17396   case X86::PCMPESTRM128REG:
17397   case X86::VPCMPESTRM128REG:
17398   case X86::PCMPESTRM128MEM:
17399   case X86::VPCMPESTRM128MEM:
17400     assert(Subtarget->hasSSE42() &&
17401            "Target must have SSE4.2 or AVX features enabled");
17402     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17403
17404   // String/text processing lowering.
17405   case X86::PCMPISTRIREG:
17406   case X86::VPCMPISTRIREG:
17407   case X86::PCMPISTRIMEM:
17408   case X86::VPCMPISTRIMEM:
17409   case X86::PCMPESTRIREG:
17410   case X86::VPCMPESTRIREG:
17411   case X86::PCMPESTRIMEM:
17412   case X86::VPCMPESTRIMEM:
17413     assert(Subtarget->hasSSE42() &&
17414            "Target must have SSE4.2 or AVX features enabled");
17415     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17416
17417   // Thread synchronization.
17418   case X86::MONITOR:
17419     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17420
17421   // xbegin
17422   case X86::XBEGIN:
17423     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17424
17425   // Atomic Lowering.
17426   case X86::ATOMAND8:
17427   case X86::ATOMAND16:
17428   case X86::ATOMAND32:
17429   case X86::ATOMAND64:
17430     // Fall through
17431   case X86::ATOMOR8:
17432   case X86::ATOMOR16:
17433   case X86::ATOMOR32:
17434   case X86::ATOMOR64:
17435     // Fall through
17436   case X86::ATOMXOR16:
17437   case X86::ATOMXOR8:
17438   case X86::ATOMXOR32:
17439   case X86::ATOMXOR64:
17440     // Fall through
17441   case X86::ATOMNAND8:
17442   case X86::ATOMNAND16:
17443   case X86::ATOMNAND32:
17444   case X86::ATOMNAND64:
17445     // Fall through
17446   case X86::ATOMMAX8:
17447   case X86::ATOMMAX16:
17448   case X86::ATOMMAX32:
17449   case X86::ATOMMAX64:
17450     // Fall through
17451   case X86::ATOMMIN8:
17452   case X86::ATOMMIN16:
17453   case X86::ATOMMIN32:
17454   case X86::ATOMMIN64:
17455     // Fall through
17456   case X86::ATOMUMAX8:
17457   case X86::ATOMUMAX16:
17458   case X86::ATOMUMAX32:
17459   case X86::ATOMUMAX64:
17460     // Fall through
17461   case X86::ATOMUMIN8:
17462   case X86::ATOMUMIN16:
17463   case X86::ATOMUMIN32:
17464   case X86::ATOMUMIN64:
17465     return EmitAtomicLoadArith(MI, BB);
17466
17467   // This group does 64-bit operations on a 32-bit host.
17468   case X86::ATOMAND6432:
17469   case X86::ATOMOR6432:
17470   case X86::ATOMXOR6432:
17471   case X86::ATOMNAND6432:
17472   case X86::ATOMADD6432:
17473   case X86::ATOMSUB6432:
17474   case X86::ATOMMAX6432:
17475   case X86::ATOMMIN6432:
17476   case X86::ATOMUMAX6432:
17477   case X86::ATOMUMIN6432:
17478   case X86::ATOMSWAP6432:
17479     return EmitAtomicLoadArith6432(MI, BB);
17480
17481   case X86::VASTART_SAVE_XMM_REGS:
17482     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17483
17484   case X86::VAARG_64:
17485     return EmitVAARG64WithCustomInserter(MI, BB);
17486
17487   case X86::EH_SjLj_SetJmp32:
17488   case X86::EH_SjLj_SetJmp64:
17489     return emitEHSjLjSetJmp(MI, BB);
17490
17491   case X86::EH_SjLj_LongJmp32:
17492   case X86::EH_SjLj_LongJmp64:
17493     return emitEHSjLjLongJmp(MI, BB);
17494
17495   case TargetOpcode::STACKMAP:
17496   case TargetOpcode::PATCHPOINT:
17497     return emitPatchPoint(MI, BB);
17498
17499   case X86::VFMADDPDr213r:
17500   case X86::VFMADDPSr213r:
17501   case X86::VFMADDSDr213r:
17502   case X86::VFMADDSSr213r:
17503   case X86::VFMSUBPDr213r:
17504   case X86::VFMSUBPSr213r:
17505   case X86::VFMSUBSDr213r:
17506   case X86::VFMSUBSSr213r:
17507   case X86::VFNMADDPDr213r:
17508   case X86::VFNMADDPSr213r:
17509   case X86::VFNMADDSDr213r:
17510   case X86::VFNMADDSSr213r:
17511   case X86::VFNMSUBPDr213r:
17512   case X86::VFNMSUBPSr213r:
17513   case X86::VFNMSUBSDr213r:
17514   case X86::VFNMSUBSSr213r:
17515   case X86::VFMADDPDr213rY:
17516   case X86::VFMADDPSr213rY:
17517   case X86::VFMSUBPDr213rY:
17518   case X86::VFMSUBPSr213rY:
17519   case X86::VFNMADDPDr213rY:
17520   case X86::VFNMADDPSr213rY:
17521   case X86::VFNMSUBPDr213rY:
17522   case X86::VFNMSUBPSr213rY:
17523     return emitFMA3Instr(MI, BB);
17524   }
17525 }
17526
17527 //===----------------------------------------------------------------------===//
17528 //                           X86 Optimization Hooks
17529 //===----------------------------------------------------------------------===//
17530
17531 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17532                                                       APInt &KnownZero,
17533                                                       APInt &KnownOne,
17534                                                       const SelectionDAG &DAG,
17535                                                       unsigned Depth) const {
17536   unsigned BitWidth = KnownZero.getBitWidth();
17537   unsigned Opc = Op.getOpcode();
17538   assert((Opc >= ISD::BUILTIN_OP_END ||
17539           Opc == ISD::INTRINSIC_WO_CHAIN ||
17540           Opc == ISD::INTRINSIC_W_CHAIN ||
17541           Opc == ISD::INTRINSIC_VOID) &&
17542          "Should use MaskedValueIsZero if you don't know whether Op"
17543          " is a target node!");
17544
17545   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17546   switch (Opc) {
17547   default: break;
17548   case X86ISD::ADD:
17549   case X86ISD::SUB:
17550   case X86ISD::ADC:
17551   case X86ISD::SBB:
17552   case X86ISD::SMUL:
17553   case X86ISD::UMUL:
17554   case X86ISD::INC:
17555   case X86ISD::DEC:
17556   case X86ISD::OR:
17557   case X86ISD::XOR:
17558   case X86ISD::AND:
17559     // These nodes' second result is a boolean.
17560     if (Op.getResNo() == 0)
17561       break;
17562     // Fallthrough
17563   case X86ISD::SETCC:
17564     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17565     break;
17566   case ISD::INTRINSIC_WO_CHAIN: {
17567     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17568     unsigned NumLoBits = 0;
17569     switch (IntId) {
17570     default: break;
17571     case Intrinsic::x86_sse_movmsk_ps:
17572     case Intrinsic::x86_avx_movmsk_ps_256:
17573     case Intrinsic::x86_sse2_movmsk_pd:
17574     case Intrinsic::x86_avx_movmsk_pd_256:
17575     case Intrinsic::x86_mmx_pmovmskb:
17576     case Intrinsic::x86_sse2_pmovmskb_128:
17577     case Intrinsic::x86_avx2_pmovmskb: {
17578       // High bits of movmskp{s|d}, pmovmskb are known zero.
17579       switch (IntId) {
17580         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17581         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17582         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17583         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17584         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17585         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17586         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17587         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17588       }
17589       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17590       break;
17591     }
17592     }
17593     break;
17594   }
17595   }
17596 }
17597
17598 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17599   SDValue Op,
17600   const SelectionDAG &,
17601   unsigned Depth) const {
17602   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17603   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17604     return Op.getValueType().getScalarType().getSizeInBits();
17605
17606   // Fallback case.
17607   return 1;
17608 }
17609
17610 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17611 /// node is a GlobalAddress + offset.
17612 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17613                                        const GlobalValue* &GA,
17614                                        int64_t &Offset) const {
17615   if (N->getOpcode() == X86ISD::Wrapper) {
17616     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17617       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17618       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17619       return true;
17620     }
17621   }
17622   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17623 }
17624
17625 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17626 /// same as extracting the high 128-bit part of 256-bit vector and then
17627 /// inserting the result into the low part of a new 256-bit vector
17628 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17629   EVT VT = SVOp->getValueType(0);
17630   unsigned NumElems = VT.getVectorNumElements();
17631
17632   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17633   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17634     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17635         SVOp->getMaskElt(j) >= 0)
17636       return false;
17637
17638   return true;
17639 }
17640
17641 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17642 /// same as extracting the low 128-bit part of 256-bit vector and then
17643 /// inserting the result into the high part of a new 256-bit vector
17644 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17645   EVT VT = SVOp->getValueType(0);
17646   unsigned NumElems = VT.getVectorNumElements();
17647
17648   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17649   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17650     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17651         SVOp->getMaskElt(j) >= 0)
17652       return false;
17653
17654   return true;
17655 }
17656
17657 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17658 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17659                                         TargetLowering::DAGCombinerInfo &DCI,
17660                                         const X86Subtarget* Subtarget) {
17661   SDLoc dl(N);
17662   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17663   SDValue V1 = SVOp->getOperand(0);
17664   SDValue V2 = SVOp->getOperand(1);
17665   EVT VT = SVOp->getValueType(0);
17666   unsigned NumElems = VT.getVectorNumElements();
17667
17668   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17669       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17670     //
17671     //                   0,0,0,...
17672     //                      |
17673     //    V      UNDEF    BUILD_VECTOR    UNDEF
17674     //     \      /           \           /
17675     //  CONCAT_VECTOR         CONCAT_VECTOR
17676     //         \                  /
17677     //          \                /
17678     //          RESULT: V + zero extended
17679     //
17680     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17681         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17682         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17683       return SDValue();
17684
17685     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17686       return SDValue();
17687
17688     // To match the shuffle mask, the first half of the mask should
17689     // be exactly the first vector, and all the rest a splat with the
17690     // first element of the second one.
17691     for (unsigned i = 0; i != NumElems/2; ++i)
17692       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17693           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17694         return SDValue();
17695
17696     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17697     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17698       if (Ld->hasNUsesOfValue(1, 0)) {
17699         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17700         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17701         SDValue ResNode =
17702           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17703                                   Ld->getMemoryVT(),
17704                                   Ld->getPointerInfo(),
17705                                   Ld->getAlignment(),
17706                                   false/*isVolatile*/, true/*ReadMem*/,
17707                                   false/*WriteMem*/);
17708
17709         // Make sure the newly-created LOAD is in the same position as Ld in
17710         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17711         // and update uses of Ld's output chain to use the TokenFactor.
17712         if (Ld->hasAnyUseOfValue(1)) {
17713           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17714                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17715           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17716           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17717                                  SDValue(ResNode.getNode(), 1));
17718         }
17719
17720         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17721       }
17722     }
17723
17724     // Emit a zeroed vector and insert the desired subvector on its
17725     // first half.
17726     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17727     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17728     return DCI.CombineTo(N, InsV);
17729   }
17730
17731   //===--------------------------------------------------------------------===//
17732   // Combine some shuffles into subvector extracts and inserts:
17733   //
17734
17735   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17736   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17737     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17738     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17739     return DCI.CombineTo(N, InsV);
17740   }
17741
17742   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17743   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17744     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17745     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17746     return DCI.CombineTo(N, InsV);
17747   }
17748
17749   return SDValue();
17750 }
17751
17752 /// PerformShuffleCombine - Performs several different shuffle combines.
17753 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17754                                      TargetLowering::DAGCombinerInfo &DCI,
17755                                      const X86Subtarget *Subtarget) {
17756   SDLoc dl(N);
17757   SDValue N0 = N->getOperand(0);
17758   SDValue N1 = N->getOperand(1);
17759   EVT VT = N->getValueType(0);
17760
17761   // Don't create instructions with illegal types after legalize types has run.
17762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17763   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17764     return SDValue();
17765
17766   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17767   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17768       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17769     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17770
17771   // During Type Legalization, when promoting illegal vector types,
17772   // the backend might introduce new shuffle dag nodes and bitcasts.
17773   //
17774   // This code performs the following transformation:
17775   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17776   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17777   //
17778   // We do this only if both the bitcast and the BINOP dag nodes have
17779   // one use. Also, perform this transformation only if the new binary
17780   // operation is legal. This is to avoid introducing dag nodes that
17781   // potentially need to be further expanded (or custom lowered) into a
17782   // less optimal sequence of dag nodes.
17783   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17784       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17785       N0.getOpcode() == ISD::BITCAST) {
17786     SDValue BC0 = N0.getOperand(0);
17787     EVT SVT = BC0.getValueType();
17788     unsigned Opcode = BC0.getOpcode();
17789     unsigned NumElts = VT.getVectorNumElements();
17790     
17791     if (BC0.hasOneUse() && SVT.isVector() &&
17792         SVT.getVectorNumElements() * 2 == NumElts &&
17793         TLI.isOperationLegal(Opcode, VT)) {
17794       bool CanFold = false;
17795       switch (Opcode) {
17796       default : break;
17797       case ISD::ADD :
17798       case ISD::FADD :
17799       case ISD::SUB :
17800       case ISD::FSUB :
17801       case ISD::MUL :
17802       case ISD::FMUL :
17803         CanFold = true;
17804       }
17805
17806       unsigned SVTNumElts = SVT.getVectorNumElements();
17807       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17808       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17809         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17810       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17811         CanFold = SVOp->getMaskElt(i) < 0;
17812
17813       if (CanFold) {
17814         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17815         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17816         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17817         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17818       }
17819     }
17820   }
17821
17822   // Only handle 128 wide vector from here on.
17823   if (!VT.is128BitVector())
17824     return SDValue();
17825
17826   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17827   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17828   // consecutive, non-overlapping, and in the right order.
17829   SmallVector<SDValue, 16> Elts;
17830   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17831     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17832
17833   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17834 }
17835
17836 /// PerformTruncateCombine - Converts truncate operation to
17837 /// a sequence of vector shuffle operations.
17838 /// It is possible when we truncate 256-bit vector to 128-bit vector
17839 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17840                                       TargetLowering::DAGCombinerInfo &DCI,
17841                                       const X86Subtarget *Subtarget)  {
17842   return SDValue();
17843 }
17844
17845 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17846 /// specific shuffle of a load can be folded into a single element load.
17847 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17848 /// shuffles have been customed lowered so we need to handle those here.
17849 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17850                                          TargetLowering::DAGCombinerInfo &DCI) {
17851   if (DCI.isBeforeLegalizeOps())
17852     return SDValue();
17853
17854   SDValue InVec = N->getOperand(0);
17855   SDValue EltNo = N->getOperand(1);
17856
17857   if (!isa<ConstantSDNode>(EltNo))
17858     return SDValue();
17859
17860   EVT VT = InVec.getValueType();
17861
17862   bool HasShuffleIntoBitcast = false;
17863   if (InVec.getOpcode() == ISD::BITCAST) {
17864     // Don't duplicate a load with other uses.
17865     if (!InVec.hasOneUse())
17866       return SDValue();
17867     EVT BCVT = InVec.getOperand(0).getValueType();
17868     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17869       return SDValue();
17870     InVec = InVec.getOperand(0);
17871     HasShuffleIntoBitcast = true;
17872   }
17873
17874   if (!isTargetShuffle(InVec.getOpcode()))
17875     return SDValue();
17876
17877   // Don't duplicate a load with other uses.
17878   if (!InVec.hasOneUse())
17879     return SDValue();
17880
17881   SmallVector<int, 16> ShuffleMask;
17882   bool UnaryShuffle;
17883   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17884                             UnaryShuffle))
17885     return SDValue();
17886
17887   // Select the input vector, guarding against out of range extract vector.
17888   unsigned NumElems = VT.getVectorNumElements();
17889   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17890   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17891   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17892                                          : InVec.getOperand(1);
17893
17894   // If inputs to shuffle are the same for both ops, then allow 2 uses
17895   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17896
17897   if (LdNode.getOpcode() == ISD::BITCAST) {
17898     // Don't duplicate a load with other uses.
17899     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17900       return SDValue();
17901
17902     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17903     LdNode = LdNode.getOperand(0);
17904   }
17905
17906   if (!ISD::isNormalLoad(LdNode.getNode()))
17907     return SDValue();
17908
17909   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17910
17911   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17912     return SDValue();
17913
17914   if (HasShuffleIntoBitcast) {
17915     // If there's a bitcast before the shuffle, check if the load type and
17916     // alignment is valid.
17917     unsigned Align = LN0->getAlignment();
17918     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17919     unsigned NewAlign = TLI.getDataLayout()->
17920       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17921
17922     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17923       return SDValue();
17924   }
17925
17926   // All checks match so transform back to vector_shuffle so that DAG combiner
17927   // can finish the job
17928   SDLoc dl(N);
17929
17930   // Create shuffle node taking into account the case that its a unary shuffle
17931   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17932   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17933                                  InVec.getOperand(0), Shuffle,
17934                                  &ShuffleMask[0]);
17935   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17936   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17937                      EltNo);
17938 }
17939
17940 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17941 /// generation and convert it from being a bunch of shuffles and extracts
17942 /// to a simple store and scalar loads to extract the elements.
17943 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17944                                          TargetLowering::DAGCombinerInfo &DCI) {
17945   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17946   if (NewOp.getNode())
17947     return NewOp;
17948
17949   SDValue InputVector = N->getOperand(0);
17950
17951   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17952   // from mmx to v2i32 has a single usage.
17953   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17954       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17955       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17956     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17957                        N->getValueType(0),
17958                        InputVector.getNode()->getOperand(0));
17959
17960   // Only operate on vectors of 4 elements, where the alternative shuffling
17961   // gets to be more expensive.
17962   if (InputVector.getValueType() != MVT::v4i32)
17963     return SDValue();
17964
17965   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17966   // single use which is a sign-extend or zero-extend, and all elements are
17967   // used.
17968   SmallVector<SDNode *, 4> Uses;
17969   unsigned ExtractedElements = 0;
17970   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17971        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17972     if (UI.getUse().getResNo() != InputVector.getResNo())
17973       return SDValue();
17974
17975     SDNode *Extract = *UI;
17976     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17977       return SDValue();
17978
17979     if (Extract->getValueType(0) != MVT::i32)
17980       return SDValue();
17981     if (!Extract->hasOneUse())
17982       return SDValue();
17983     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17984         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17985       return SDValue();
17986     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17987       return SDValue();
17988
17989     // Record which element was extracted.
17990     ExtractedElements |=
17991       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17992
17993     Uses.push_back(Extract);
17994   }
17995
17996   // If not all the elements were used, this may not be worthwhile.
17997   if (ExtractedElements != 15)
17998     return SDValue();
17999
18000   // Ok, we've now decided to do the transformation.
18001   SDLoc dl(InputVector);
18002
18003   // Store the value to a temporary stack slot.
18004   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18005   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18006                             MachinePointerInfo(), false, false, 0);
18007
18008   // Replace each use (extract) with a load of the appropriate element.
18009   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18010        UE = Uses.end(); UI != UE; ++UI) {
18011     SDNode *Extract = *UI;
18012
18013     // cOMpute the element's address.
18014     SDValue Idx = Extract->getOperand(1);
18015     unsigned EltSize =
18016         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18017     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18018     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18019     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18020
18021     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18022                                      StackPtr, OffsetVal);
18023
18024     // Load the scalar.
18025     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18026                                      ScalarAddr, MachinePointerInfo(),
18027                                      false, false, false, 0);
18028
18029     // Replace the exact with the load.
18030     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18031   }
18032
18033   // The replacement was made in place; don't return anything.
18034   return SDValue();
18035 }
18036
18037 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18038 static std::pair<unsigned, bool>
18039 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18040                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18041   if (!VT.isVector())
18042     return std::make_pair(0, false);
18043
18044   bool NeedSplit = false;
18045   switch (VT.getSimpleVT().SimpleTy) {
18046   default: return std::make_pair(0, false);
18047   case MVT::v32i8:
18048   case MVT::v16i16:
18049   case MVT::v8i32:
18050     if (!Subtarget->hasAVX2())
18051       NeedSplit = true;
18052     if (!Subtarget->hasAVX())
18053       return std::make_pair(0, false);
18054     break;
18055   case MVT::v16i8:
18056   case MVT::v8i16:
18057   case MVT::v4i32:
18058     if (!Subtarget->hasSSE2())
18059       return std::make_pair(0, false);
18060   }
18061
18062   // SSE2 has only a small subset of the operations.
18063   bool hasUnsigned = Subtarget->hasSSE41() ||
18064                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
18065   bool hasSigned = Subtarget->hasSSE41() ||
18066                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
18067
18068   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18069
18070   unsigned Opc = 0;
18071   // Check for x CC y ? x : y.
18072   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18073       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18074     switch (CC) {
18075     default: break;
18076     case ISD::SETULT:
18077     case ISD::SETULE:
18078       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18079     case ISD::SETUGT:
18080     case ISD::SETUGE:
18081       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18082     case ISD::SETLT:
18083     case ISD::SETLE:
18084       Opc = hasSigned ? X86ISD::SMIN : 0; break;
18085     case ISD::SETGT:
18086     case ISD::SETGE:
18087       Opc = hasSigned ? X86ISD::SMAX : 0; break;
18088     }
18089   // Check for x CC y ? y : x -- a min/max with reversed arms.
18090   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18091              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18092     switch (CC) {
18093     default: break;
18094     case ISD::SETULT:
18095     case ISD::SETULE:
18096       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18097     case ISD::SETUGT:
18098     case ISD::SETUGE:
18099       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18100     case ISD::SETLT:
18101     case ISD::SETLE:
18102       Opc = hasSigned ? X86ISD::SMAX : 0; break;
18103     case ISD::SETGT:
18104     case ISD::SETGE:
18105       Opc = hasSigned ? X86ISD::SMIN : 0; break;
18106     }
18107   }
18108
18109   return std::make_pair(Opc, NeedSplit);
18110 }
18111
18112 static SDValue
18113 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18114                                       const X86Subtarget *Subtarget) {
18115   SDLoc dl(N);
18116   SDValue Cond = N->getOperand(0);
18117   SDValue LHS = N->getOperand(1);
18118   SDValue RHS = N->getOperand(2);
18119
18120   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18121     SDValue CondSrc = Cond->getOperand(0);
18122     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18123       Cond = CondSrc->getOperand(0);
18124   }
18125
18126   MVT VT = N->getSimpleValueType(0);
18127   MVT EltVT = VT.getVectorElementType();
18128   unsigned NumElems = VT.getVectorNumElements();
18129   // There is no blend with immediate in AVX-512.
18130   if (VT.is512BitVector())
18131     return SDValue();
18132
18133   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18134     return SDValue();
18135   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18136     return SDValue();
18137
18138   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18139     return SDValue();
18140
18141   unsigned MaskValue = 0;
18142   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18143     return SDValue();
18144
18145   SmallVector<int, 8> ShuffleMask(NumElems, -1);
18146   for (unsigned i = 0; i < NumElems; ++i) {
18147     // Be sure we emit undef where we can.
18148     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18149       ShuffleMask[i] = -1;
18150     else
18151       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18152   }
18153
18154   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18155 }
18156
18157 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18158 /// nodes.
18159 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18160                                     TargetLowering::DAGCombinerInfo &DCI,
18161                                     const X86Subtarget *Subtarget) {
18162   SDLoc DL(N);
18163   SDValue Cond = N->getOperand(0);
18164   // Get the LHS/RHS of the select.
18165   SDValue LHS = N->getOperand(1);
18166   SDValue RHS = N->getOperand(2);
18167   EVT VT = LHS.getValueType();
18168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18169
18170   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18171   // instructions match the semantics of the common C idiom x<y?x:y but not
18172   // x<=y?x:y, because of how they handle negative zero (which can be
18173   // ignored in unsafe-math mode).
18174   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18175       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18176       (Subtarget->hasSSE2() ||
18177        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18178     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18179
18180     unsigned Opcode = 0;
18181     // Check for x CC y ? x : y.
18182     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18183         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18184       switch (CC) {
18185       default: break;
18186       case ISD::SETULT:
18187         // Converting this to a min would handle NaNs incorrectly, and swapping
18188         // the operands would cause it to handle comparisons between positive
18189         // and negative zero incorrectly.
18190         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18191           if (!DAG.getTarget().Options.UnsafeFPMath &&
18192               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18193             break;
18194           std::swap(LHS, RHS);
18195         }
18196         Opcode = X86ISD::FMIN;
18197         break;
18198       case ISD::SETOLE:
18199         // Converting this to a min would handle comparisons between positive
18200         // and negative zero incorrectly.
18201         if (!DAG.getTarget().Options.UnsafeFPMath &&
18202             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18203           break;
18204         Opcode = X86ISD::FMIN;
18205         break;
18206       case ISD::SETULE:
18207         // Converting this to a min would handle both negative zeros and NaNs
18208         // incorrectly, but we can swap the operands to fix both.
18209         std::swap(LHS, RHS);
18210       case ISD::SETOLT:
18211       case ISD::SETLT:
18212       case ISD::SETLE:
18213         Opcode = X86ISD::FMIN;
18214         break;
18215
18216       case ISD::SETOGE:
18217         // Converting this to a max would handle comparisons between positive
18218         // and negative zero incorrectly.
18219         if (!DAG.getTarget().Options.UnsafeFPMath &&
18220             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18221           break;
18222         Opcode = X86ISD::FMAX;
18223         break;
18224       case ISD::SETUGT:
18225         // Converting this to a max would handle NaNs incorrectly, and swapping
18226         // the operands would cause it to handle comparisons between positive
18227         // and negative zero incorrectly.
18228         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18229           if (!DAG.getTarget().Options.UnsafeFPMath &&
18230               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18231             break;
18232           std::swap(LHS, RHS);
18233         }
18234         Opcode = X86ISD::FMAX;
18235         break;
18236       case ISD::SETUGE:
18237         // Converting this to a max would handle both negative zeros and NaNs
18238         // incorrectly, but we can swap the operands to fix both.
18239         std::swap(LHS, RHS);
18240       case ISD::SETOGT:
18241       case ISD::SETGT:
18242       case ISD::SETGE:
18243         Opcode = X86ISD::FMAX;
18244         break;
18245       }
18246     // Check for x CC y ? y : x -- a min/max with reversed arms.
18247     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18248                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18249       switch (CC) {
18250       default: break;
18251       case ISD::SETOGE:
18252         // Converting this to a min would handle comparisons between positive
18253         // and negative zero incorrectly, and swapping the operands would
18254         // cause it to handle NaNs incorrectly.
18255         if (!DAG.getTarget().Options.UnsafeFPMath &&
18256             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18257           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18258             break;
18259           std::swap(LHS, RHS);
18260         }
18261         Opcode = X86ISD::FMIN;
18262         break;
18263       case ISD::SETUGT:
18264         // Converting this to a min would handle NaNs incorrectly.
18265         if (!DAG.getTarget().Options.UnsafeFPMath &&
18266             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18267           break;
18268         Opcode = X86ISD::FMIN;
18269         break;
18270       case ISD::SETUGE:
18271         // Converting this to a min would handle both negative zeros and NaNs
18272         // incorrectly, but we can swap the operands to fix both.
18273         std::swap(LHS, RHS);
18274       case ISD::SETOGT:
18275       case ISD::SETGT:
18276       case ISD::SETGE:
18277         Opcode = X86ISD::FMIN;
18278         break;
18279
18280       case ISD::SETULT:
18281         // Converting this to a max would handle NaNs incorrectly.
18282         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18283           break;
18284         Opcode = X86ISD::FMAX;
18285         break;
18286       case ISD::SETOLE:
18287         // Converting this to a max would handle comparisons between positive
18288         // and negative zero incorrectly, and swapping the operands would
18289         // cause it to handle NaNs incorrectly.
18290         if (!DAG.getTarget().Options.UnsafeFPMath &&
18291             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18292           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18293             break;
18294           std::swap(LHS, RHS);
18295         }
18296         Opcode = X86ISD::FMAX;
18297         break;
18298       case ISD::SETULE:
18299         // Converting this to a max would handle both negative zeros and NaNs
18300         // incorrectly, but we can swap the operands to fix both.
18301         std::swap(LHS, RHS);
18302       case ISD::SETOLT:
18303       case ISD::SETLT:
18304       case ISD::SETLE:
18305         Opcode = X86ISD::FMAX;
18306         break;
18307       }
18308     }
18309
18310     if (Opcode)
18311       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18312   }
18313
18314   EVT CondVT = Cond.getValueType();
18315   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18316       CondVT.getVectorElementType() == MVT::i1) {
18317     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18318     // lowering on AVX-512. In this case we convert it to
18319     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18320     // The same situation for all 128 and 256-bit vectors of i8 and i16
18321     EVT OpVT = LHS.getValueType();
18322     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18323         (OpVT.getVectorElementType() == MVT::i8 ||
18324          OpVT.getVectorElementType() == MVT::i16)) {
18325       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18326       DCI.AddToWorklist(Cond.getNode());
18327       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18328     }
18329   }
18330   // If this is a select between two integer constants, try to do some
18331   // optimizations.
18332   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18333     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18334       // Don't do this for crazy integer types.
18335       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18336         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18337         // so that TrueC (the true value) is larger than FalseC.
18338         bool NeedsCondInvert = false;
18339
18340         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18341             // Efficiently invertible.
18342             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
18343              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
18344               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18345           NeedsCondInvert = true;
18346           std::swap(TrueC, FalseC);
18347         }
18348
18349         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18350         if (FalseC->getAPIntValue() == 0 &&
18351             TrueC->getAPIntValue().isPowerOf2()) {
18352           if (NeedsCondInvert) // Invert the condition if needed.
18353             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18354                                DAG.getConstant(1, Cond.getValueType()));
18355
18356           // Zero extend the condition if needed.
18357           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18358
18359           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18360           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18361                              DAG.getConstant(ShAmt, MVT::i8));
18362         }
18363
18364         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18365         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18366           if (NeedsCondInvert) // Invert the condition if needed.
18367             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18368                                DAG.getConstant(1, Cond.getValueType()));
18369
18370           // Zero extend the condition if needed.
18371           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18372                              FalseC->getValueType(0), Cond);
18373           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18374                              SDValue(FalseC, 0));
18375         }
18376
18377         // Optimize cases that will turn into an LEA instruction.  This requires
18378         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18379         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18380           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18381           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18382
18383           bool isFastMultiplier = false;
18384           if (Diff < 10) {
18385             switch ((unsigned char)Diff) {
18386               default: break;
18387               case 1:  // result = add base, cond
18388               case 2:  // result = lea base(    , cond*2)
18389               case 3:  // result = lea base(cond, cond*2)
18390               case 4:  // result = lea base(    , cond*4)
18391               case 5:  // result = lea base(cond, cond*4)
18392               case 8:  // result = lea base(    , cond*8)
18393               case 9:  // result = lea base(cond, cond*8)
18394                 isFastMultiplier = true;
18395                 break;
18396             }
18397           }
18398
18399           if (isFastMultiplier) {
18400             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18401             if (NeedsCondInvert) // Invert the condition if needed.
18402               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18403                                  DAG.getConstant(1, Cond.getValueType()));
18404
18405             // Zero extend the condition if needed.
18406             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18407                                Cond);
18408             // Scale the condition by the difference.
18409             if (Diff != 1)
18410               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18411                                  DAG.getConstant(Diff, Cond.getValueType()));
18412
18413             // Add the base if non-zero.
18414             if (FalseC->getAPIntValue() != 0)
18415               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18416                                  SDValue(FalseC, 0));
18417             return Cond;
18418           }
18419         }
18420       }
18421   }
18422
18423   // Canonicalize max and min:
18424   // (x > y) ? x : y -> (x >= y) ? x : y
18425   // (x < y) ? x : y -> (x <= y) ? x : y
18426   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18427   // the need for an extra compare
18428   // against zero. e.g.
18429   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18430   // subl   %esi, %edi
18431   // testl  %edi, %edi
18432   // movl   $0, %eax
18433   // cmovgl %edi, %eax
18434   // =>
18435   // xorl   %eax, %eax
18436   // subl   %esi, $edi
18437   // cmovsl %eax, %edi
18438   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18439       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18440       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18441     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18442     switch (CC) {
18443     default: break;
18444     case ISD::SETLT:
18445     case ISD::SETGT: {
18446       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18447       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18448                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18449       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18450     }
18451     }
18452   }
18453
18454   // Early exit check
18455   if (!TLI.isTypeLegal(VT))
18456     return SDValue();
18457
18458   // Match VSELECTs into subs with unsigned saturation.
18459   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18460       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18461       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18462        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18463     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18464
18465     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18466     // left side invert the predicate to simplify logic below.
18467     SDValue Other;
18468     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18469       Other = RHS;
18470       CC = ISD::getSetCCInverse(CC, true);
18471     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18472       Other = LHS;
18473     }
18474
18475     if (Other.getNode() && Other->getNumOperands() == 2 &&
18476         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18477       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18478       SDValue CondRHS = Cond->getOperand(1);
18479
18480       // Look for a general sub with unsigned saturation first.
18481       // x >= y ? x-y : 0 --> subus x, y
18482       // x >  y ? x-y : 0 --> subus x, y
18483       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18484           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18485         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18486
18487       // If the RHS is a constant we have to reverse the const canonicalization.
18488       // x > C-1 ? x+-C : 0 --> subus x, C
18489       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18490           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18491         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18492         if (CondRHS.getConstantOperandVal(0) == -A-1)
18493           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18494                              DAG.getConstant(-A, VT));
18495       }
18496
18497       // Another special case: If C was a sign bit, the sub has been
18498       // canonicalized into a xor.
18499       // FIXME: Would it be better to use computeKnownBits to determine whether
18500       //        it's safe to decanonicalize the xor?
18501       // x s< 0 ? x^C : 0 --> subus x, C
18502       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18503           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18504           isSplatVector(OpRHS.getNode())) {
18505         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18506         if (A.isSignBit())
18507           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18508       }
18509     }
18510   }
18511
18512   // Try to match a min/max vector operation.
18513   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18514     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18515     unsigned Opc = ret.first;
18516     bool NeedSplit = ret.second;
18517
18518     if (Opc && NeedSplit) {
18519       unsigned NumElems = VT.getVectorNumElements();
18520       // Extract the LHS vectors
18521       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18522       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18523
18524       // Extract the RHS vectors
18525       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18526       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18527
18528       // Create min/max for each subvector
18529       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18530       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18531
18532       // Merge the result
18533       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18534     } else if (Opc)
18535       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18536   }
18537
18538   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18539   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18540       // Check if SETCC has already been promoted
18541       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18542       // Check that condition value type matches vselect operand type
18543       CondVT == VT) { 
18544
18545     assert(Cond.getValueType().isVector() &&
18546            "vector select expects a vector selector!");
18547
18548     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18549     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18550
18551     if (!TValIsAllOnes && !FValIsAllZeros) {
18552       // Try invert the condition if true value is not all 1s and false value
18553       // is not all 0s.
18554       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18555       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18556
18557       if (TValIsAllZeros || FValIsAllOnes) {
18558         SDValue CC = Cond.getOperand(2);
18559         ISD::CondCode NewCC =
18560           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18561                                Cond.getOperand(0).getValueType().isInteger());
18562         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18563         std::swap(LHS, RHS);
18564         TValIsAllOnes = FValIsAllOnes;
18565         FValIsAllZeros = TValIsAllZeros;
18566       }
18567     }
18568
18569     if (TValIsAllOnes || FValIsAllZeros) {
18570       SDValue Ret;
18571
18572       if (TValIsAllOnes && FValIsAllZeros)
18573         Ret = Cond;
18574       else if (TValIsAllOnes)
18575         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18576                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18577       else if (FValIsAllZeros)
18578         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18579                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18580
18581       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18582     }
18583   }
18584
18585   // Try to fold this VSELECT into a MOVSS/MOVSD
18586   if (N->getOpcode() == ISD::VSELECT &&
18587       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18588     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18589         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18590       bool CanFold = false;
18591       unsigned NumElems = Cond.getNumOperands();
18592       SDValue A = LHS;
18593       SDValue B = RHS;
18594       
18595       if (isZero(Cond.getOperand(0))) {
18596         CanFold = true;
18597
18598         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18599         // fold (vselect <0,-1> -> (movsd A, B)
18600         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18601           CanFold = isAllOnes(Cond.getOperand(i));
18602       } else if (isAllOnes(Cond.getOperand(0))) {
18603         CanFold = true;
18604         std::swap(A, B);
18605
18606         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18607         // fold (vselect <-1,0> -> (movsd B, A)
18608         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18609           CanFold = isZero(Cond.getOperand(i));
18610       }
18611
18612       if (CanFold) {
18613         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18614           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18615         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18616       }
18617
18618       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18619         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18620         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18621         //                             (v2i64 (bitcast B)))))
18622         //
18623         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18624         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18625         //                             (v2f64 (bitcast B)))))
18626         //
18627         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18628         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18629         //                             (v2i64 (bitcast A)))))
18630         //
18631         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18632         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18633         //                             (v2f64 (bitcast A)))))
18634
18635         CanFold = (isZero(Cond.getOperand(0)) &&
18636                    isZero(Cond.getOperand(1)) &&
18637                    isAllOnes(Cond.getOperand(2)) &&
18638                    isAllOnes(Cond.getOperand(3)));
18639
18640         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18641             isAllOnes(Cond.getOperand(1)) &&
18642             isZero(Cond.getOperand(2)) &&
18643             isZero(Cond.getOperand(3))) {
18644           CanFold = true;
18645           std::swap(LHS, RHS);
18646         }
18647
18648         if (CanFold) {
18649           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18650           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18651           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18652           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18653                                                 NewB, DAG);
18654           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18655         }
18656       }
18657     }
18658   }
18659
18660   // If we know that this node is legal then we know that it is going to be
18661   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18662   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18663   // to simplify previous instructions.
18664   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18665       !DCI.isBeforeLegalize() &&
18666       // We explicitly check against v8i16 and v16i16 because, although
18667       // they're marked as Custom, they might only be legal when Cond is a
18668       // build_vector of constants. This will be taken care in a later
18669       // condition.
18670       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18671        VT != MVT::v8i16)) {
18672     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18673
18674     // Don't optimize vector selects that map to mask-registers.
18675     if (BitWidth == 1)
18676       return SDValue();
18677
18678     // Check all uses of that condition operand to check whether it will be
18679     // consumed by non-BLEND instructions, which may depend on all bits are set
18680     // properly.
18681     for (SDNode::use_iterator I = Cond->use_begin(),
18682                               E = Cond->use_end(); I != E; ++I)
18683       if (I->getOpcode() != ISD::VSELECT)
18684         // TODO: Add other opcodes eventually lowered into BLEND.
18685         return SDValue();
18686
18687     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18688     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18689
18690     APInt KnownZero, KnownOne;
18691     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18692                                           DCI.isBeforeLegalizeOps());
18693     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18694         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18695       DCI.CommitTargetLoweringOpt(TLO);
18696   }
18697
18698   // We should generate an X86ISD::BLENDI from a vselect if its argument
18699   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18700   // constants. This specific pattern gets generated when we split a
18701   // selector for a 512 bit vector in a machine without AVX512 (but with
18702   // 256-bit vectors), during legalization:
18703   //
18704   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18705   //
18706   // Iff we find this pattern and the build_vectors are built from
18707   // constants, we translate the vselect into a shuffle_vector that we
18708   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18709   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18710     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18711     if (Shuffle.getNode())
18712       return Shuffle;
18713   }
18714
18715   return SDValue();
18716 }
18717
18718 // Check whether a boolean test is testing a boolean value generated by
18719 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18720 // code.
18721 //
18722 // Simplify the following patterns:
18723 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18724 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18725 // to (Op EFLAGS Cond)
18726 //
18727 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18728 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18729 // to (Op EFLAGS !Cond)
18730 //
18731 // where Op could be BRCOND or CMOV.
18732 //
18733 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18734   // Quit if not CMP and SUB with its value result used.
18735   if (Cmp.getOpcode() != X86ISD::CMP &&
18736       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18737       return SDValue();
18738
18739   // Quit if not used as a boolean value.
18740   if (CC != X86::COND_E && CC != X86::COND_NE)
18741     return SDValue();
18742
18743   // Check CMP operands. One of them should be 0 or 1 and the other should be
18744   // an SetCC or extended from it.
18745   SDValue Op1 = Cmp.getOperand(0);
18746   SDValue Op2 = Cmp.getOperand(1);
18747
18748   SDValue SetCC;
18749   const ConstantSDNode* C = nullptr;
18750   bool needOppositeCond = (CC == X86::COND_E);
18751   bool checkAgainstTrue = false; // Is it a comparison against 1?
18752
18753   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18754     SetCC = Op2;
18755   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18756     SetCC = Op1;
18757   else // Quit if all operands are not constants.
18758     return SDValue();
18759
18760   if (C->getZExtValue() == 1) {
18761     needOppositeCond = !needOppositeCond;
18762     checkAgainstTrue = true;
18763   } else if (C->getZExtValue() != 0)
18764     // Quit if the constant is neither 0 or 1.
18765     return SDValue();
18766
18767   bool truncatedToBoolWithAnd = false;
18768   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18769   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18770          SetCC.getOpcode() == ISD::TRUNCATE ||
18771          SetCC.getOpcode() == ISD::AND) {
18772     if (SetCC.getOpcode() == ISD::AND) {
18773       int OpIdx = -1;
18774       ConstantSDNode *CS;
18775       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18776           CS->getZExtValue() == 1)
18777         OpIdx = 1;
18778       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18779           CS->getZExtValue() == 1)
18780         OpIdx = 0;
18781       if (OpIdx == -1)
18782         break;
18783       SetCC = SetCC.getOperand(OpIdx);
18784       truncatedToBoolWithAnd = true;
18785     } else
18786       SetCC = SetCC.getOperand(0);
18787   }
18788
18789   switch (SetCC.getOpcode()) {
18790   case X86ISD::SETCC_CARRY:
18791     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18792     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18793     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18794     // truncated to i1 using 'and'.
18795     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18796       break;
18797     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18798            "Invalid use of SETCC_CARRY!");
18799     // FALL THROUGH
18800   case X86ISD::SETCC:
18801     // Set the condition code or opposite one if necessary.
18802     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18803     if (needOppositeCond)
18804       CC = X86::GetOppositeBranchCondition(CC);
18805     return SetCC.getOperand(1);
18806   case X86ISD::CMOV: {
18807     // Check whether false/true value has canonical one, i.e. 0 or 1.
18808     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18809     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18810     // Quit if true value is not a constant.
18811     if (!TVal)
18812       return SDValue();
18813     // Quit if false value is not a constant.
18814     if (!FVal) {
18815       SDValue Op = SetCC.getOperand(0);
18816       // Skip 'zext' or 'trunc' node.
18817       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18818           Op.getOpcode() == ISD::TRUNCATE)
18819         Op = Op.getOperand(0);
18820       // A special case for rdrand/rdseed, where 0 is set if false cond is
18821       // found.
18822       if ((Op.getOpcode() != X86ISD::RDRAND &&
18823            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18824         return SDValue();
18825     }
18826     // Quit if false value is not the constant 0 or 1.
18827     bool FValIsFalse = true;
18828     if (FVal && FVal->getZExtValue() != 0) {
18829       if (FVal->getZExtValue() != 1)
18830         return SDValue();
18831       // If FVal is 1, opposite cond is needed.
18832       needOppositeCond = !needOppositeCond;
18833       FValIsFalse = false;
18834     }
18835     // Quit if TVal is not the constant opposite of FVal.
18836     if (FValIsFalse && TVal->getZExtValue() != 1)
18837       return SDValue();
18838     if (!FValIsFalse && TVal->getZExtValue() != 0)
18839       return SDValue();
18840     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18841     if (needOppositeCond)
18842       CC = X86::GetOppositeBranchCondition(CC);
18843     return SetCC.getOperand(3);
18844   }
18845   }
18846
18847   return SDValue();
18848 }
18849
18850 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18851 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18852                                   TargetLowering::DAGCombinerInfo &DCI,
18853                                   const X86Subtarget *Subtarget) {
18854   SDLoc DL(N);
18855
18856   // If the flag operand isn't dead, don't touch this CMOV.
18857   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18858     return SDValue();
18859
18860   SDValue FalseOp = N->getOperand(0);
18861   SDValue TrueOp = N->getOperand(1);
18862   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18863   SDValue Cond = N->getOperand(3);
18864
18865   if (CC == X86::COND_E || CC == X86::COND_NE) {
18866     switch (Cond.getOpcode()) {
18867     default: break;
18868     case X86ISD::BSR:
18869     case X86ISD::BSF:
18870       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18871       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18872         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18873     }
18874   }
18875
18876   SDValue Flags;
18877
18878   Flags = checkBoolTestSetCCCombine(Cond, CC);
18879   if (Flags.getNode() &&
18880       // Extra check as FCMOV only supports a subset of X86 cond.
18881       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18882     SDValue Ops[] = { FalseOp, TrueOp,
18883                       DAG.getConstant(CC, MVT::i8), Flags };
18884     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18885   }
18886
18887   // If this is a select between two integer constants, try to do some
18888   // optimizations.  Note that the operands are ordered the opposite of SELECT
18889   // operands.
18890   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18891     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18892       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18893       // larger than FalseC (the false value).
18894       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18895         CC = X86::GetOppositeBranchCondition(CC);
18896         std::swap(TrueC, FalseC);
18897         std::swap(TrueOp, FalseOp);
18898       }
18899
18900       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18901       // This is efficient for any integer data type (including i8/i16) and
18902       // shift amount.
18903       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18904         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18905                            DAG.getConstant(CC, MVT::i8), Cond);
18906
18907         // Zero extend the condition if needed.
18908         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18909
18910         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18911         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18912                            DAG.getConstant(ShAmt, MVT::i8));
18913         if (N->getNumValues() == 2)  // Dead flag value?
18914           return DCI.CombineTo(N, Cond, SDValue());
18915         return Cond;
18916       }
18917
18918       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18919       // for any integer data type, including i8/i16.
18920       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18921         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18922                            DAG.getConstant(CC, MVT::i8), Cond);
18923
18924         // Zero extend the condition if needed.
18925         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18926                            FalseC->getValueType(0), Cond);
18927         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18928                            SDValue(FalseC, 0));
18929
18930         if (N->getNumValues() == 2)  // Dead flag value?
18931           return DCI.CombineTo(N, Cond, SDValue());
18932         return Cond;
18933       }
18934
18935       // Optimize cases that will turn into an LEA instruction.  This requires
18936       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18937       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18938         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18939         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18940
18941         bool isFastMultiplier = false;
18942         if (Diff < 10) {
18943           switch ((unsigned char)Diff) {
18944           default: break;
18945           case 1:  // result = add base, cond
18946           case 2:  // result = lea base(    , cond*2)
18947           case 3:  // result = lea base(cond, cond*2)
18948           case 4:  // result = lea base(    , cond*4)
18949           case 5:  // result = lea base(cond, cond*4)
18950           case 8:  // result = lea base(    , cond*8)
18951           case 9:  // result = lea base(cond, cond*8)
18952             isFastMultiplier = true;
18953             break;
18954           }
18955         }
18956
18957         if (isFastMultiplier) {
18958           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18959           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18960                              DAG.getConstant(CC, MVT::i8), Cond);
18961           // Zero extend the condition if needed.
18962           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18963                              Cond);
18964           // Scale the condition by the difference.
18965           if (Diff != 1)
18966             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18967                                DAG.getConstant(Diff, Cond.getValueType()));
18968
18969           // Add the base if non-zero.
18970           if (FalseC->getAPIntValue() != 0)
18971             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18972                                SDValue(FalseC, 0));
18973           if (N->getNumValues() == 2)  // Dead flag value?
18974             return DCI.CombineTo(N, Cond, SDValue());
18975           return Cond;
18976         }
18977       }
18978     }
18979   }
18980
18981   // Handle these cases:
18982   //   (select (x != c), e, c) -> select (x != c), e, x),
18983   //   (select (x == c), c, e) -> select (x == c), x, e)
18984   // where the c is an integer constant, and the "select" is the combination
18985   // of CMOV and CMP.
18986   //
18987   // The rationale for this change is that the conditional-move from a constant
18988   // needs two instructions, however, conditional-move from a register needs
18989   // only one instruction.
18990   //
18991   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18992   //  some instruction-combining opportunities. This opt needs to be
18993   //  postponed as late as possible.
18994   //
18995   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18996     // the DCI.xxxx conditions are provided to postpone the optimization as
18997     // late as possible.
18998
18999     ConstantSDNode *CmpAgainst = nullptr;
19000     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19001         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19002         !isa<ConstantSDNode>(Cond.getOperand(0))) {
19003
19004       if (CC == X86::COND_NE &&
19005           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19006         CC = X86::GetOppositeBranchCondition(CC);
19007         std::swap(TrueOp, FalseOp);
19008       }
19009
19010       if (CC == X86::COND_E &&
19011           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19012         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19013                           DAG.getConstant(CC, MVT::i8), Cond };
19014         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19015       }
19016     }
19017   }
19018
19019   return SDValue();
19020 }
19021
19022 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19023                                                 const X86Subtarget *Subtarget) {
19024   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19025   switch (IntNo) {
19026   default: return SDValue();
19027   // SSE/AVX/AVX2 blend intrinsics.
19028   case Intrinsic::x86_avx2_pblendvb:
19029   case Intrinsic::x86_avx2_pblendw:
19030   case Intrinsic::x86_avx2_pblendd_128:
19031   case Intrinsic::x86_avx2_pblendd_256:
19032     // Don't try to simplify this intrinsic if we don't have AVX2.
19033     if (!Subtarget->hasAVX2())
19034       return SDValue();
19035     // FALL-THROUGH
19036   case Intrinsic::x86_avx_blend_pd_256:
19037   case Intrinsic::x86_avx_blend_ps_256:
19038   case Intrinsic::x86_avx_blendv_pd_256:
19039   case Intrinsic::x86_avx_blendv_ps_256:
19040     // Don't try to simplify this intrinsic if we don't have AVX.
19041     if (!Subtarget->hasAVX())
19042       return SDValue();
19043     // FALL-THROUGH
19044   case Intrinsic::x86_sse41_pblendw:
19045   case Intrinsic::x86_sse41_blendpd:
19046   case Intrinsic::x86_sse41_blendps:
19047   case Intrinsic::x86_sse41_blendvps:
19048   case Intrinsic::x86_sse41_blendvpd:
19049   case Intrinsic::x86_sse41_pblendvb: {
19050     SDValue Op0 = N->getOperand(1);
19051     SDValue Op1 = N->getOperand(2);
19052     SDValue Mask = N->getOperand(3);
19053
19054     // Don't try to simplify this intrinsic if we don't have SSE4.1.
19055     if (!Subtarget->hasSSE41())
19056       return SDValue();
19057
19058     // fold (blend A, A, Mask) -> A
19059     if (Op0 == Op1)
19060       return Op0;
19061     // fold (blend A, B, allZeros) -> A
19062     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19063       return Op0;
19064     // fold (blend A, B, allOnes) -> B
19065     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19066       return Op1;
19067     
19068     // Simplify the case where the mask is a constant i32 value.
19069     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19070       if (C->isNullValue())
19071         return Op0;
19072       if (C->isAllOnesValue())
19073         return Op1;
19074     }
19075   }
19076
19077   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19078   case Intrinsic::x86_sse2_psrai_w:
19079   case Intrinsic::x86_sse2_psrai_d:
19080   case Intrinsic::x86_avx2_psrai_w:
19081   case Intrinsic::x86_avx2_psrai_d:
19082   case Intrinsic::x86_sse2_psra_w:
19083   case Intrinsic::x86_sse2_psra_d:
19084   case Intrinsic::x86_avx2_psra_w:
19085   case Intrinsic::x86_avx2_psra_d: {
19086     SDValue Op0 = N->getOperand(1);
19087     SDValue Op1 = N->getOperand(2);
19088     EVT VT = Op0.getValueType();
19089     assert(VT.isVector() && "Expected a vector type!");
19090
19091     if (isa<BuildVectorSDNode>(Op1))
19092       Op1 = Op1.getOperand(0);
19093
19094     if (!isa<ConstantSDNode>(Op1))
19095       return SDValue();
19096
19097     EVT SVT = VT.getVectorElementType();
19098     unsigned SVTBits = SVT.getSizeInBits();
19099
19100     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19101     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19102     uint64_t ShAmt = C.getZExtValue();
19103
19104     // Don't try to convert this shift into a ISD::SRA if the shift
19105     // count is bigger than or equal to the element size.
19106     if (ShAmt >= SVTBits)
19107       return SDValue();
19108
19109     // Trivial case: if the shift count is zero, then fold this
19110     // into the first operand.
19111     if (ShAmt == 0)
19112       return Op0;
19113
19114     // Replace this packed shift intrinsic with a target independent
19115     // shift dag node.
19116     SDValue Splat = DAG.getConstant(C, VT);
19117     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19118   }
19119   }
19120 }
19121
19122 /// PerformMulCombine - Optimize a single multiply with constant into two
19123 /// in order to implement it with two cheaper instructions, e.g.
19124 /// LEA + SHL, LEA + LEA.
19125 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19126                                  TargetLowering::DAGCombinerInfo &DCI) {
19127   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19128     return SDValue();
19129
19130   EVT VT = N->getValueType(0);
19131   if (VT != MVT::i64)
19132     return SDValue();
19133
19134   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19135   if (!C)
19136     return SDValue();
19137   uint64_t MulAmt = C->getZExtValue();
19138   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19139     return SDValue();
19140
19141   uint64_t MulAmt1 = 0;
19142   uint64_t MulAmt2 = 0;
19143   if ((MulAmt % 9) == 0) {
19144     MulAmt1 = 9;
19145     MulAmt2 = MulAmt / 9;
19146   } else if ((MulAmt % 5) == 0) {
19147     MulAmt1 = 5;
19148     MulAmt2 = MulAmt / 5;
19149   } else if ((MulAmt % 3) == 0) {
19150     MulAmt1 = 3;
19151     MulAmt2 = MulAmt / 3;
19152   }
19153   if (MulAmt2 &&
19154       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19155     SDLoc DL(N);
19156
19157     if (isPowerOf2_64(MulAmt2) &&
19158         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19159       // If second multiplifer is pow2, issue it first. We want the multiply by
19160       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19161       // is an add.
19162       std::swap(MulAmt1, MulAmt2);
19163
19164     SDValue NewMul;
19165     if (isPowerOf2_64(MulAmt1))
19166       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19167                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19168     else
19169       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19170                            DAG.getConstant(MulAmt1, VT));
19171
19172     if (isPowerOf2_64(MulAmt2))
19173       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19174                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19175     else
19176       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19177                            DAG.getConstant(MulAmt2, VT));
19178
19179     // Do not add new nodes to DAG combiner worklist.
19180     DCI.CombineTo(N, NewMul, false);
19181   }
19182   return SDValue();
19183 }
19184
19185 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19186   SDValue N0 = N->getOperand(0);
19187   SDValue N1 = N->getOperand(1);
19188   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19189   EVT VT = N0.getValueType();
19190
19191   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19192   // since the result of setcc_c is all zero's or all ones.
19193   if (VT.isInteger() && !VT.isVector() &&
19194       N1C && N0.getOpcode() == ISD::AND &&
19195       N0.getOperand(1).getOpcode() == ISD::Constant) {
19196     SDValue N00 = N0.getOperand(0);
19197     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19198         ((N00.getOpcode() == ISD::ANY_EXTEND ||
19199           N00.getOpcode() == ISD::ZERO_EXTEND) &&
19200          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19201       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19202       APInt ShAmt = N1C->getAPIntValue();
19203       Mask = Mask.shl(ShAmt);
19204       if (Mask != 0)
19205         return DAG.getNode(ISD::AND, SDLoc(N), VT,
19206                            N00, DAG.getConstant(Mask, VT));
19207     }
19208   }
19209
19210   // Hardware support for vector shifts is sparse which makes us scalarize the
19211   // vector operations in many cases. Also, on sandybridge ADD is faster than
19212   // shl.
19213   // (shl V, 1) -> add V,V
19214   if (isSplatVector(N1.getNode())) {
19215     assert(N0.getValueType().isVector() && "Invalid vector shift type");
19216     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19217     // We shift all of the values by one. In many cases we do not have
19218     // hardware support for this operation. This is better expressed as an ADD
19219     // of two values.
19220     if (N1C && (1 == N1C->getZExtValue())) {
19221       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19222     }
19223   }
19224
19225   return SDValue();
19226 }
19227
19228 /// \brief Returns a vector of 0s if the node in input is a vector logical
19229 /// shift by a constant amount which is known to be bigger than or equal
19230 /// to the vector element size in bits.
19231 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19232                                       const X86Subtarget *Subtarget) {
19233   EVT VT = N->getValueType(0);
19234
19235   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19236       (!Subtarget->hasInt256() ||
19237        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19238     return SDValue();
19239
19240   SDValue Amt = N->getOperand(1);
19241   SDLoc DL(N);
19242   if (isSplatVector(Amt.getNode())) {
19243     SDValue SclrAmt = Amt->getOperand(0);
19244     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19245       APInt ShiftAmt = C->getAPIntValue();
19246       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19247
19248       // SSE2/AVX2 logical shifts always return a vector of 0s
19249       // if the shift amount is bigger than or equal to
19250       // the element size. The constant shift amount will be
19251       // encoded as a 8-bit immediate.
19252       if (ShiftAmt.trunc(8).uge(MaxAmount))
19253         return getZeroVector(VT, Subtarget, DAG, DL);
19254     }
19255   }
19256
19257   return SDValue();
19258 }
19259
19260 /// PerformShiftCombine - Combine shifts.
19261 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19262                                    TargetLowering::DAGCombinerInfo &DCI,
19263                                    const X86Subtarget *Subtarget) {
19264   if (N->getOpcode() == ISD::SHL) {
19265     SDValue V = PerformSHLCombine(N, DAG);
19266     if (V.getNode()) return V;
19267   }
19268
19269   if (N->getOpcode() != ISD::SRA) {
19270     // Try to fold this logical shift into a zero vector.
19271     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19272     if (V.getNode()) return V;
19273   }
19274
19275   return SDValue();
19276 }
19277
19278 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
19279 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19280 // and friends.  Likewise for OR -> CMPNEQSS.
19281 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19282                             TargetLowering::DAGCombinerInfo &DCI,
19283                             const X86Subtarget *Subtarget) {
19284   unsigned opcode;
19285
19286   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19287   // we're requiring SSE2 for both.
19288   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19289     SDValue N0 = N->getOperand(0);
19290     SDValue N1 = N->getOperand(1);
19291     SDValue CMP0 = N0->getOperand(1);
19292     SDValue CMP1 = N1->getOperand(1);
19293     SDLoc DL(N);
19294
19295     // The SETCCs should both refer to the same CMP.
19296     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19297       return SDValue();
19298
19299     SDValue CMP00 = CMP0->getOperand(0);
19300     SDValue CMP01 = CMP0->getOperand(1);
19301     EVT     VT    = CMP00.getValueType();
19302
19303     if (VT == MVT::f32 || VT == MVT::f64) {
19304       bool ExpectingFlags = false;
19305       // Check for any users that want flags:
19306       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19307            !ExpectingFlags && UI != UE; ++UI)
19308         switch (UI->getOpcode()) {
19309         default:
19310         case ISD::BR_CC:
19311         case ISD::BRCOND:
19312         case ISD::SELECT:
19313           ExpectingFlags = true;
19314           break;
19315         case ISD::CopyToReg:
19316         case ISD::SIGN_EXTEND:
19317         case ISD::ZERO_EXTEND:
19318         case ISD::ANY_EXTEND:
19319           break;
19320         }
19321
19322       if (!ExpectingFlags) {
19323         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19324         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19325
19326         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19327           X86::CondCode tmp = cc0;
19328           cc0 = cc1;
19329           cc1 = tmp;
19330         }
19331
19332         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
19333             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19334           // FIXME: need symbolic constants for these magic numbers.
19335           // See X86ATTInstPrinter.cpp:printSSECC().
19336           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19337           if (Subtarget->hasAVX512()) {
19338             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19339                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
19340             if (N->getValueType(0) != MVT::i1)
19341               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19342                                  FSetCC);
19343             return FSetCC;
19344           }
19345           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19346                                               CMP00.getValueType(), CMP00, CMP01,
19347                                               DAG.getConstant(x86cc, MVT::i8));
19348
19349           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19350           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19351
19352           if (is64BitFP && !Subtarget->is64Bit()) {
19353             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19354             // 64-bit integer, since that's not a legal type. Since
19355             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19356             // bits, but can do this little dance to extract the lowest 32 bits
19357             // and work with those going forward.
19358             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19359                                            OnesOrZeroesF);
19360             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19361                                            Vector64);
19362             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19363                                         Vector32, DAG.getIntPtrConstant(0));
19364             IntVT = MVT::i32;
19365           }
19366
19367           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19368           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19369                                       DAG.getConstant(1, IntVT));
19370           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19371           return OneBitOfTruth;
19372         }
19373       }
19374     }
19375   }
19376   return SDValue();
19377 }
19378
19379 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19380 /// so it can be folded inside ANDNP.
19381 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19382   EVT VT = N->getValueType(0);
19383
19384   // Match direct AllOnes for 128 and 256-bit vectors
19385   if (ISD::isBuildVectorAllOnes(N))
19386     return true;
19387
19388   // Look through a bit convert.
19389   if (N->getOpcode() == ISD::BITCAST)
19390     N = N->getOperand(0).getNode();
19391
19392   // Sometimes the operand may come from a insert_subvector building a 256-bit
19393   // allones vector
19394   if (VT.is256BitVector() &&
19395       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19396     SDValue V1 = N->getOperand(0);
19397     SDValue V2 = N->getOperand(1);
19398
19399     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19400         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19401         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19402         ISD::isBuildVectorAllOnes(V2.getNode()))
19403       return true;
19404   }
19405
19406   return false;
19407 }
19408
19409 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19410 // register. In most cases we actually compare or select YMM-sized registers
19411 // and mixing the two types creates horrible code. This method optimizes
19412 // some of the transition sequences.
19413 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19414                                  TargetLowering::DAGCombinerInfo &DCI,
19415                                  const X86Subtarget *Subtarget) {
19416   EVT VT = N->getValueType(0);
19417   if (!VT.is256BitVector())
19418     return SDValue();
19419
19420   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19421           N->getOpcode() == ISD::ZERO_EXTEND ||
19422           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19423
19424   SDValue Narrow = N->getOperand(0);
19425   EVT NarrowVT = Narrow->getValueType(0);
19426   if (!NarrowVT.is128BitVector())
19427     return SDValue();
19428
19429   if (Narrow->getOpcode() != ISD::XOR &&
19430       Narrow->getOpcode() != ISD::AND &&
19431       Narrow->getOpcode() != ISD::OR)
19432     return SDValue();
19433
19434   SDValue N0  = Narrow->getOperand(0);
19435   SDValue N1  = Narrow->getOperand(1);
19436   SDLoc DL(Narrow);
19437
19438   // The Left side has to be a trunc.
19439   if (N0.getOpcode() != ISD::TRUNCATE)
19440     return SDValue();
19441
19442   // The type of the truncated inputs.
19443   EVT WideVT = N0->getOperand(0)->getValueType(0);
19444   if (WideVT != VT)
19445     return SDValue();
19446
19447   // The right side has to be a 'trunc' or a constant vector.
19448   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19449   bool RHSConst = (isSplatVector(N1.getNode()) &&
19450                    isa<ConstantSDNode>(N1->getOperand(0)));
19451   if (!RHSTrunc && !RHSConst)
19452     return SDValue();
19453
19454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19455
19456   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19457     return SDValue();
19458
19459   // Set N0 and N1 to hold the inputs to the new wide operation.
19460   N0 = N0->getOperand(0);
19461   if (RHSConst) {
19462     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19463                      N1->getOperand(0));
19464     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19465     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19466   } else if (RHSTrunc) {
19467     N1 = N1->getOperand(0);
19468   }
19469
19470   // Generate the wide operation.
19471   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19472   unsigned Opcode = N->getOpcode();
19473   switch (Opcode) {
19474   case ISD::ANY_EXTEND:
19475     return Op;
19476   case ISD::ZERO_EXTEND: {
19477     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19478     APInt Mask = APInt::getAllOnesValue(InBits);
19479     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19480     return DAG.getNode(ISD::AND, DL, VT,
19481                        Op, DAG.getConstant(Mask, VT));
19482   }
19483   case ISD::SIGN_EXTEND:
19484     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19485                        Op, DAG.getValueType(NarrowVT));
19486   default:
19487     llvm_unreachable("Unexpected opcode");
19488   }
19489 }
19490
19491 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19492                                  TargetLowering::DAGCombinerInfo &DCI,
19493                                  const X86Subtarget *Subtarget) {
19494   EVT VT = N->getValueType(0);
19495   if (DCI.isBeforeLegalizeOps())
19496     return SDValue();
19497
19498   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19499   if (R.getNode())
19500     return R;
19501
19502   // Create BEXTR instructions
19503   // BEXTR is ((X >> imm) & (2**size-1))
19504   if (VT == MVT::i32 || VT == MVT::i64) {
19505     SDValue N0 = N->getOperand(0);
19506     SDValue N1 = N->getOperand(1);
19507     SDLoc DL(N);
19508
19509     // Check for BEXTR.
19510     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19511         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19512       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19513       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19514       if (MaskNode && ShiftNode) {
19515         uint64_t Mask = MaskNode->getZExtValue();
19516         uint64_t Shift = ShiftNode->getZExtValue();
19517         if (isMask_64(Mask)) {
19518           uint64_t MaskSize = CountPopulation_64(Mask);
19519           if (Shift + MaskSize <= VT.getSizeInBits())
19520             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19521                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19522         }
19523       }
19524     } // BEXTR
19525
19526     return SDValue();
19527   }
19528
19529   // Want to form ANDNP nodes:
19530   // 1) In the hopes of then easily combining them with OR and AND nodes
19531   //    to form PBLEND/PSIGN.
19532   // 2) To match ANDN packed intrinsics
19533   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19534     return SDValue();
19535
19536   SDValue N0 = N->getOperand(0);
19537   SDValue N1 = N->getOperand(1);
19538   SDLoc DL(N);
19539
19540   // Check LHS for vnot
19541   if (N0.getOpcode() == ISD::XOR &&
19542       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19543       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19544     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19545
19546   // Check RHS for vnot
19547   if (N1.getOpcode() == ISD::XOR &&
19548       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19549       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19550     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19551
19552   return SDValue();
19553 }
19554
19555 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19556                                 TargetLowering::DAGCombinerInfo &DCI,
19557                                 const X86Subtarget *Subtarget) {
19558   if (DCI.isBeforeLegalizeOps())
19559     return SDValue();
19560
19561   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19562   if (R.getNode())
19563     return R;
19564
19565   SDValue N0 = N->getOperand(0);
19566   SDValue N1 = N->getOperand(1);
19567   EVT VT = N->getValueType(0);
19568
19569   // look for psign/blend
19570   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19571     if (!Subtarget->hasSSSE3() ||
19572         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19573       return SDValue();
19574
19575     // Canonicalize pandn to RHS
19576     if (N0.getOpcode() == X86ISD::ANDNP)
19577       std::swap(N0, N1);
19578     // or (and (m, y), (pandn m, x))
19579     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19580       SDValue Mask = N1.getOperand(0);
19581       SDValue X    = N1.getOperand(1);
19582       SDValue Y;
19583       if (N0.getOperand(0) == Mask)
19584         Y = N0.getOperand(1);
19585       if (N0.getOperand(1) == Mask)
19586         Y = N0.getOperand(0);
19587
19588       // Check to see if the mask appeared in both the AND and ANDNP and
19589       if (!Y.getNode())
19590         return SDValue();
19591
19592       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19593       // Look through mask bitcast.
19594       if (Mask.getOpcode() == ISD::BITCAST)
19595         Mask = Mask.getOperand(0);
19596       if (X.getOpcode() == ISD::BITCAST)
19597         X = X.getOperand(0);
19598       if (Y.getOpcode() == ISD::BITCAST)
19599         Y = Y.getOperand(0);
19600
19601       EVT MaskVT = Mask.getValueType();
19602
19603       // Validate that the Mask operand is a vector sra node.
19604       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19605       // there is no psrai.b
19606       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19607       unsigned SraAmt = ~0;
19608       if (Mask.getOpcode() == ISD::SRA) {
19609         SDValue Amt = Mask.getOperand(1);
19610         if (isSplatVector(Amt.getNode())) {
19611           SDValue SclrAmt = Amt->getOperand(0);
19612           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19613             SraAmt = C->getZExtValue();
19614         }
19615       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19616         SDValue SraC = Mask.getOperand(1);
19617         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19618       }
19619       if ((SraAmt + 1) != EltBits)
19620         return SDValue();
19621
19622       SDLoc DL(N);
19623
19624       // Now we know we at least have a plendvb with the mask val.  See if
19625       // we can form a psignb/w/d.
19626       // psign = x.type == y.type == mask.type && y = sub(0, x);
19627       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19628           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19629           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19630         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19631                "Unsupported VT for PSIGN");
19632         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19633         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19634       }
19635       // PBLENDVB only available on SSE 4.1
19636       if (!Subtarget->hasSSE41())
19637         return SDValue();
19638
19639       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19640
19641       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19642       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19643       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19644       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19645       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19646     }
19647   }
19648
19649   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19650     return SDValue();
19651
19652   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19653   MachineFunction &MF = DAG.getMachineFunction();
19654   bool OptForSize = MF.getFunction()->getAttributes().
19655     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19656
19657   // SHLD/SHRD instructions have lower register pressure, but on some
19658   // platforms they have higher latency than the equivalent
19659   // series of shifts/or that would otherwise be generated.
19660   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19661   // have higher latencies and we are not optimizing for size.
19662   if (!OptForSize && Subtarget->isSHLDSlow())
19663     return SDValue();
19664
19665   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19666     std::swap(N0, N1);
19667   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19668     return SDValue();
19669   if (!N0.hasOneUse() || !N1.hasOneUse())
19670     return SDValue();
19671
19672   SDValue ShAmt0 = N0.getOperand(1);
19673   if (ShAmt0.getValueType() != MVT::i8)
19674     return SDValue();
19675   SDValue ShAmt1 = N1.getOperand(1);
19676   if (ShAmt1.getValueType() != MVT::i8)
19677     return SDValue();
19678   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19679     ShAmt0 = ShAmt0.getOperand(0);
19680   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19681     ShAmt1 = ShAmt1.getOperand(0);
19682
19683   SDLoc DL(N);
19684   unsigned Opc = X86ISD::SHLD;
19685   SDValue Op0 = N0.getOperand(0);
19686   SDValue Op1 = N1.getOperand(0);
19687   if (ShAmt0.getOpcode() == ISD::SUB) {
19688     Opc = X86ISD::SHRD;
19689     std::swap(Op0, Op1);
19690     std::swap(ShAmt0, ShAmt1);
19691   }
19692
19693   unsigned Bits = VT.getSizeInBits();
19694   if (ShAmt1.getOpcode() == ISD::SUB) {
19695     SDValue Sum = ShAmt1.getOperand(0);
19696     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19697       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19698       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19699         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19700       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19701         return DAG.getNode(Opc, DL, VT,
19702                            Op0, Op1,
19703                            DAG.getNode(ISD::TRUNCATE, DL,
19704                                        MVT::i8, ShAmt0));
19705     }
19706   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19707     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19708     if (ShAmt0C &&
19709         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19710       return DAG.getNode(Opc, DL, VT,
19711                          N0.getOperand(0), N1.getOperand(0),
19712                          DAG.getNode(ISD::TRUNCATE, DL,
19713                                        MVT::i8, ShAmt0));
19714   }
19715
19716   return SDValue();
19717 }
19718
19719 // Generate NEG and CMOV for integer abs.
19720 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19721   EVT VT = N->getValueType(0);
19722
19723   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19724   // 8-bit integer abs to NEG and CMOV.
19725   if (VT.isInteger() && VT.getSizeInBits() == 8)
19726     return SDValue();
19727
19728   SDValue N0 = N->getOperand(0);
19729   SDValue N1 = N->getOperand(1);
19730   SDLoc DL(N);
19731
19732   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19733   // and change it to SUB and CMOV.
19734   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19735       N0.getOpcode() == ISD::ADD &&
19736       N0.getOperand(1) == N1 &&
19737       N1.getOpcode() == ISD::SRA &&
19738       N1.getOperand(0) == N0.getOperand(0))
19739     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19740       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19741         // Generate SUB & CMOV.
19742         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19743                                   DAG.getConstant(0, VT), N0.getOperand(0));
19744
19745         SDValue Ops[] = { N0.getOperand(0), Neg,
19746                           DAG.getConstant(X86::COND_GE, MVT::i8),
19747                           SDValue(Neg.getNode(), 1) };
19748         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19749       }
19750   return SDValue();
19751 }
19752
19753 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19754 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19755                                  TargetLowering::DAGCombinerInfo &DCI,
19756                                  const X86Subtarget *Subtarget) {
19757   if (DCI.isBeforeLegalizeOps())
19758     return SDValue();
19759
19760   if (Subtarget->hasCMov()) {
19761     SDValue RV = performIntegerAbsCombine(N, DAG);
19762     if (RV.getNode())
19763       return RV;
19764   }
19765
19766   return SDValue();
19767 }
19768
19769 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19770 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19771                                   TargetLowering::DAGCombinerInfo &DCI,
19772                                   const X86Subtarget *Subtarget) {
19773   LoadSDNode *Ld = cast<LoadSDNode>(N);
19774   EVT RegVT = Ld->getValueType(0);
19775   EVT MemVT = Ld->getMemoryVT();
19776   SDLoc dl(Ld);
19777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19778   unsigned RegSz = RegVT.getSizeInBits();
19779
19780   // On Sandybridge unaligned 256bit loads are inefficient.
19781   ISD::LoadExtType Ext = Ld->getExtensionType();
19782   unsigned Alignment = Ld->getAlignment();
19783   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19784   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19785       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19786     unsigned NumElems = RegVT.getVectorNumElements();
19787     if (NumElems < 2)
19788       return SDValue();
19789
19790     SDValue Ptr = Ld->getBasePtr();
19791     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19792
19793     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19794                                   NumElems/2);
19795     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19796                                 Ld->getPointerInfo(), Ld->isVolatile(),
19797                                 Ld->isNonTemporal(), Ld->isInvariant(),
19798                                 Alignment);
19799     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19800     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19801                                 Ld->getPointerInfo(), Ld->isVolatile(),
19802                                 Ld->isNonTemporal(), Ld->isInvariant(),
19803                                 std::min(16U, Alignment));
19804     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19805                              Load1.getValue(1),
19806                              Load2.getValue(1));
19807
19808     SDValue NewVec = DAG.getUNDEF(RegVT);
19809     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19810     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19811     return DCI.CombineTo(N, NewVec, TF, true);
19812   }
19813
19814   // If this is a vector EXT Load then attempt to optimize it using a
19815   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19816   // expansion is still better than scalar code.
19817   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19818   // emit a shuffle and a arithmetic shift.
19819   // TODO: It is possible to support ZExt by zeroing the undef values
19820   // during the shuffle phase or after the shuffle.
19821   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19822       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19823     assert(MemVT != RegVT && "Cannot extend to the same type");
19824     assert(MemVT.isVector() && "Must load a vector from memory");
19825
19826     unsigned NumElems = RegVT.getVectorNumElements();
19827     unsigned MemSz = MemVT.getSizeInBits();
19828     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19829
19830     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19831       return SDValue();
19832
19833     // All sizes must be a power of two.
19834     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19835       return SDValue();
19836
19837     // Attempt to load the original value using scalar loads.
19838     // Find the largest scalar type that divides the total loaded size.
19839     MVT SclrLoadTy = MVT::i8;
19840     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19841          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19842       MVT Tp = (MVT::SimpleValueType)tp;
19843       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19844         SclrLoadTy = Tp;
19845       }
19846     }
19847
19848     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19849     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19850         (64 <= MemSz))
19851       SclrLoadTy = MVT::f64;
19852
19853     // Calculate the number of scalar loads that we need to perform
19854     // in order to load our vector from memory.
19855     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19856     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19857       return SDValue();
19858
19859     unsigned loadRegZize = RegSz;
19860     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19861       loadRegZize /= 2;
19862
19863     // Represent our vector as a sequence of elements which are the
19864     // largest scalar that we can load.
19865     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19866       loadRegZize/SclrLoadTy.getSizeInBits());
19867
19868     // Represent the data using the same element type that is stored in
19869     // memory. In practice, we ''widen'' MemVT.
19870     EVT WideVecVT =
19871           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19872                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19873
19874     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19875       "Invalid vector type");
19876
19877     // We can't shuffle using an illegal type.
19878     if (!TLI.isTypeLegal(WideVecVT))
19879       return SDValue();
19880
19881     SmallVector<SDValue, 8> Chains;
19882     SDValue Ptr = Ld->getBasePtr();
19883     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19884                                         TLI.getPointerTy());
19885     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19886
19887     for (unsigned i = 0; i < NumLoads; ++i) {
19888       // Perform a single load.
19889       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19890                                        Ptr, Ld->getPointerInfo(),
19891                                        Ld->isVolatile(), Ld->isNonTemporal(),
19892                                        Ld->isInvariant(), Ld->getAlignment());
19893       Chains.push_back(ScalarLoad.getValue(1));
19894       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19895       // another round of DAGCombining.
19896       if (i == 0)
19897         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19898       else
19899         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19900                           ScalarLoad, DAG.getIntPtrConstant(i));
19901
19902       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19903     }
19904
19905     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19906
19907     // Bitcast the loaded value to a vector of the original element type, in
19908     // the size of the target vector type.
19909     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19910     unsigned SizeRatio = RegSz/MemSz;
19911
19912     if (Ext == ISD::SEXTLOAD) {
19913       // If we have SSE4.1 we can directly emit a VSEXT node.
19914       if (Subtarget->hasSSE41()) {
19915         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19916         return DCI.CombineTo(N, Sext, TF, true);
19917       }
19918
19919       // Otherwise we'll shuffle the small elements in the high bits of the
19920       // larger type and perform an arithmetic shift. If the shift is not legal
19921       // it's better to scalarize.
19922       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19923         return SDValue();
19924
19925       // Redistribute the loaded elements into the different locations.
19926       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19927       for (unsigned i = 0; i != NumElems; ++i)
19928         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19929
19930       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19931                                            DAG.getUNDEF(WideVecVT),
19932                                            &ShuffleVec[0]);
19933
19934       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19935
19936       // Build the arithmetic shift.
19937       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19938                      MemVT.getVectorElementType().getSizeInBits();
19939       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19940                           DAG.getConstant(Amt, RegVT));
19941
19942       return DCI.CombineTo(N, Shuff, TF, true);
19943     }
19944
19945     // Redistribute the loaded elements into the different locations.
19946     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19947     for (unsigned i = 0; i != NumElems; ++i)
19948       ShuffleVec[i*SizeRatio] = i;
19949
19950     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19951                                          DAG.getUNDEF(WideVecVT),
19952                                          &ShuffleVec[0]);
19953
19954     // Bitcast to the requested type.
19955     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19956     // Replace the original load with the new sequence
19957     // and return the new chain.
19958     return DCI.CombineTo(N, Shuff, TF, true);
19959   }
19960
19961   return SDValue();
19962 }
19963
19964 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19965 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19966                                    const X86Subtarget *Subtarget) {
19967   StoreSDNode *St = cast<StoreSDNode>(N);
19968   EVT VT = St->getValue().getValueType();
19969   EVT StVT = St->getMemoryVT();
19970   SDLoc dl(St);
19971   SDValue StoredVal = St->getOperand(1);
19972   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19973
19974   // If we are saving a concatenation of two XMM registers, perform two stores.
19975   // On Sandy Bridge, 256-bit memory operations are executed by two
19976   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19977   // memory  operation.
19978   unsigned Alignment = St->getAlignment();
19979   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19980   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19981       StVT == VT && !IsAligned) {
19982     unsigned NumElems = VT.getVectorNumElements();
19983     if (NumElems < 2)
19984       return SDValue();
19985
19986     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19987     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19988
19989     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19990     SDValue Ptr0 = St->getBasePtr();
19991     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19992
19993     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19994                                 St->getPointerInfo(), St->isVolatile(),
19995                                 St->isNonTemporal(), Alignment);
19996     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19997                                 St->getPointerInfo(), St->isVolatile(),
19998                                 St->isNonTemporal(),
19999                                 std::min(16U, Alignment));
20000     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20001   }
20002
20003   // Optimize trunc store (of multiple scalars) to shuffle and store.
20004   // First, pack all of the elements in one place. Next, store to memory
20005   // in fewer chunks.
20006   if (St->isTruncatingStore() && VT.isVector()) {
20007     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20008     unsigned NumElems = VT.getVectorNumElements();
20009     assert(StVT != VT && "Cannot truncate to the same type");
20010     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20011     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20012
20013     // From, To sizes and ElemCount must be pow of two
20014     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20015     // We are going to use the original vector elt for storing.
20016     // Accumulated smaller vector elements must be a multiple of the store size.
20017     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20018
20019     unsigned SizeRatio  = FromSz / ToSz;
20020
20021     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20022
20023     // Create a type on which we perform the shuffle
20024     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20025             StVT.getScalarType(), NumElems*SizeRatio);
20026
20027     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20028
20029     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20030     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20031     for (unsigned i = 0; i != NumElems; ++i)
20032       ShuffleVec[i] = i * SizeRatio;
20033
20034     // Can't shuffle using an illegal type.
20035     if (!TLI.isTypeLegal(WideVecVT))
20036       return SDValue();
20037
20038     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20039                                          DAG.getUNDEF(WideVecVT),
20040                                          &ShuffleVec[0]);
20041     // At this point all of the data is stored at the bottom of the
20042     // register. We now need to save it to mem.
20043
20044     // Find the largest store unit
20045     MVT StoreType = MVT::i8;
20046     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20047          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20048       MVT Tp = (MVT::SimpleValueType)tp;
20049       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20050         StoreType = Tp;
20051     }
20052
20053     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20054     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20055         (64 <= NumElems * ToSz))
20056       StoreType = MVT::f64;
20057
20058     // Bitcast the original vector into a vector of store-size units
20059     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20060             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20061     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20062     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20063     SmallVector<SDValue, 8> Chains;
20064     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20065                                         TLI.getPointerTy());
20066     SDValue Ptr = St->getBasePtr();
20067
20068     // Perform one or more big stores into memory.
20069     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20070       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20071                                    StoreType, ShuffWide,
20072                                    DAG.getIntPtrConstant(i));
20073       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20074                                 St->getPointerInfo(), St->isVolatile(),
20075                                 St->isNonTemporal(), St->getAlignment());
20076       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20077       Chains.push_back(Ch);
20078     }
20079
20080     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20081   }
20082
20083   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
20084   // the FP state in cases where an emms may be missing.
20085   // A preferable solution to the general problem is to figure out the right
20086   // places to insert EMMS.  This qualifies as a quick hack.
20087
20088   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
20089   if (VT.getSizeInBits() != 64)
20090     return SDValue();
20091
20092   const Function *F = DAG.getMachineFunction().getFunction();
20093   bool NoImplicitFloatOps = F->getAttributes().
20094     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20095   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20096                      && Subtarget->hasSSE2();
20097   if ((VT.isVector() ||
20098        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20099       isa<LoadSDNode>(St->getValue()) &&
20100       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20101       St->getChain().hasOneUse() && !St->isVolatile()) {
20102     SDNode* LdVal = St->getValue().getNode();
20103     LoadSDNode *Ld = nullptr;
20104     int TokenFactorIndex = -1;
20105     SmallVector<SDValue, 8> Ops;
20106     SDNode* ChainVal = St->getChain().getNode();
20107     // Must be a store of a load.  We currently handle two cases:  the load
20108     // is a direct child, and it's under an intervening TokenFactor.  It is
20109     // possible to dig deeper under nested TokenFactors.
20110     if (ChainVal == LdVal)
20111       Ld = cast<LoadSDNode>(St->getChain());
20112     else if (St->getValue().hasOneUse() &&
20113              ChainVal->getOpcode() == ISD::TokenFactor) {
20114       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20115         if (ChainVal->getOperand(i).getNode() == LdVal) {
20116           TokenFactorIndex = i;
20117           Ld = cast<LoadSDNode>(St->getValue());
20118         } else
20119           Ops.push_back(ChainVal->getOperand(i));
20120       }
20121     }
20122
20123     if (!Ld || !ISD::isNormalLoad(Ld))
20124       return SDValue();
20125
20126     // If this is not the MMX case, i.e. we are just turning i64 load/store
20127     // into f64 load/store, avoid the transformation if there are multiple
20128     // uses of the loaded value.
20129     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20130       return SDValue();
20131
20132     SDLoc LdDL(Ld);
20133     SDLoc StDL(N);
20134     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20135     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20136     // pair instead.
20137     if (Subtarget->is64Bit() || F64IsLegal) {
20138       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20139       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20140                                   Ld->getPointerInfo(), Ld->isVolatile(),
20141                                   Ld->isNonTemporal(), Ld->isInvariant(),
20142                                   Ld->getAlignment());
20143       SDValue NewChain = NewLd.getValue(1);
20144       if (TokenFactorIndex != -1) {
20145         Ops.push_back(NewChain);
20146         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20147       }
20148       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20149                           St->getPointerInfo(),
20150                           St->isVolatile(), St->isNonTemporal(),
20151                           St->getAlignment());
20152     }
20153
20154     // Otherwise, lower to two pairs of 32-bit loads / stores.
20155     SDValue LoAddr = Ld->getBasePtr();
20156     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20157                                  DAG.getConstant(4, MVT::i32));
20158
20159     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20160                                Ld->getPointerInfo(),
20161                                Ld->isVolatile(), Ld->isNonTemporal(),
20162                                Ld->isInvariant(), Ld->getAlignment());
20163     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20164                                Ld->getPointerInfo().getWithOffset(4),
20165                                Ld->isVolatile(), Ld->isNonTemporal(),
20166                                Ld->isInvariant(),
20167                                MinAlign(Ld->getAlignment(), 4));
20168
20169     SDValue NewChain = LoLd.getValue(1);
20170     if (TokenFactorIndex != -1) {
20171       Ops.push_back(LoLd);
20172       Ops.push_back(HiLd);
20173       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20174     }
20175
20176     LoAddr = St->getBasePtr();
20177     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20178                          DAG.getConstant(4, MVT::i32));
20179
20180     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20181                                 St->getPointerInfo(),
20182                                 St->isVolatile(), St->isNonTemporal(),
20183                                 St->getAlignment());
20184     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20185                                 St->getPointerInfo().getWithOffset(4),
20186                                 St->isVolatile(),
20187                                 St->isNonTemporal(),
20188                                 MinAlign(St->getAlignment(), 4));
20189     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20190   }
20191   return SDValue();
20192 }
20193
20194 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20195 /// and return the operands for the horizontal operation in LHS and RHS.  A
20196 /// horizontal operation performs the binary operation on successive elements
20197 /// of its first operand, then on successive elements of its second operand,
20198 /// returning the resulting values in a vector.  For example, if
20199 ///   A = < float a0, float a1, float a2, float a3 >
20200 /// and
20201 ///   B = < float b0, float b1, float b2, float b3 >
20202 /// then the result of doing a horizontal operation on A and B is
20203 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20204 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20205 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20206 /// set to A, RHS to B, and the routine returns 'true'.
20207 /// Note that the binary operation should have the property that if one of the
20208 /// operands is UNDEF then the result is UNDEF.
20209 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20210   // Look for the following pattern: if
20211   //   A = < float a0, float a1, float a2, float a3 >
20212   //   B = < float b0, float b1, float b2, float b3 >
20213   // and
20214   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20215   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20216   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20217   // which is A horizontal-op B.
20218
20219   // At least one of the operands should be a vector shuffle.
20220   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20221       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20222     return false;
20223
20224   MVT VT = LHS.getSimpleValueType();
20225
20226   assert((VT.is128BitVector() || VT.is256BitVector()) &&
20227          "Unsupported vector type for horizontal add/sub");
20228
20229   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20230   // operate independently on 128-bit lanes.
20231   unsigned NumElts = VT.getVectorNumElements();
20232   unsigned NumLanes = VT.getSizeInBits()/128;
20233   unsigned NumLaneElts = NumElts / NumLanes;
20234   assert((NumLaneElts % 2 == 0) &&
20235          "Vector type should have an even number of elements in each lane");
20236   unsigned HalfLaneElts = NumLaneElts/2;
20237
20238   // View LHS in the form
20239   //   LHS = VECTOR_SHUFFLE A, B, LMask
20240   // If LHS is not a shuffle then pretend it is the shuffle
20241   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20242   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20243   // type VT.
20244   SDValue A, B;
20245   SmallVector<int, 16> LMask(NumElts);
20246   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20247     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20248       A = LHS.getOperand(0);
20249     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20250       B = LHS.getOperand(1);
20251     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20252     std::copy(Mask.begin(), Mask.end(), LMask.begin());
20253   } else {
20254     if (LHS.getOpcode() != ISD::UNDEF)
20255       A = LHS;
20256     for (unsigned i = 0; i != NumElts; ++i)
20257       LMask[i] = i;
20258   }
20259
20260   // Likewise, view RHS in the form
20261   //   RHS = VECTOR_SHUFFLE C, D, RMask
20262   SDValue C, D;
20263   SmallVector<int, 16> RMask(NumElts);
20264   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20265     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20266       C = RHS.getOperand(0);
20267     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20268       D = RHS.getOperand(1);
20269     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20270     std::copy(Mask.begin(), Mask.end(), RMask.begin());
20271   } else {
20272     if (RHS.getOpcode() != ISD::UNDEF)
20273       C = RHS;
20274     for (unsigned i = 0; i != NumElts; ++i)
20275       RMask[i] = i;
20276   }
20277
20278   // Check that the shuffles are both shuffling the same vectors.
20279   if (!(A == C && B == D) && !(A == D && B == C))
20280     return false;
20281
20282   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20283   if (!A.getNode() && !B.getNode())
20284     return false;
20285
20286   // If A and B occur in reverse order in RHS, then "swap" them (which means
20287   // rewriting the mask).
20288   if (A != C)
20289     CommuteVectorShuffleMask(RMask, NumElts);
20290
20291   // At this point LHS and RHS are equivalent to
20292   //   LHS = VECTOR_SHUFFLE A, B, LMask
20293   //   RHS = VECTOR_SHUFFLE A, B, RMask
20294   // Check that the masks correspond to performing a horizontal operation.
20295   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20296     for (unsigned i = 0; i != NumLaneElts; ++i) {
20297       int LIdx = LMask[i+l], RIdx = RMask[i+l];
20298
20299       // Ignore any UNDEF components.
20300       if (LIdx < 0 || RIdx < 0 ||
20301           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20302           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20303         continue;
20304
20305       // Check that successive elements are being operated on.  If not, this is
20306       // not a horizontal operation.
20307       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20308       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20309       if (!(LIdx == Index && RIdx == Index + 1) &&
20310           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20311         return false;
20312     }
20313   }
20314
20315   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20316   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20317   return true;
20318 }
20319
20320 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20321 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20322                                   const X86Subtarget *Subtarget) {
20323   EVT VT = N->getValueType(0);
20324   SDValue LHS = N->getOperand(0);
20325   SDValue RHS = N->getOperand(1);
20326
20327   // Try to synthesize horizontal adds from adds of shuffles.
20328   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20329        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20330       isHorizontalBinOp(LHS, RHS, true))
20331     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20332   return SDValue();
20333 }
20334
20335 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20336 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20337                                   const X86Subtarget *Subtarget) {
20338   EVT VT = N->getValueType(0);
20339   SDValue LHS = N->getOperand(0);
20340   SDValue RHS = N->getOperand(1);
20341
20342   // Try to synthesize horizontal subs from subs of shuffles.
20343   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20344        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20345       isHorizontalBinOp(LHS, RHS, false))
20346     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20347   return SDValue();
20348 }
20349
20350 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20351 /// X86ISD::FXOR nodes.
20352 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20353   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20354   // F[X]OR(0.0, x) -> x
20355   // F[X]OR(x, 0.0) -> x
20356   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20357     if (C->getValueAPF().isPosZero())
20358       return N->getOperand(1);
20359   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20360     if (C->getValueAPF().isPosZero())
20361       return N->getOperand(0);
20362   return SDValue();
20363 }
20364
20365 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20366 /// X86ISD::FMAX nodes.
20367 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20368   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20369
20370   // Only perform optimizations if UnsafeMath is used.
20371   if (!DAG.getTarget().Options.UnsafeFPMath)
20372     return SDValue();
20373
20374   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20375   // into FMINC and FMAXC, which are Commutative operations.
20376   unsigned NewOp = 0;
20377   switch (N->getOpcode()) {
20378     default: llvm_unreachable("unknown opcode");
20379     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20380     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20381   }
20382
20383   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20384                      N->getOperand(0), N->getOperand(1));
20385 }
20386
20387 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20388 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20389   // FAND(0.0, x) -> 0.0
20390   // FAND(x, 0.0) -> 0.0
20391   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20392     if (C->getValueAPF().isPosZero())
20393       return N->getOperand(0);
20394   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20395     if (C->getValueAPF().isPosZero())
20396       return N->getOperand(1);
20397   return SDValue();
20398 }
20399
20400 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20401 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20402   // FANDN(x, 0.0) -> 0.0
20403   // FANDN(0.0, x) -> x
20404   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20405     if (C->getValueAPF().isPosZero())
20406       return N->getOperand(1);
20407   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20408     if (C->getValueAPF().isPosZero())
20409       return N->getOperand(1);
20410   return SDValue();
20411 }
20412
20413 static SDValue PerformBTCombine(SDNode *N,
20414                                 SelectionDAG &DAG,
20415                                 TargetLowering::DAGCombinerInfo &DCI) {
20416   // BT ignores high bits in the bit index operand.
20417   SDValue Op1 = N->getOperand(1);
20418   if (Op1.hasOneUse()) {
20419     unsigned BitWidth = Op1.getValueSizeInBits();
20420     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20421     APInt KnownZero, KnownOne;
20422     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20423                                           !DCI.isBeforeLegalizeOps());
20424     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20425     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20426         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20427       DCI.CommitTargetLoweringOpt(TLO);
20428   }
20429   return SDValue();
20430 }
20431
20432 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20433   SDValue Op = N->getOperand(0);
20434   if (Op.getOpcode() == ISD::BITCAST)
20435     Op = Op.getOperand(0);
20436   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20437   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20438       VT.getVectorElementType().getSizeInBits() ==
20439       OpVT.getVectorElementType().getSizeInBits()) {
20440     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20441   }
20442   return SDValue();
20443 }
20444
20445 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20446                                                const X86Subtarget *Subtarget) {
20447   EVT VT = N->getValueType(0);
20448   if (!VT.isVector())
20449     return SDValue();
20450
20451   SDValue N0 = N->getOperand(0);
20452   SDValue N1 = N->getOperand(1);
20453   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20454   SDLoc dl(N);
20455
20456   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20457   // both SSE and AVX2 since there is no sign-extended shift right
20458   // operation on a vector with 64-bit elements.
20459   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20460   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20461   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20462       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20463     SDValue N00 = N0.getOperand(0);
20464
20465     // EXTLOAD has a better solution on AVX2,
20466     // it may be replaced with X86ISD::VSEXT node.
20467     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20468       if (!ISD::isNormalLoad(N00.getNode()))
20469         return SDValue();
20470
20471     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20472         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20473                                   N00, N1);
20474       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20475     }
20476   }
20477   return SDValue();
20478 }
20479
20480 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20481                                   TargetLowering::DAGCombinerInfo &DCI,
20482                                   const X86Subtarget *Subtarget) {
20483   if (!DCI.isBeforeLegalizeOps())
20484     return SDValue();
20485
20486   if (!Subtarget->hasFp256())
20487     return SDValue();
20488
20489   EVT VT = N->getValueType(0);
20490   if (VT.isVector() && VT.getSizeInBits() == 256) {
20491     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20492     if (R.getNode())
20493       return R;
20494   }
20495
20496   return SDValue();
20497 }
20498
20499 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20500                                  const X86Subtarget* Subtarget) {
20501   SDLoc dl(N);
20502   EVT VT = N->getValueType(0);
20503
20504   // Let legalize expand this if it isn't a legal type yet.
20505   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20506     return SDValue();
20507
20508   EVT ScalarVT = VT.getScalarType();
20509   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20510       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20511     return SDValue();
20512
20513   SDValue A = N->getOperand(0);
20514   SDValue B = N->getOperand(1);
20515   SDValue C = N->getOperand(2);
20516
20517   bool NegA = (A.getOpcode() == ISD::FNEG);
20518   bool NegB = (B.getOpcode() == ISD::FNEG);
20519   bool NegC = (C.getOpcode() == ISD::FNEG);
20520
20521   // Negative multiplication when NegA xor NegB
20522   bool NegMul = (NegA != NegB);
20523   if (NegA)
20524     A = A.getOperand(0);
20525   if (NegB)
20526     B = B.getOperand(0);
20527   if (NegC)
20528     C = C.getOperand(0);
20529
20530   unsigned Opcode;
20531   if (!NegMul)
20532     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20533   else
20534     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20535
20536   return DAG.getNode(Opcode, dl, VT, A, B, C);
20537 }
20538
20539 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20540                                   TargetLowering::DAGCombinerInfo &DCI,
20541                                   const X86Subtarget *Subtarget) {
20542   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20543   //           (and (i32 x86isd::setcc_carry), 1)
20544   // This eliminates the zext. This transformation is necessary because
20545   // ISD::SETCC is always legalized to i8.
20546   SDLoc dl(N);
20547   SDValue N0 = N->getOperand(0);
20548   EVT VT = N->getValueType(0);
20549
20550   if (N0.getOpcode() == ISD::AND &&
20551       N0.hasOneUse() &&
20552       N0.getOperand(0).hasOneUse()) {
20553     SDValue N00 = N0.getOperand(0);
20554     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20555       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20556       if (!C || C->getZExtValue() != 1)
20557         return SDValue();
20558       return DAG.getNode(ISD::AND, dl, VT,
20559                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20560                                      N00.getOperand(0), N00.getOperand(1)),
20561                          DAG.getConstant(1, VT));
20562     }
20563   }
20564
20565   if (N0.getOpcode() == ISD::TRUNCATE &&
20566       N0.hasOneUse() &&
20567       N0.getOperand(0).hasOneUse()) {
20568     SDValue N00 = N0.getOperand(0);
20569     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20570       return DAG.getNode(ISD::AND, dl, VT,
20571                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20572                                      N00.getOperand(0), N00.getOperand(1)),
20573                          DAG.getConstant(1, VT));
20574     }
20575   }
20576   if (VT.is256BitVector()) {
20577     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20578     if (R.getNode())
20579       return R;
20580   }
20581
20582   return SDValue();
20583 }
20584
20585 // Optimize x == -y --> x+y == 0
20586 //          x != -y --> x+y != 0
20587 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20588                                       const X86Subtarget* Subtarget) {
20589   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20590   SDValue LHS = N->getOperand(0);
20591   SDValue RHS = N->getOperand(1);
20592   EVT VT = N->getValueType(0);
20593   SDLoc DL(N);
20594
20595   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20596     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20597       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20598         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20599                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20600         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20601                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20602       }
20603   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20604     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20605       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20606         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20607                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20608         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20609                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20610       }
20611
20612   if (VT.getScalarType() == MVT::i1) {
20613     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20614       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20615     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20616     if (!IsSEXT0 && !IsVZero0)
20617       return SDValue();
20618     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20619       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20620     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20621
20622     if (!IsSEXT1 && !IsVZero1)
20623       return SDValue();
20624
20625     if (IsSEXT0 && IsVZero1) {
20626       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20627       if (CC == ISD::SETEQ)
20628         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20629       return LHS.getOperand(0);
20630     }
20631     if (IsSEXT1 && IsVZero0) {
20632       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20633       if (CC == ISD::SETEQ)
20634         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20635       return RHS.getOperand(0);
20636     }
20637   }
20638
20639   return SDValue();
20640 }
20641
20642 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20643                                       const X86Subtarget *Subtarget) {
20644   SDLoc dl(N);
20645   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20646   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20647          "X86insertps is only defined for v4x32");
20648
20649   SDValue Ld = N->getOperand(1);
20650   if (MayFoldLoad(Ld)) {
20651     // Extract the countS bits from the immediate so we can get the proper
20652     // address when narrowing the vector load to a specific element.
20653     // When the second source op is a memory address, interps doesn't use
20654     // countS and just gets an f32 from that address.
20655     unsigned DestIndex =
20656         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20657     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20658   } else
20659     return SDValue();
20660
20661   // Create this as a scalar to vector to match the instruction pattern.
20662   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20663   // countS bits are ignored when loading from memory on insertps, which
20664   // means we don't need to explicitly set them to 0.
20665   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20666                      LoadScalarToVector, N->getOperand(2));
20667 }
20668
20669 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20670 // as "sbb reg,reg", since it can be extended without zext and produces
20671 // an all-ones bit which is more useful than 0/1 in some cases.
20672 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20673                                MVT VT) {
20674   if (VT == MVT::i8)
20675     return DAG.getNode(ISD::AND, DL, VT,
20676                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20677                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20678                        DAG.getConstant(1, VT));
20679   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20680   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20681                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20682                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20683 }
20684
20685 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20686 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20687                                    TargetLowering::DAGCombinerInfo &DCI,
20688                                    const X86Subtarget *Subtarget) {
20689   SDLoc DL(N);
20690   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20691   SDValue EFLAGS = N->getOperand(1);
20692
20693   if (CC == X86::COND_A) {
20694     // Try to convert COND_A into COND_B in an attempt to facilitate
20695     // materializing "setb reg".
20696     //
20697     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20698     // cannot take an immediate as its first operand.
20699     //
20700     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20701         EFLAGS.getValueType().isInteger() &&
20702         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20703       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20704                                    EFLAGS.getNode()->getVTList(),
20705                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20706       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20707       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20708     }
20709   }
20710
20711   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20712   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20713   // cases.
20714   if (CC == X86::COND_B)
20715     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20716
20717   SDValue Flags;
20718
20719   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20720   if (Flags.getNode()) {
20721     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20722     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20723   }
20724
20725   return SDValue();
20726 }
20727
20728 // Optimize branch condition evaluation.
20729 //
20730 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20731                                     TargetLowering::DAGCombinerInfo &DCI,
20732                                     const X86Subtarget *Subtarget) {
20733   SDLoc DL(N);
20734   SDValue Chain = N->getOperand(0);
20735   SDValue Dest = N->getOperand(1);
20736   SDValue EFLAGS = N->getOperand(3);
20737   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20738
20739   SDValue Flags;
20740
20741   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20742   if (Flags.getNode()) {
20743     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20744     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20745                        Flags);
20746   }
20747
20748   return SDValue();
20749 }
20750
20751 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20752                                         const X86TargetLowering *XTLI) {
20753   SDValue Op0 = N->getOperand(0);
20754   EVT InVT = Op0->getValueType(0);
20755
20756   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20757   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20758     SDLoc dl(N);
20759     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20760     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20761     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20762   }
20763
20764   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20765   // a 32-bit target where SSE doesn't support i64->FP operations.
20766   if (Op0.getOpcode() == ISD::LOAD) {
20767     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20768     EVT VT = Ld->getValueType(0);
20769     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20770         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20771         !XTLI->getSubtarget()->is64Bit() &&
20772         VT == MVT::i64) {
20773       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20774                                           Ld->getChain(), Op0, DAG);
20775       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20776       return FILDChain;
20777     }
20778   }
20779   return SDValue();
20780 }
20781
20782 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20783 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20784                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20785   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20786   // the result is either zero or one (depending on the input carry bit).
20787   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20788   if (X86::isZeroNode(N->getOperand(0)) &&
20789       X86::isZeroNode(N->getOperand(1)) &&
20790       // We don't have a good way to replace an EFLAGS use, so only do this when
20791       // dead right now.
20792       SDValue(N, 1).use_empty()) {
20793     SDLoc DL(N);
20794     EVT VT = N->getValueType(0);
20795     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20796     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20797                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20798                                            DAG.getConstant(X86::COND_B,MVT::i8),
20799                                            N->getOperand(2)),
20800                                DAG.getConstant(1, VT));
20801     return DCI.CombineTo(N, Res1, CarryOut);
20802   }
20803
20804   return SDValue();
20805 }
20806
20807 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20808 //      (add Y, (setne X, 0)) -> sbb -1, Y
20809 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20810 //      (sub (setne X, 0), Y) -> adc -1, Y
20811 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20812   SDLoc DL(N);
20813
20814   // Look through ZExts.
20815   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20816   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20817     return SDValue();
20818
20819   SDValue SetCC = Ext.getOperand(0);
20820   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20821     return SDValue();
20822
20823   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20824   if (CC != X86::COND_E && CC != X86::COND_NE)
20825     return SDValue();
20826
20827   SDValue Cmp = SetCC.getOperand(1);
20828   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20829       !X86::isZeroNode(Cmp.getOperand(1)) ||
20830       !Cmp.getOperand(0).getValueType().isInteger())
20831     return SDValue();
20832
20833   SDValue CmpOp0 = Cmp.getOperand(0);
20834   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20835                                DAG.getConstant(1, CmpOp0.getValueType()));
20836
20837   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20838   if (CC == X86::COND_NE)
20839     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20840                        DL, OtherVal.getValueType(), OtherVal,
20841                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20842   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20843                      DL, OtherVal.getValueType(), OtherVal,
20844                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20845 }
20846
20847 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20848 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20849                                  const X86Subtarget *Subtarget) {
20850   EVT VT = N->getValueType(0);
20851   SDValue Op0 = N->getOperand(0);
20852   SDValue Op1 = N->getOperand(1);
20853
20854   // Try to synthesize horizontal adds from adds of shuffles.
20855   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20856        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20857       isHorizontalBinOp(Op0, Op1, true))
20858     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20859
20860   return OptimizeConditionalInDecrement(N, DAG);
20861 }
20862
20863 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20864                                  const X86Subtarget *Subtarget) {
20865   SDValue Op0 = N->getOperand(0);
20866   SDValue Op1 = N->getOperand(1);
20867
20868   // X86 can't encode an immediate LHS of a sub. See if we can push the
20869   // negation into a preceding instruction.
20870   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20871     // If the RHS of the sub is a XOR with one use and a constant, invert the
20872     // immediate. Then add one to the LHS of the sub so we can turn
20873     // X-Y -> X+~Y+1, saving one register.
20874     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20875         isa<ConstantSDNode>(Op1.getOperand(1))) {
20876       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20877       EVT VT = Op0.getValueType();
20878       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20879                                    Op1.getOperand(0),
20880                                    DAG.getConstant(~XorC, VT));
20881       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20882                          DAG.getConstant(C->getAPIntValue()+1, VT));
20883     }
20884   }
20885
20886   // Try to synthesize horizontal adds from adds of shuffles.
20887   EVT VT = N->getValueType(0);
20888   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20889        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20890       isHorizontalBinOp(Op0, Op1, true))
20891     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20892
20893   return OptimizeConditionalInDecrement(N, DAG);
20894 }
20895
20896 /// performVZEXTCombine - Performs build vector combines
20897 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20898                                         TargetLowering::DAGCombinerInfo &DCI,
20899                                         const X86Subtarget *Subtarget) {
20900   // (vzext (bitcast (vzext (x)) -> (vzext x)
20901   SDValue In = N->getOperand(0);
20902   while (In.getOpcode() == ISD::BITCAST)
20903     In = In.getOperand(0);
20904
20905   if (In.getOpcode() != X86ISD::VZEXT)
20906     return SDValue();
20907
20908   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20909                      In.getOperand(0));
20910 }
20911
20912 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20913                                              DAGCombinerInfo &DCI) const {
20914   SelectionDAG &DAG = DCI.DAG;
20915   switch (N->getOpcode()) {
20916   default: break;
20917   case ISD::EXTRACT_VECTOR_ELT:
20918     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20919   case ISD::VSELECT:
20920   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20921   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20922   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20923   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20924   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20925   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20926   case ISD::SHL:
20927   case ISD::SRA:
20928   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20929   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20930   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20931   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20932   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20933   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20934   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20935   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20936   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20937   case X86ISD::FXOR:
20938   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20939   case X86ISD::FMIN:
20940   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20941   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20942   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20943   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20944   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20945   case ISD::ANY_EXTEND:
20946   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20947   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20948   case ISD::SIGN_EXTEND_INREG:
20949     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20950   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20951   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20952   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20953   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20954   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20955   case X86ISD::SHUFP:       // Handle all target specific shuffles
20956   case X86ISD::PALIGNR:
20957   case X86ISD::UNPCKH:
20958   case X86ISD::UNPCKL:
20959   case X86ISD::MOVHLPS:
20960   case X86ISD::MOVLHPS:
20961   case X86ISD::PSHUFD:
20962   case X86ISD::PSHUFHW:
20963   case X86ISD::PSHUFLW:
20964   case X86ISD::MOVSS:
20965   case X86ISD::MOVSD:
20966   case X86ISD::VPERMILP:
20967   case X86ISD::VPERM2X128:
20968   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20969   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20970   case ISD::INTRINSIC_WO_CHAIN:
20971     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20972   case X86ISD::INSERTPS:
20973     return PerformINSERTPSCombine(N, DAG, Subtarget);
20974   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
20975   }
20976
20977   return SDValue();
20978 }
20979
20980 /// isTypeDesirableForOp - Return true if the target has native support for
20981 /// the specified value type and it is 'desirable' to use the type for the
20982 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20983 /// instruction encodings are longer and some i16 instructions are slow.
20984 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20985   if (!isTypeLegal(VT))
20986     return false;
20987   if (VT != MVT::i16)
20988     return true;
20989
20990   switch (Opc) {
20991   default:
20992     return true;
20993   case ISD::LOAD:
20994   case ISD::SIGN_EXTEND:
20995   case ISD::ZERO_EXTEND:
20996   case ISD::ANY_EXTEND:
20997   case ISD::SHL:
20998   case ISD::SRL:
20999   case ISD::SUB:
21000   case ISD::ADD:
21001   case ISD::MUL:
21002   case ISD::AND:
21003   case ISD::OR:
21004   case ISD::XOR:
21005     return false;
21006   }
21007 }
21008
21009 /// IsDesirableToPromoteOp - This method query the target whether it is
21010 /// beneficial for dag combiner to promote the specified node. If true, it
21011 /// should return the desired promotion type by reference.
21012 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21013   EVT VT = Op.getValueType();
21014   if (VT != MVT::i16)
21015     return false;
21016
21017   bool Promote = false;
21018   bool Commute = false;
21019   switch (Op.getOpcode()) {
21020   default: break;
21021   case ISD::LOAD: {
21022     LoadSDNode *LD = cast<LoadSDNode>(Op);
21023     // If the non-extending load has a single use and it's not live out, then it
21024     // might be folded.
21025     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21026                                                      Op.hasOneUse()*/) {
21027       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21028              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21029         // The only case where we'd want to promote LOAD (rather then it being
21030         // promoted as an operand is when it's only use is liveout.
21031         if (UI->getOpcode() != ISD::CopyToReg)
21032           return false;
21033       }
21034     }
21035     Promote = true;
21036     break;
21037   }
21038   case ISD::SIGN_EXTEND:
21039   case ISD::ZERO_EXTEND:
21040   case ISD::ANY_EXTEND:
21041     Promote = true;
21042     break;
21043   case ISD::SHL:
21044   case ISD::SRL: {
21045     SDValue N0 = Op.getOperand(0);
21046     // Look out for (store (shl (load), x)).
21047     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21048       return false;
21049     Promote = true;
21050     break;
21051   }
21052   case ISD::ADD:
21053   case ISD::MUL:
21054   case ISD::AND:
21055   case ISD::OR:
21056   case ISD::XOR:
21057     Commute = true;
21058     // fallthrough
21059   case ISD::SUB: {
21060     SDValue N0 = Op.getOperand(0);
21061     SDValue N1 = Op.getOperand(1);
21062     if (!Commute && MayFoldLoad(N1))
21063       return false;
21064     // Avoid disabling potential load folding opportunities.
21065     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21066       return false;
21067     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21068       return false;
21069     Promote = true;
21070   }
21071   }
21072
21073   PVT = MVT::i32;
21074   return Promote;
21075 }
21076
21077 //===----------------------------------------------------------------------===//
21078 //                           X86 Inline Assembly Support
21079 //===----------------------------------------------------------------------===//
21080
21081 namespace {
21082   // Helper to match a string separated by whitespace.
21083   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21084     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21085
21086     for (unsigned i = 0, e = args.size(); i != e; ++i) {
21087       StringRef piece(*args[i]);
21088       if (!s.startswith(piece)) // Check if the piece matches.
21089         return false;
21090
21091       s = s.substr(piece.size());
21092       StringRef::size_type pos = s.find_first_not_of(" \t");
21093       if (pos == 0) // We matched a prefix.
21094         return false;
21095
21096       s = s.substr(pos);
21097     }
21098
21099     return s.empty();
21100   }
21101   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21102 }
21103
21104 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21105
21106   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21107     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21108         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21109         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21110
21111       if (AsmPieces.size() == 3)
21112         return true;
21113       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21114         return true;
21115     }
21116   }
21117   return false;
21118 }
21119
21120 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21121   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21122
21123   std::string AsmStr = IA->getAsmString();
21124
21125   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21126   if (!Ty || Ty->getBitWidth() % 16 != 0)
21127     return false;
21128
21129   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21130   SmallVector<StringRef, 4> AsmPieces;
21131   SplitString(AsmStr, AsmPieces, ";\n");
21132
21133   switch (AsmPieces.size()) {
21134   default: return false;
21135   case 1:
21136     // FIXME: this should verify that we are targeting a 486 or better.  If not,
21137     // we will turn this bswap into something that will be lowered to logical
21138     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
21139     // lower so don't worry about this.
21140     // bswap $0
21141     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21142         matchAsm(AsmPieces[0], "bswapl", "$0") ||
21143         matchAsm(AsmPieces[0], "bswapq", "$0") ||
21144         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21145         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21146         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21147       // No need to check constraints, nothing other than the equivalent of
21148       // "=r,0" would be valid here.
21149       return IntrinsicLowering::LowerToByteSwap(CI);
21150     }
21151
21152     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
21153     if (CI->getType()->isIntegerTy(16) &&
21154         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21155         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21156          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21157       AsmPieces.clear();
21158       const std::string &ConstraintsStr = IA->getConstraintString();
21159       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21160       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21161       if (clobbersFlagRegisters(AsmPieces))
21162         return IntrinsicLowering::LowerToByteSwap(CI);
21163     }
21164     break;
21165   case 3:
21166     if (CI->getType()->isIntegerTy(32) &&
21167         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21168         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21169         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21170         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21171       AsmPieces.clear();
21172       const std::string &ConstraintsStr = IA->getConstraintString();
21173       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21174       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21175       if (clobbersFlagRegisters(AsmPieces))
21176         return IntrinsicLowering::LowerToByteSwap(CI);
21177     }
21178
21179     if (CI->getType()->isIntegerTy(64)) {
21180       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21181       if (Constraints.size() >= 2 &&
21182           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21183           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21184         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
21185         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21186             matchAsm(AsmPieces[1], "bswap", "%edx") &&
21187             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21188           return IntrinsicLowering::LowerToByteSwap(CI);
21189       }
21190     }
21191     break;
21192   }
21193   return false;
21194 }
21195
21196 /// getConstraintType - Given a constraint letter, return the type of
21197 /// constraint it is for this target.
21198 X86TargetLowering::ConstraintType
21199 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21200   if (Constraint.size() == 1) {
21201     switch (Constraint[0]) {
21202     case 'R':
21203     case 'q':
21204     case 'Q':
21205     case 'f':
21206     case 't':
21207     case 'u':
21208     case 'y':
21209     case 'x':
21210     case 'Y':
21211     case 'l':
21212       return C_RegisterClass;
21213     case 'a':
21214     case 'b':
21215     case 'c':
21216     case 'd':
21217     case 'S':
21218     case 'D':
21219     case 'A':
21220       return C_Register;
21221     case 'I':
21222     case 'J':
21223     case 'K':
21224     case 'L':
21225     case 'M':
21226     case 'N':
21227     case 'G':
21228     case 'C':
21229     case 'e':
21230     case 'Z':
21231       return C_Other;
21232     default:
21233       break;
21234     }
21235   }
21236   return TargetLowering::getConstraintType(Constraint);
21237 }
21238
21239 /// Examine constraint type and operand type and determine a weight value.
21240 /// This object must already have been set up with the operand type
21241 /// and the current alternative constraint selected.
21242 TargetLowering::ConstraintWeight
21243   X86TargetLowering::getSingleConstraintMatchWeight(
21244     AsmOperandInfo &info, const char *constraint) const {
21245   ConstraintWeight weight = CW_Invalid;
21246   Value *CallOperandVal = info.CallOperandVal;
21247     // If we don't have a value, we can't do a match,
21248     // but allow it at the lowest weight.
21249   if (!CallOperandVal)
21250     return CW_Default;
21251   Type *type = CallOperandVal->getType();
21252   // Look at the constraint type.
21253   switch (*constraint) {
21254   default:
21255     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21256   case 'R':
21257   case 'q':
21258   case 'Q':
21259   case 'a':
21260   case 'b':
21261   case 'c':
21262   case 'd':
21263   case 'S':
21264   case 'D':
21265   case 'A':
21266     if (CallOperandVal->getType()->isIntegerTy())
21267       weight = CW_SpecificReg;
21268     break;
21269   case 'f':
21270   case 't':
21271   case 'u':
21272     if (type->isFloatingPointTy())
21273       weight = CW_SpecificReg;
21274     break;
21275   case 'y':
21276     if (type->isX86_MMXTy() && Subtarget->hasMMX())
21277       weight = CW_SpecificReg;
21278     break;
21279   case 'x':
21280   case 'Y':
21281     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21282         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21283       weight = CW_Register;
21284     break;
21285   case 'I':
21286     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21287       if (C->getZExtValue() <= 31)
21288         weight = CW_Constant;
21289     }
21290     break;
21291   case 'J':
21292     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21293       if (C->getZExtValue() <= 63)
21294         weight = CW_Constant;
21295     }
21296     break;
21297   case 'K':
21298     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21299       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21300         weight = CW_Constant;
21301     }
21302     break;
21303   case 'L':
21304     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21305       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21306         weight = CW_Constant;
21307     }
21308     break;
21309   case 'M':
21310     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21311       if (C->getZExtValue() <= 3)
21312         weight = CW_Constant;
21313     }
21314     break;
21315   case 'N':
21316     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21317       if (C->getZExtValue() <= 0xff)
21318         weight = CW_Constant;
21319     }
21320     break;
21321   case 'G':
21322   case 'C':
21323     if (dyn_cast<ConstantFP>(CallOperandVal)) {
21324       weight = CW_Constant;
21325     }
21326     break;
21327   case 'e':
21328     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21329       if ((C->getSExtValue() >= -0x80000000LL) &&
21330           (C->getSExtValue() <= 0x7fffffffLL))
21331         weight = CW_Constant;
21332     }
21333     break;
21334   case 'Z':
21335     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21336       if (C->getZExtValue() <= 0xffffffff)
21337         weight = CW_Constant;
21338     }
21339     break;
21340   }
21341   return weight;
21342 }
21343
21344 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21345 /// with another that has more specific requirements based on the type of the
21346 /// corresponding operand.
21347 const char *X86TargetLowering::
21348 LowerXConstraint(EVT ConstraintVT) const {
21349   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21350   // 'f' like normal targets.
21351   if (ConstraintVT.isFloatingPoint()) {
21352     if (Subtarget->hasSSE2())
21353       return "Y";
21354     if (Subtarget->hasSSE1())
21355       return "x";
21356   }
21357
21358   return TargetLowering::LowerXConstraint(ConstraintVT);
21359 }
21360
21361 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21362 /// vector.  If it is invalid, don't add anything to Ops.
21363 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21364                                                      std::string &Constraint,
21365                                                      std::vector<SDValue>&Ops,
21366                                                      SelectionDAG &DAG) const {
21367   SDValue Result;
21368
21369   // Only support length 1 constraints for now.
21370   if (Constraint.length() > 1) return;
21371
21372   char ConstraintLetter = Constraint[0];
21373   switch (ConstraintLetter) {
21374   default: break;
21375   case 'I':
21376     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21377       if (C->getZExtValue() <= 31) {
21378         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21379         break;
21380       }
21381     }
21382     return;
21383   case 'J':
21384     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21385       if (C->getZExtValue() <= 63) {
21386         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21387         break;
21388       }
21389     }
21390     return;
21391   case 'K':
21392     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21393       if (isInt<8>(C->getSExtValue())) {
21394         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21395         break;
21396       }
21397     }
21398     return;
21399   case 'N':
21400     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21401       if (C->getZExtValue() <= 255) {
21402         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21403         break;
21404       }
21405     }
21406     return;
21407   case 'e': {
21408     // 32-bit signed value
21409     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21410       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21411                                            C->getSExtValue())) {
21412         // Widen to 64 bits here to get it sign extended.
21413         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21414         break;
21415       }
21416     // FIXME gcc accepts some relocatable values here too, but only in certain
21417     // memory models; it's complicated.
21418     }
21419     return;
21420   }
21421   case 'Z': {
21422     // 32-bit unsigned value
21423     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21424       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21425                                            C->getZExtValue())) {
21426         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21427         break;
21428       }
21429     }
21430     // FIXME gcc accepts some relocatable values here too, but only in certain
21431     // memory models; it's complicated.
21432     return;
21433   }
21434   case 'i': {
21435     // Literal immediates are always ok.
21436     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21437       // Widen to 64 bits here to get it sign extended.
21438       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21439       break;
21440     }
21441
21442     // In any sort of PIC mode addresses need to be computed at runtime by
21443     // adding in a register or some sort of table lookup.  These can't
21444     // be used as immediates.
21445     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21446       return;
21447
21448     // If we are in non-pic codegen mode, we allow the address of a global (with
21449     // an optional displacement) to be used with 'i'.
21450     GlobalAddressSDNode *GA = nullptr;
21451     int64_t Offset = 0;
21452
21453     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21454     while (1) {
21455       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21456         Offset += GA->getOffset();
21457         break;
21458       } else if (Op.getOpcode() == ISD::ADD) {
21459         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21460           Offset += C->getZExtValue();
21461           Op = Op.getOperand(0);
21462           continue;
21463         }
21464       } else if (Op.getOpcode() == ISD::SUB) {
21465         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21466           Offset += -C->getZExtValue();
21467           Op = Op.getOperand(0);
21468           continue;
21469         }
21470       }
21471
21472       // Otherwise, this isn't something we can handle, reject it.
21473       return;
21474     }
21475
21476     const GlobalValue *GV = GA->getGlobal();
21477     // If we require an extra load to get this address, as in PIC mode, we
21478     // can't accept it.
21479     if (isGlobalStubReference(
21480             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21481       return;
21482
21483     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21484                                         GA->getValueType(0), Offset);
21485     break;
21486   }
21487   }
21488
21489   if (Result.getNode()) {
21490     Ops.push_back(Result);
21491     return;
21492   }
21493   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21494 }
21495
21496 std::pair<unsigned, const TargetRegisterClass*>
21497 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21498                                                 MVT VT) const {
21499   // First, see if this is a constraint that directly corresponds to an LLVM
21500   // register class.
21501   if (Constraint.size() == 1) {
21502     // GCC Constraint Letters
21503     switch (Constraint[0]) {
21504     default: break;
21505       // TODO: Slight differences here in allocation order and leaving
21506       // RIP in the class. Do they matter any more here than they do
21507       // in the normal allocation?
21508     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21509       if (Subtarget->is64Bit()) {
21510         if (VT == MVT::i32 || VT == MVT::f32)
21511           return std::make_pair(0U, &X86::GR32RegClass);
21512         if (VT == MVT::i16)
21513           return std::make_pair(0U, &X86::GR16RegClass);
21514         if (VT == MVT::i8 || VT == MVT::i1)
21515           return std::make_pair(0U, &X86::GR8RegClass);
21516         if (VT == MVT::i64 || VT == MVT::f64)
21517           return std::make_pair(0U, &X86::GR64RegClass);
21518         break;
21519       }
21520       // 32-bit fallthrough
21521     case 'Q':   // Q_REGS
21522       if (VT == MVT::i32 || VT == MVT::f32)
21523         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21524       if (VT == MVT::i16)
21525         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21526       if (VT == MVT::i8 || VT == MVT::i1)
21527         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21528       if (VT == MVT::i64)
21529         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21530       break;
21531     case 'r':   // GENERAL_REGS
21532     case 'l':   // INDEX_REGS
21533       if (VT == MVT::i8 || VT == MVT::i1)
21534         return std::make_pair(0U, &X86::GR8RegClass);
21535       if (VT == MVT::i16)
21536         return std::make_pair(0U, &X86::GR16RegClass);
21537       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21538         return std::make_pair(0U, &X86::GR32RegClass);
21539       return std::make_pair(0U, &X86::GR64RegClass);
21540     case 'R':   // LEGACY_REGS
21541       if (VT == MVT::i8 || VT == MVT::i1)
21542         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21543       if (VT == MVT::i16)
21544         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21545       if (VT == MVT::i32 || !Subtarget->is64Bit())
21546         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21547       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21548     case 'f':  // FP Stack registers.
21549       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21550       // value to the correct fpstack register class.
21551       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21552         return std::make_pair(0U, &X86::RFP32RegClass);
21553       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21554         return std::make_pair(0U, &X86::RFP64RegClass);
21555       return std::make_pair(0U, &X86::RFP80RegClass);
21556     case 'y':   // MMX_REGS if MMX allowed.
21557       if (!Subtarget->hasMMX()) break;
21558       return std::make_pair(0U, &X86::VR64RegClass);
21559     case 'Y':   // SSE_REGS if SSE2 allowed
21560       if (!Subtarget->hasSSE2()) break;
21561       // FALL THROUGH.
21562     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21563       if (!Subtarget->hasSSE1()) break;
21564
21565       switch (VT.SimpleTy) {
21566       default: break;
21567       // Scalar SSE types.
21568       case MVT::f32:
21569       case MVT::i32:
21570         return std::make_pair(0U, &X86::FR32RegClass);
21571       case MVT::f64:
21572       case MVT::i64:
21573         return std::make_pair(0U, &X86::FR64RegClass);
21574       // Vector types.
21575       case MVT::v16i8:
21576       case MVT::v8i16:
21577       case MVT::v4i32:
21578       case MVT::v2i64:
21579       case MVT::v4f32:
21580       case MVT::v2f64:
21581         return std::make_pair(0U, &X86::VR128RegClass);
21582       // AVX types.
21583       case MVT::v32i8:
21584       case MVT::v16i16:
21585       case MVT::v8i32:
21586       case MVT::v4i64:
21587       case MVT::v8f32:
21588       case MVT::v4f64:
21589         return std::make_pair(0U, &X86::VR256RegClass);
21590       case MVT::v8f64:
21591       case MVT::v16f32:
21592       case MVT::v16i32:
21593       case MVT::v8i64:
21594         return std::make_pair(0U, &X86::VR512RegClass);
21595       }
21596       break;
21597     }
21598   }
21599
21600   // Use the default implementation in TargetLowering to convert the register
21601   // constraint into a member of a register class.
21602   std::pair<unsigned, const TargetRegisterClass*> Res;
21603   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21604
21605   // Not found as a standard register?
21606   if (!Res.second) {
21607     // Map st(0) -> st(7) -> ST0
21608     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21609         tolower(Constraint[1]) == 's' &&
21610         tolower(Constraint[2]) == 't' &&
21611         Constraint[3] == '(' &&
21612         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21613         Constraint[5] == ')' &&
21614         Constraint[6] == '}') {
21615
21616       Res.first = X86::ST0+Constraint[4]-'0';
21617       Res.second = &X86::RFP80RegClass;
21618       return Res;
21619     }
21620
21621     // GCC allows "st(0)" to be called just plain "st".
21622     if (StringRef("{st}").equals_lower(Constraint)) {
21623       Res.first = X86::ST0;
21624       Res.second = &X86::RFP80RegClass;
21625       return Res;
21626     }
21627
21628     // flags -> EFLAGS
21629     if (StringRef("{flags}").equals_lower(Constraint)) {
21630       Res.first = X86::EFLAGS;
21631       Res.second = &X86::CCRRegClass;
21632       return Res;
21633     }
21634
21635     // 'A' means EAX + EDX.
21636     if (Constraint == "A") {
21637       Res.first = X86::EAX;
21638       Res.second = &X86::GR32_ADRegClass;
21639       return Res;
21640     }
21641     return Res;
21642   }
21643
21644   // Otherwise, check to see if this is a register class of the wrong value
21645   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21646   // turn into {ax},{dx}.
21647   if (Res.second->hasType(VT))
21648     return Res;   // Correct type already, nothing to do.
21649
21650   // All of the single-register GCC register classes map their values onto
21651   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21652   // really want an 8-bit or 32-bit register, map to the appropriate register
21653   // class and return the appropriate register.
21654   if (Res.second == &X86::GR16RegClass) {
21655     if (VT == MVT::i8 || VT == MVT::i1) {
21656       unsigned DestReg = 0;
21657       switch (Res.first) {
21658       default: break;
21659       case X86::AX: DestReg = X86::AL; break;
21660       case X86::DX: DestReg = X86::DL; break;
21661       case X86::CX: DestReg = X86::CL; break;
21662       case X86::BX: DestReg = X86::BL; break;
21663       }
21664       if (DestReg) {
21665         Res.first = DestReg;
21666         Res.second = &X86::GR8RegClass;
21667       }
21668     } else if (VT == MVT::i32 || VT == MVT::f32) {
21669       unsigned DestReg = 0;
21670       switch (Res.first) {
21671       default: break;
21672       case X86::AX: DestReg = X86::EAX; break;
21673       case X86::DX: DestReg = X86::EDX; break;
21674       case X86::CX: DestReg = X86::ECX; break;
21675       case X86::BX: DestReg = X86::EBX; break;
21676       case X86::SI: DestReg = X86::ESI; break;
21677       case X86::DI: DestReg = X86::EDI; break;
21678       case X86::BP: DestReg = X86::EBP; break;
21679       case X86::SP: DestReg = X86::ESP; break;
21680       }
21681       if (DestReg) {
21682         Res.first = DestReg;
21683         Res.second = &X86::GR32RegClass;
21684       }
21685     } else if (VT == MVT::i64 || VT == MVT::f64) {
21686       unsigned DestReg = 0;
21687       switch (Res.first) {
21688       default: break;
21689       case X86::AX: DestReg = X86::RAX; break;
21690       case X86::DX: DestReg = X86::RDX; break;
21691       case X86::CX: DestReg = X86::RCX; break;
21692       case X86::BX: DestReg = X86::RBX; break;
21693       case X86::SI: DestReg = X86::RSI; break;
21694       case X86::DI: DestReg = X86::RDI; break;
21695       case X86::BP: DestReg = X86::RBP; break;
21696       case X86::SP: DestReg = X86::RSP; break;
21697       }
21698       if (DestReg) {
21699         Res.first = DestReg;
21700         Res.second = &X86::GR64RegClass;
21701       }
21702     }
21703   } else if (Res.second == &X86::FR32RegClass ||
21704              Res.second == &X86::FR64RegClass ||
21705              Res.second == &X86::VR128RegClass ||
21706              Res.second == &X86::VR256RegClass ||
21707              Res.second == &X86::FR32XRegClass ||
21708              Res.second == &X86::FR64XRegClass ||
21709              Res.second == &X86::VR128XRegClass ||
21710              Res.second == &X86::VR256XRegClass ||
21711              Res.second == &X86::VR512RegClass) {
21712     // Handle references to XMM physical registers that got mapped into the
21713     // wrong class.  This can happen with constraints like {xmm0} where the
21714     // target independent register mapper will just pick the first match it can
21715     // find, ignoring the required type.
21716
21717     if (VT == MVT::f32 || VT == MVT::i32)
21718       Res.second = &X86::FR32RegClass;
21719     else if (VT == MVT::f64 || VT == MVT::i64)
21720       Res.second = &X86::FR64RegClass;
21721     else if (X86::VR128RegClass.hasType(VT))
21722       Res.second = &X86::VR128RegClass;
21723     else if (X86::VR256RegClass.hasType(VT))
21724       Res.second = &X86::VR256RegClass;
21725     else if (X86::VR512RegClass.hasType(VT))
21726       Res.second = &X86::VR512RegClass;
21727   }
21728
21729   return Res;
21730 }
21731
21732 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21733                                             Type *Ty) const {
21734   // Scaling factors are not free at all.
21735   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21736   // will take 2 allocations in the out of order engine instead of 1
21737   // for plain addressing mode, i.e. inst (reg1).
21738   // E.g.,
21739   // vaddps (%rsi,%drx), %ymm0, %ymm1
21740   // Requires two allocations (one for the load, one for the computation)
21741   // whereas:
21742   // vaddps (%rsi), %ymm0, %ymm1
21743   // Requires just 1 allocation, i.e., freeing allocations for other operations
21744   // and having less micro operations to execute.
21745   //
21746   // For some X86 architectures, this is even worse because for instance for
21747   // stores, the complex addressing mode forces the instruction to use the
21748   // "load" ports instead of the dedicated "store" port.
21749   // E.g., on Haswell:
21750   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21751   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21752   if (isLegalAddressingMode(AM, Ty))
21753     // Scale represents reg2 * scale, thus account for 1
21754     // as soon as we use a second register.
21755     return AM.Scale != 0;
21756   return -1;
21757 }
21758
21759 bool X86TargetLowering::isTargetFTOL() const {
21760   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
21761 }