SelectionDAG: Don't use MVT::Other to determine legality of ISD::SELECT_CC
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 #define DEBUG_TYPE "x86-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64                                 SelectionDAG &DAG, SDLoc dl,
65                                 unsigned vectorWidth) {
66   assert((vectorWidth == 128 || vectorWidth == 256) &&
67          "Unsupported vector width");
68   EVT VT = Vec.getValueType();
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/vectorWidth;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
79   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80
81   // This is the index of the first element of the vectorWidth-bit chunk
82   // we want.
83   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84                                * ElemsPerChunk);
85
86   // If the input is a buildvector just emit a smaller one.
87   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
90                                     ElemsPerChunk));
91
92   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94                                VecIdx);
95
96   return Result;
97
98 }
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106                                    SelectionDAG &DAG, SDLoc dl) {
107   assert((Vec.getValueType().is256BitVector() ||
108           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 }
111
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114                                    SelectionDAG &DAG, SDLoc dl) {
115   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 }
118
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120                                unsigned IdxVal, SelectionDAG &DAG,
121                                SDLoc dl, unsigned vectorWidth) {
122   assert((vectorWidth == 128 || vectorWidth == 256) &&
123          "Unsupported vector width");
124   // Inserting UNDEF is Result
125   if (Vec.getOpcode() == ISD::UNDEF)
126     return Result;
127   EVT VT = Vec.getValueType();
128   EVT ElVT = VT.getVectorElementType();
129   EVT ResultVT = Result.getValueType();
130
131   // Insert the relevant vectorWidth bits.
132   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133
134   // This is the index of the first element of the vectorWidth-bit chunk
135   // we want.
136   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137                                * ElemsPerChunk);
138
139   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141                      VecIdx);
142 }
143 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference.  Idx is an index in the 128 bits
147 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150                                   unsigned IdxVal, SelectionDAG &DAG,
151                                   SDLoc dl) {
152   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 }
155
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 }
162
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168                                    unsigned NumElems, SelectionDAG &DAG,
169                                    SDLoc dl) {
170   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 }
173
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
182   if (TT.isOSBinFormatMachO()) {
183     if (TT.getArch() == Triple::x86_64)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (TT.isOSLinux())
189     return new X86LinuxTargetObjectFile();
190   if (TT.isOSBinFormatELF())
191     return new TargetLoweringObjectFileELF();
192   if (TT.isKnownWindowsMSVCEnvironment())
193     return new X86WindowsTargetObjectFile();
194   if (TT.isOSBinFormatCOFF())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird, it always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit since we have so many registers use the ILP scheduler, for
234   // 32-bit code use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2
247   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248     addBypassSlowDiv(32, 8);
249     if (Subtarget->is64Bit())
250       addBypassSlowDiv(64, 16);
251   }
252
253   if (Subtarget->isTargetKnownWindowsMSVC()) {
254     // Setup Windows compiler runtime calls.
255     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257     setLibcallName(RTLIB::SREM_I64, "_allrem");
258     setLibcallName(RTLIB::UREM_I64, "_aullrem");
259     setLibcallName(RTLIB::MUL_I64, "_allmul");
260     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
265
266     // The _ftol2 runtime function has an unusual calling conv, which
267     // is modeled by a special pseudo-instruction.
268     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
269     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
272   }
273
274   if (Subtarget->isTargetDarwin()) {
275     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276     setUseUnderscoreSetJmp(false);
277     setUseUnderscoreLongJmp(false);
278   } else if (Subtarget->isTargetWindowsGNU()) {
279     // MS runtime is weird: it exports _setjmp, but longjmp!
280     setUseUnderscoreSetJmp(true);
281     setUseUnderscoreLongJmp(false);
282   } else {
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(true);
285   }
286
287   // Set up the register classes.
288   addRegisterClass(MVT::i8, &X86::GR8RegClass);
289   addRegisterClass(MVT::i16, &X86::GR16RegClass);
290   addRegisterClass(MVT::i32, &X86::GR32RegClass);
291   if (Subtarget->is64Bit())
292     addRegisterClass(MVT::i64, &X86::GR64RegClass);
293
294   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
295
296   // We don't accept any truncstore of integer registers.
297   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
303
304   // SETOEQ and SETUNE require checking two conditions.
305   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
311
312   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
313   // operation.
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
317
318   if (Subtarget->is64Bit()) {
319     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
321   } else if (!TM.Options.UseSoftFloat) {
322     // We have an algorithm for SSE2->double, and we turn this into a
323     // 64-bit FILD followed by conditional FADD for other targets.
324     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
325     // We have an algorithm for SSE2, and we turn this into a 64-bit
326     // FILD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
328   }
329
330   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
331   // this operation.
332   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
334
335   if (!TM.Options.UseSoftFloat) {
336     // SSE has no i16 to fp conversion, only i32
337     if (X86ScalarSSEf32) {
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
339       // f32 and f64 cases are Legal, f80 case is not
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
341     } else {
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     }
345   } else {
346     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
348   }
349
350   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
351   // are Legal, f80 is custom lowered.
352   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
353   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
354
355   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
356   // this operation.
357   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
359
360   if (X86ScalarSSEf32) {
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
362     // f32 and f64 cases are Legal, f80 case is not
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
364   } else {
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   }
368
369   // Handle FP_TO_UINT by promoting the destination to a larger signed
370   // conversion.
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
374
375   if (Subtarget->is64Bit()) {
376     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
378   } else if (!TM.Options.UseSoftFloat) {
379     // Since AVX is a superset of SSE3, only check for SSE here.
380     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381       // Expand FP_TO_UINT into a select.
382       // FIXME: We would like to use a Custom expander here eventually to do
383       // the optimal thing for SSE vs. the default expansion in the legalizer.
384       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
385     else
386       // With SSE3 we can use fisttpll to convert to a signed i64; without
387       // SSE, we're stuck with a fistpll.
388       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
389   }
390
391   if (isTargetFTOL()) {
392     // Use the _ftol2 runtime function, which has a pseudo-instruction
393     // to handle its weird calling convention.
394     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
395   }
396
397   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398   if (!X86ScalarSSEf64) {
399     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
400     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
401     if (Subtarget->is64Bit()) {
402       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
403       // Without SSE, i64->f64 goes through memory.
404       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
405     }
406   }
407
408   // Scalar integer divide and remainder are lowered to use operations that
409   // produce two results, to match the available instructions. This exposes
410   // the two-result form to trivial CSE, which is able to combine x/y and x%y
411   // into a single instruction.
412   //
413   // Scalar integer multiply-high is also lowered to use two-result
414   // operations, to match the available instructions. However, plain multiply
415   // (low) operations are left as Legal, as there are single-result
416   // instructions for this in x86. Using the two-result multiply instructions
417   // when both high and low results are needed must be arranged by dagcombine.
418   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
419     MVT VT = IntVTs[i];
420     setOperationAction(ISD::MULHS, VT, Expand);
421     setOperationAction(ISD::MULHU, VT, Expand);
422     setOperationAction(ISD::SDIV, VT, Expand);
423     setOperationAction(ISD::UDIV, VT, Expand);
424     setOperationAction(ISD::SREM, VT, Expand);
425     setOperationAction(ISD::UREM, VT, Expand);
426
427     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428     setOperationAction(ISD::ADDC, VT, Custom);
429     setOperationAction(ISD::ADDE, VT, Custom);
430     setOperationAction(ISD::SUBC, VT, Custom);
431     setOperationAction(ISD::SUBE, VT, Custom);
432   }
433
434   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
435   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
436   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
443   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
444   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
445   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
447   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
448   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
449   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
450   if (Subtarget->is64Bit())
451     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
452   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
453   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
454   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
455   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
456   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
457   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
458   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
459   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
460
461   // Promote the i8 variants and force them on up to i32 which has a shorter
462   // encoding.
463   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
464   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
465   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
466   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
467   if (Subtarget->hasBMI()) {
468     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
469     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
470     if (Subtarget->is64Bit())
471       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
472   } else {
473     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
474     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
475     if (Subtarget->is64Bit())
476       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
477   }
478
479   if (Subtarget->hasLZCNT()) {
480     // When promoting the i8 variants, force them to i32 for a shorter
481     // encoding.
482     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
483     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
484     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
485     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
488     if (Subtarget->is64Bit())
489       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
490   } else {
491     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
492     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
493     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
494     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
495     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
496     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
497     if (Subtarget->is64Bit()) {
498       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
499       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
500     }
501   }
502
503   if (Subtarget->hasPOPCNT()) {
504     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
505   } else {
506     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
507     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
508     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
509     if (Subtarget->is64Bit())
510       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
511   }
512
513   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
514
515   if (!Subtarget->hasMOVBE())
516     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
517
518   // These should be promoted to a larger select which is supported.
519   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
520   // X86 wants to expand cmov itself.
521   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
522   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
523   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
524   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
525   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
526   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
528   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
530   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
531   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
532   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
533   if (Subtarget->is64Bit()) {
534     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
535     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
536   }
537   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
538   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
539   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
540   // support continuation, user-level threading, and etc.. As a result, no
541   // other SjLj exception interfaces are implemented and please don't build
542   // your own exception handling based on them.
543   // LLVM/Clang supports zero-cost DWARF exception handling.
544   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
545   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
546
547   // Darwin ABI issue.
548   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
549   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
550   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
551   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
552   if (Subtarget->is64Bit())
553     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
554   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
555   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
556   if (Subtarget->is64Bit()) {
557     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
558     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
559     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
560     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
561     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
562   }
563   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
564   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
565   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
566   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
569     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
570     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
571   }
572
573   if (Subtarget->hasSSE1())
574     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
575
576   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
577
578   // Expand certain atomics
579   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
580     MVT VT = IntVTs[i];
581     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
583     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
584   }
585
586   if (!Subtarget->is64Bit()) {
587     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
594     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
595     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
596     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
597     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
598     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
599   }
600
601   if (Subtarget->hasCmpxchg16b()) {
602     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
603   }
604
605   // FIXME - use subtarget debug flags
606   if (!Subtarget->isTargetDarwin() &&
607       !Subtarget->isTargetELF() &&
608       !Subtarget->isTargetCygMing()) {
609     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
610   }
611
612   if (Subtarget->is64Bit()) {
613     setExceptionPointerRegister(X86::RAX);
614     setExceptionSelectorRegister(X86::RDX);
615   } else {
616     setExceptionPointerRegister(X86::EAX);
617     setExceptionSelectorRegister(X86::EDX);
618   }
619   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
620   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
621
622   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
623   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
624
625   setOperationAction(ISD::TRAP, MVT::Other, Legal);
626   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
627
628   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
629   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
630   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
631   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
632     // TargetInfo::X86_64ABIBuiltinVaList
633     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
634     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
635   } else {
636     // TargetInfo::CharPtrBuiltinVaList
637     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
638     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
639   }
640
641   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
642   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
643
644   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
645                      MVT::i64 : MVT::i32, Custom);
646
647   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
648     // f32 and f64 use SSE.
649     // Set up the FP register classes.
650     addRegisterClass(MVT::f32, &X86::FR32RegClass);
651     addRegisterClass(MVT::f64, &X86::FR64RegClass);
652
653     // Use ANDPD to simulate FABS.
654     setOperationAction(ISD::FABS , MVT::f64, Custom);
655     setOperationAction(ISD::FABS , MVT::f32, Custom);
656
657     // Use XORP to simulate FNEG.
658     setOperationAction(ISD::FNEG , MVT::f64, Custom);
659     setOperationAction(ISD::FNEG , MVT::f32, Custom);
660
661     // Use ANDPD and ORPD to simulate FCOPYSIGN.
662     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
663     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
664
665     // Lower this to FGETSIGNx86 plus an AND.
666     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
667     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
668
669     // We don't support sin/cos/fmod
670     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
673     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
674     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
675     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
676
677     // Expand FP immediates into loads from the stack, except for the special
678     // cases we handle.
679     addLegalFPImmediate(APFloat(+0.0)); // xorpd
680     addLegalFPImmediate(APFloat(+0.0f)); // xorps
681   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
682     // Use SSE for f32, x87 for f64.
683     // Set up the FP register classes.
684     addRegisterClass(MVT::f32, &X86::FR32RegClass);
685     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
686
687     // Use ANDPS to simulate FABS.
688     setOperationAction(ISD::FABS , MVT::f32, Custom);
689
690     // Use XORP to simulate FNEG.
691     setOperationAction(ISD::FNEG , MVT::f32, Custom);
692
693     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
694
695     // Use ANDPS and ORPS to simulate FCOPYSIGN.
696     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
697     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
698
699     // We don't support sin/cos/fmod
700     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
701     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
702     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
703
704     // Special cases we handle for FP constants.
705     addLegalFPImmediate(APFloat(+0.0f)); // xorps
706     addLegalFPImmediate(APFloat(+0.0)); // FLD0
707     addLegalFPImmediate(APFloat(+1.0)); // FLD1
708     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
709     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
710
711     if (!TM.Options.UnsafeFPMath) {
712       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
713       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
714       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
715     }
716   } else if (!TM.Options.UseSoftFloat) {
717     // f32 and f64 in x87.
718     // Set up the FP register classes.
719     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
720     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
721
722     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
723     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
724     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
725     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
726
727     if (!TM.Options.UnsafeFPMath) {
728       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
729       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
730       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
734     }
735     addLegalFPImmediate(APFloat(+0.0)); // FLD0
736     addLegalFPImmediate(APFloat(+1.0)); // FLD1
737     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
738     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
739     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
740     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
741     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
742     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
743   }
744
745   // We don't support FMA.
746   setOperationAction(ISD::FMA, MVT::f64, Expand);
747   setOperationAction(ISD::FMA, MVT::f32, Expand);
748
749   // Long double always uses X87.
750   if (!TM.Options.UseSoftFloat) {
751     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
752     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
753     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
754     {
755       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
756       addLegalFPImmediate(TmpFlt);  // FLD0
757       TmpFlt.changeSign();
758       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
759
760       bool ignored;
761       APFloat TmpFlt2(+1.0);
762       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
763                       &ignored);
764       addLegalFPImmediate(TmpFlt2);  // FLD1
765       TmpFlt2.changeSign();
766       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
767     }
768
769     if (!TM.Options.UnsafeFPMath) {
770       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
771       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
772       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
773     }
774
775     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
776     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
777     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
778     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
779     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
780     setOperationAction(ISD::FMA, MVT::f80, Expand);
781   }
782
783   // Always use a library call for pow.
784   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
785   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
786   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
787
788   setOperationAction(ISD::FLOG, MVT::f80, Expand);
789   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
790   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
791   setOperationAction(ISD::FEXP, MVT::f80, Expand);
792   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
793
794   // First set operation action for all vector types to either promote
795   // (for widening) or expand (for scalarization). Then we will selectively
796   // turn on ones that can be effectively codegen'd.
797   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
798            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
799     MVT VT = (MVT::SimpleValueType)i;
800     setOperationAction(ISD::ADD , VT, Expand);
801     setOperationAction(ISD::SUB , VT, Expand);
802     setOperationAction(ISD::FADD, VT, Expand);
803     setOperationAction(ISD::FNEG, VT, Expand);
804     setOperationAction(ISD::FSUB, VT, Expand);
805     setOperationAction(ISD::MUL , VT, Expand);
806     setOperationAction(ISD::FMUL, VT, Expand);
807     setOperationAction(ISD::SDIV, VT, Expand);
808     setOperationAction(ISD::UDIV, VT, Expand);
809     setOperationAction(ISD::FDIV, VT, Expand);
810     setOperationAction(ISD::SREM, VT, Expand);
811     setOperationAction(ISD::UREM, VT, Expand);
812     setOperationAction(ISD::LOAD, VT, Expand);
813     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
814     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
815     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
816     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
817     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
818     setOperationAction(ISD::FABS, VT, Expand);
819     setOperationAction(ISD::FSIN, VT, Expand);
820     setOperationAction(ISD::FSINCOS, VT, Expand);
821     setOperationAction(ISD::FCOS, VT, Expand);
822     setOperationAction(ISD::FSINCOS, VT, Expand);
823     setOperationAction(ISD::FREM, VT, Expand);
824     setOperationAction(ISD::FMA,  VT, Expand);
825     setOperationAction(ISD::FPOWI, VT, Expand);
826     setOperationAction(ISD::FSQRT, VT, Expand);
827     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
828     setOperationAction(ISD::FFLOOR, VT, Expand);
829     setOperationAction(ISD::FCEIL, VT, Expand);
830     setOperationAction(ISD::FTRUNC, VT, Expand);
831     setOperationAction(ISD::FRINT, VT, Expand);
832     setOperationAction(ISD::FNEARBYINT, VT, Expand);
833     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
834     setOperationAction(ISD::MULHS, VT, Expand);
835     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
836     setOperationAction(ISD::MULHU, VT, Expand);
837     setOperationAction(ISD::SDIVREM, VT, Expand);
838     setOperationAction(ISD::UDIVREM, VT, Expand);
839     setOperationAction(ISD::FPOW, VT, Expand);
840     setOperationAction(ISD::CTPOP, VT, Expand);
841     setOperationAction(ISD::CTTZ, VT, Expand);
842     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
843     setOperationAction(ISD::CTLZ, VT, Expand);
844     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
845     setOperationAction(ISD::SHL, VT, Expand);
846     setOperationAction(ISD::SRA, VT, Expand);
847     setOperationAction(ISD::SRL, VT, Expand);
848     setOperationAction(ISD::ROTL, VT, Expand);
849     setOperationAction(ISD::ROTR, VT, Expand);
850     setOperationAction(ISD::BSWAP, VT, Expand);
851     setOperationAction(ISD::SETCC, VT, Expand);
852     setOperationAction(ISD::FLOG, VT, Expand);
853     setOperationAction(ISD::FLOG2, VT, Expand);
854     setOperationAction(ISD::FLOG10, VT, Expand);
855     setOperationAction(ISD::FEXP, VT, Expand);
856     setOperationAction(ISD::FEXP2, VT, Expand);
857     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
858     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
859     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
860     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
861     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
862     setOperationAction(ISD::TRUNCATE, VT, Expand);
863     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
864     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
865     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
866     setOperationAction(ISD::VSELECT, VT, Expand);
867     setOperationAction(ISD::SELECT_CC, VT, Expand);
868     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
869              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
870       setTruncStoreAction(VT,
871                           (MVT::SimpleValueType)InnerVT, Expand);
872     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
873     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
874     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
875   }
876
877   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
878   // with -msoft-float, disable use of MMX as well.
879   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
880     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
881     // No operations on x86mmx supported, everything uses intrinsics.
882   }
883
884   // MMX-sized vectors (other than x86mmx) are expected to be expanded
885   // into smaller operations.
886   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
887   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
888   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
889   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
890   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
891   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
892   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
893   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
894   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
895   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
896   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
897   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
898   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
899   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
900   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
901   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
902   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
903   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
904   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
905   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
906   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
907   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
908   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
909   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
910   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
911   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
912   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
913   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
914   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
915
916   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
917     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
918
919     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
920     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
921     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
922     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
923     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
924     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
925     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
926     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
927     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
928     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
929     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
930     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
931   }
932
933   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
934     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
935
936     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
937     // registers cannot be used even for integer operations.
938     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
939     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
940     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
941     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
942
943     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
944     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
945     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
946     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
947     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
948     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
949     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
950     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
951     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
952     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
953     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
954     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
955     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
956     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
957     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
958     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
959     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
960     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
961     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
962     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
963     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
964     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
965
966     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
967     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
968     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
969     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
970
971     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
972     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
973     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
974     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
975     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
976
977     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
978     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
979       MVT VT = (MVT::SimpleValueType)i;
980       // Do not attempt to custom lower non-power-of-2 vectors
981       if (!isPowerOf2_32(VT.getVectorNumElements()))
982         continue;
983       // Do not attempt to custom lower non-128-bit vectors
984       if (!VT.is128BitVector())
985         continue;
986       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
987       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
988       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
989     }
990
991     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
992     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
993     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
994     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
997
998     if (Subtarget->is64Bit()) {
999       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1000       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1001     }
1002
1003     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1004     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1005       MVT VT = (MVT::SimpleValueType)i;
1006
1007       // Do not attempt to promote non-128-bit vectors
1008       if (!VT.is128BitVector())
1009         continue;
1010
1011       setOperationAction(ISD::AND,    VT, Promote);
1012       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1013       setOperationAction(ISD::OR,     VT, Promote);
1014       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1015       setOperationAction(ISD::XOR,    VT, Promote);
1016       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1017       setOperationAction(ISD::LOAD,   VT, Promote);
1018       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1019       setOperationAction(ISD::SELECT, VT, Promote);
1020       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1021     }
1022
1023     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1024
1025     // Custom lower v2i64 and v2f64 selects.
1026     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1027     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1028     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1029     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1030
1031     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1032     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1033
1034     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1035     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1036     // As there is no 64-bit GPR available, we need build a special custom
1037     // sequence to convert from v2i32 to v2f32.
1038     if (!Subtarget->is64Bit())
1039       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1040
1041     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1042     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1043
1044     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1045
1046     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1047     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1048     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1049   }
1050
1051   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1052     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1055     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1060     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1062
1063     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1064     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1065     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1066     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1067     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1068     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1069     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1070     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1071     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1072     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1073
1074     // FIXME: Do we need to handle scalar-to-vector here?
1075     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1076
1077     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1078     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1079     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1080     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1081     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1082     // There is no BLENDI for byte vectors. We don't need to custom lower
1083     // some vselects for now.
1084     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1085
1086     // i8 and i16 vectors are custom , because the source register and source
1087     // source memory operand types are not the same width.  f32 vectors are
1088     // custom since the immediate controlling the insert encodes additional
1089     // information.
1090     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1091     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1092     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1093     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1094
1095     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1096     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1097     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1098     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1099
1100     // FIXME: these should be Legal but thats only for the case where
1101     // the index is constant.  For now custom expand to deal with that.
1102     if (Subtarget->is64Bit()) {
1103       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1104       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1105     }
1106   }
1107
1108   if (Subtarget->hasSSE2()) {
1109     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1110     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1111
1112     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1113     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1114
1115     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1116     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1117
1118     // In the customized shift lowering, the legal cases in AVX2 will be
1119     // recognized.
1120     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1121     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1122
1123     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1124     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1125
1126     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1127   }
1128
1129   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1130     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1131     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1132     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1133     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1134     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1135     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1136
1137     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1138     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1139     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1140
1141     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1142     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1143     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1144     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1145     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1146     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1147     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1148     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1149     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1150     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1151     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1152     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1153
1154     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1155     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1156     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1157     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1158     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1159     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1160     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1161     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1162     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1163     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1164     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1165     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1166
1167     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1168     // even though v8i16 is a legal type.
1169     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1170     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1171     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1172
1173     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1174     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1175     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1176
1177     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1178     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1179
1180     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1181
1182     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1183     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1184
1185     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1186     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1187
1188     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1189     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1190
1191     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1192     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1193     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1194     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1195
1196     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1197     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1198     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1199
1200     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1201     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1202     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1203     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1204
1205     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1206     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1207     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1208     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1209     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1210     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1211     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1212     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1213     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1214     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1215     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1216     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1217
1218     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1219       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1220       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1221       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1222       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1223       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1224       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1225     }
1226
1227     if (Subtarget->hasInt256()) {
1228       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1229       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1230       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1231       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1232
1233       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1234       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1235       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1236       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1237
1238       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1239       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1240       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1241       // Don't lower v32i8 because there is no 128-bit byte mul
1242
1243       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1244       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1245       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1246       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1247
1248       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1249       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1250     } else {
1251       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1252       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1253       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1254       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1255
1256       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1257       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1258       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1259       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1260
1261       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1262       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1263       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1264       // Don't lower v32i8 because there is no 128-bit byte mul
1265     }
1266
1267     // In the customized shift lowering, the legal cases in AVX2 will be
1268     // recognized.
1269     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1270     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1271
1272     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1273     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1274
1275     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1276
1277     // Custom lower several nodes for 256-bit types.
1278     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1279              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1280       MVT VT = (MVT::SimpleValueType)i;
1281
1282       // Extract subvector is special because the value type
1283       // (result) is 128-bit but the source is 256-bit wide.
1284       if (VT.is128BitVector())
1285         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1286
1287       // Do not attempt to custom lower other non-256-bit vectors
1288       if (!VT.is256BitVector())
1289         continue;
1290
1291       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1292       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1293       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1294       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1295       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1296       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1297       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1298     }
1299
1300     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1301     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1302       MVT VT = (MVT::SimpleValueType)i;
1303
1304       // Do not attempt to promote non-256-bit vectors
1305       if (!VT.is256BitVector())
1306         continue;
1307
1308       setOperationAction(ISD::AND,    VT, Promote);
1309       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1310       setOperationAction(ISD::OR,     VT, Promote);
1311       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1312       setOperationAction(ISD::XOR,    VT, Promote);
1313       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1314       setOperationAction(ISD::LOAD,   VT, Promote);
1315       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1316       setOperationAction(ISD::SELECT, VT, Promote);
1317       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1318     }
1319   }
1320
1321   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1322     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1323     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1324     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1325     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1326
1327     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1328     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1329     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1330
1331     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1332     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1333     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1334     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1335     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1336     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1337     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1340     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1341     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1342
1343     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1344     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1348     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1349
1350     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1351     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1352     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1353     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1354     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1355     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1356     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1357     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1358
1359     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1360     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1361     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1363     if (Subtarget->is64Bit()) {
1364       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1365       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1366       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1367       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1368     }
1369     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1370     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1372     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1373     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1374     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1375     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1376     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1377     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1378     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1379
1380     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1381     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1382     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1383     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1384     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1386     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1387     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1388     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1389     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1390     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1391     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1392     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1393
1394     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1395     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1396     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1397     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1398     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1399     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1400
1401     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1402     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1403
1404     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1405
1406     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1407     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1408     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1409     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1410     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1411     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1412     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1413     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1414     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1415
1416     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1417     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1418
1419     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1420     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1421
1422     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1423
1424     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1425     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1426
1427     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1428     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1429
1430     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1431     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1432
1433     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1434     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1435     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1436     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1437     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1438     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1439
1440     // Custom lower several nodes.
1441     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1442              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1443       MVT VT = (MVT::SimpleValueType)i;
1444
1445       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1446       // Extract subvector is special because the value type
1447       // (result) is 256/128-bit but the source is 512-bit wide.
1448       if (VT.is128BitVector() || VT.is256BitVector())
1449         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1450
1451       if (VT.getVectorElementType() == MVT::i1)
1452         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1453
1454       // Do not attempt to custom lower other non-512-bit vectors
1455       if (!VT.is512BitVector())
1456         continue;
1457
1458       if ( EltSize >= 32) {
1459         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1460         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1461         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1462         setOperationAction(ISD::VSELECT,             VT, Legal);
1463         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1464         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1465         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1466       }
1467     }
1468     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1469       MVT VT = (MVT::SimpleValueType)i;
1470
1471       // Do not attempt to promote non-256-bit vectors
1472       if (!VT.is512BitVector())
1473         continue;
1474
1475       setOperationAction(ISD::SELECT, VT, Promote);
1476       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1477     }
1478   }// has  AVX-512
1479
1480   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1481   // of this type with custom code.
1482   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1483            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1484     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1485                        Custom);
1486   }
1487
1488   // We want to custom lower some of our intrinsics.
1489   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1490   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1491   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1492   if (!Subtarget->is64Bit())
1493     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1494
1495   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1496   // handle type legalization for these operations here.
1497   //
1498   // FIXME: We really should do custom legalization for addition and
1499   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1500   // than generic legalization for 64-bit multiplication-with-overflow, though.
1501   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1502     // Add/Sub/Mul with overflow operations are custom lowered.
1503     MVT VT = IntVTs[i];
1504     setOperationAction(ISD::SADDO, VT, Custom);
1505     setOperationAction(ISD::UADDO, VT, Custom);
1506     setOperationAction(ISD::SSUBO, VT, Custom);
1507     setOperationAction(ISD::USUBO, VT, Custom);
1508     setOperationAction(ISD::SMULO, VT, Custom);
1509     setOperationAction(ISD::UMULO, VT, Custom);
1510   }
1511
1512   // There are no 8-bit 3-address imul/mul instructions
1513   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1514   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1515
1516   if (!Subtarget->is64Bit()) {
1517     // These libcalls are not available in 32-bit.
1518     setLibcallName(RTLIB::SHL_I128, nullptr);
1519     setLibcallName(RTLIB::SRL_I128, nullptr);
1520     setLibcallName(RTLIB::SRA_I128, nullptr);
1521   }
1522
1523   // Combine sin / cos into one node or libcall if possible.
1524   if (Subtarget->hasSinCos()) {
1525     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1526     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1527     if (Subtarget->isTargetDarwin()) {
1528       // For MacOSX, we don't want to the normal expansion of a libcall to
1529       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1530       // traffic.
1531       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1532       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1533     }
1534   }
1535
1536   if (Subtarget->isTargetWin64()) {
1537     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1538     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1539     setOperationAction(ISD::SREM, MVT::i128, Custom);
1540     setOperationAction(ISD::UREM, MVT::i128, Custom);
1541     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1542     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1543   }
1544
1545   // We have target-specific dag combine patterns for the following nodes:
1546   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1547   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1548   setTargetDAGCombine(ISD::VSELECT);
1549   setTargetDAGCombine(ISD::SELECT);
1550   setTargetDAGCombine(ISD::SHL);
1551   setTargetDAGCombine(ISD::SRA);
1552   setTargetDAGCombine(ISD::SRL);
1553   setTargetDAGCombine(ISD::OR);
1554   setTargetDAGCombine(ISD::AND);
1555   setTargetDAGCombine(ISD::ADD);
1556   setTargetDAGCombine(ISD::FADD);
1557   setTargetDAGCombine(ISD::FSUB);
1558   setTargetDAGCombine(ISD::FMA);
1559   setTargetDAGCombine(ISD::SUB);
1560   setTargetDAGCombine(ISD::LOAD);
1561   setTargetDAGCombine(ISD::STORE);
1562   setTargetDAGCombine(ISD::ZERO_EXTEND);
1563   setTargetDAGCombine(ISD::ANY_EXTEND);
1564   setTargetDAGCombine(ISD::SIGN_EXTEND);
1565   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1566   setTargetDAGCombine(ISD::TRUNCATE);
1567   setTargetDAGCombine(ISD::SINT_TO_FP);
1568   setTargetDAGCombine(ISD::SETCC);
1569   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1570   setTargetDAGCombine(ISD::BUILD_VECTOR);
1571   if (Subtarget->is64Bit())
1572     setTargetDAGCombine(ISD::MUL);
1573   setTargetDAGCombine(ISD::XOR);
1574
1575   computeRegisterProperties();
1576
1577   // On Darwin, -Os means optimize for size without hurting performance,
1578   // do not reduce the limit.
1579   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1580   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1581   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1582   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1583   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1584   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1585   setPrefLoopAlignment(4); // 2^4 bytes.
1586
1587   // Predictable cmov don't hurt on atom because it's in-order.
1588   PredictableSelectIsExpensive = !Subtarget->isAtom();
1589
1590   setPrefFunctionAlignment(4); // 2^4 bytes.
1591 }
1592
1593 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1594   if (!VT.isVector())
1595     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1596
1597   if (Subtarget->hasAVX512())
1598     switch(VT.getVectorNumElements()) {
1599     case  8: return MVT::v8i1;
1600     case 16: return MVT::v16i1;
1601   }
1602
1603   return VT.changeVectorElementTypeToInteger();
1604 }
1605
1606 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1607 /// the desired ByVal argument alignment.
1608 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1609   if (MaxAlign == 16)
1610     return;
1611   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1612     if (VTy->getBitWidth() == 128)
1613       MaxAlign = 16;
1614   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1615     unsigned EltAlign = 0;
1616     getMaxByValAlign(ATy->getElementType(), EltAlign);
1617     if (EltAlign > MaxAlign)
1618       MaxAlign = EltAlign;
1619   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1620     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1621       unsigned EltAlign = 0;
1622       getMaxByValAlign(STy->getElementType(i), EltAlign);
1623       if (EltAlign > MaxAlign)
1624         MaxAlign = EltAlign;
1625       if (MaxAlign == 16)
1626         break;
1627     }
1628   }
1629 }
1630
1631 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1632 /// function arguments in the caller parameter area. For X86, aggregates
1633 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1634 /// are at 4-byte boundaries.
1635 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1636   if (Subtarget->is64Bit()) {
1637     // Max of 8 and alignment of type.
1638     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1639     if (TyAlign > 8)
1640       return TyAlign;
1641     return 8;
1642   }
1643
1644   unsigned Align = 4;
1645   if (Subtarget->hasSSE1())
1646     getMaxByValAlign(Ty, Align);
1647   return Align;
1648 }
1649
1650 /// getOptimalMemOpType - Returns the target specific optimal type for load
1651 /// and store operations as a result of memset, memcpy, and memmove
1652 /// lowering. If DstAlign is zero that means it's safe to destination
1653 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1654 /// means there isn't a need to check it against alignment requirement,
1655 /// probably because the source does not need to be loaded. If 'IsMemset' is
1656 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1657 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1658 /// source is constant so it does not need to be loaded.
1659 /// It returns EVT::Other if the type should be determined using generic
1660 /// target-independent logic.
1661 EVT
1662 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1663                                        unsigned DstAlign, unsigned SrcAlign,
1664                                        bool IsMemset, bool ZeroMemset,
1665                                        bool MemcpyStrSrc,
1666                                        MachineFunction &MF) const {
1667   const Function *F = MF.getFunction();
1668   if ((!IsMemset || ZeroMemset) &&
1669       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1670                                        Attribute::NoImplicitFloat)) {
1671     if (Size >= 16 &&
1672         (Subtarget->isUnalignedMemAccessFast() ||
1673          ((DstAlign == 0 || DstAlign >= 16) &&
1674           (SrcAlign == 0 || SrcAlign >= 16)))) {
1675       if (Size >= 32) {
1676         if (Subtarget->hasInt256())
1677           return MVT::v8i32;
1678         if (Subtarget->hasFp256())
1679           return MVT::v8f32;
1680       }
1681       if (Subtarget->hasSSE2())
1682         return MVT::v4i32;
1683       if (Subtarget->hasSSE1())
1684         return MVT::v4f32;
1685     } else if (!MemcpyStrSrc && Size >= 8 &&
1686                !Subtarget->is64Bit() &&
1687                Subtarget->hasSSE2()) {
1688       // Do not use f64 to lower memcpy if source is string constant. It's
1689       // better to use i32 to avoid the loads.
1690       return MVT::f64;
1691     }
1692   }
1693   if (Subtarget->is64Bit() && Size >= 8)
1694     return MVT::i64;
1695   return MVT::i32;
1696 }
1697
1698 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1699   if (VT == MVT::f32)
1700     return X86ScalarSSEf32;
1701   else if (VT == MVT::f64)
1702     return X86ScalarSSEf64;
1703   return true;
1704 }
1705
1706 bool
1707 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1708                                                  unsigned,
1709                                                  bool *Fast) const {
1710   if (Fast)
1711     *Fast = Subtarget->isUnalignedMemAccessFast();
1712   return true;
1713 }
1714
1715 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1716 /// current function.  The returned value is a member of the
1717 /// MachineJumpTableInfo::JTEntryKind enum.
1718 unsigned X86TargetLowering::getJumpTableEncoding() const {
1719   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1720   // symbol.
1721   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1722       Subtarget->isPICStyleGOT())
1723     return MachineJumpTableInfo::EK_Custom32;
1724
1725   // Otherwise, use the normal jump table encoding heuristics.
1726   return TargetLowering::getJumpTableEncoding();
1727 }
1728
1729 const MCExpr *
1730 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1731                                              const MachineBasicBlock *MBB,
1732                                              unsigned uid,MCContext &Ctx) const{
1733   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1734          Subtarget->isPICStyleGOT());
1735   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1736   // entries.
1737   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1738                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1739 }
1740
1741 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1742 /// jumptable.
1743 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1744                                                     SelectionDAG &DAG) const {
1745   if (!Subtarget->is64Bit())
1746     // This doesn't have SDLoc associated with it, but is not really the
1747     // same as a Register.
1748     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1749   return Table;
1750 }
1751
1752 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1753 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1754 /// MCExpr.
1755 const MCExpr *X86TargetLowering::
1756 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1757                              MCContext &Ctx) const {
1758   // X86-64 uses RIP relative addressing based on the jump table label.
1759   if (Subtarget->isPICStyleRIPRel())
1760     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1761
1762   // Otherwise, the reference is relative to the PIC base.
1763   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1764 }
1765
1766 // FIXME: Why this routine is here? Move to RegInfo!
1767 std::pair<const TargetRegisterClass*, uint8_t>
1768 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1769   const TargetRegisterClass *RRC = nullptr;
1770   uint8_t Cost = 1;
1771   switch (VT.SimpleTy) {
1772   default:
1773     return TargetLowering::findRepresentativeClass(VT);
1774   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1775     RRC = Subtarget->is64Bit() ?
1776       (const TargetRegisterClass*)&X86::GR64RegClass :
1777       (const TargetRegisterClass*)&X86::GR32RegClass;
1778     break;
1779   case MVT::x86mmx:
1780     RRC = &X86::VR64RegClass;
1781     break;
1782   case MVT::f32: case MVT::f64:
1783   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1784   case MVT::v4f32: case MVT::v2f64:
1785   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1786   case MVT::v4f64:
1787     RRC = &X86::VR128RegClass;
1788     break;
1789   }
1790   return std::make_pair(RRC, Cost);
1791 }
1792
1793 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1794                                                unsigned &Offset) const {
1795   if (!Subtarget->isTargetLinux())
1796     return false;
1797
1798   if (Subtarget->is64Bit()) {
1799     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1800     Offset = 0x28;
1801     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1802       AddressSpace = 256;
1803     else
1804       AddressSpace = 257;
1805   } else {
1806     // %gs:0x14 on i386
1807     Offset = 0x14;
1808     AddressSpace = 256;
1809   }
1810   return true;
1811 }
1812
1813 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1814                                             unsigned DestAS) const {
1815   assert(SrcAS != DestAS && "Expected different address spaces!");
1816
1817   return SrcAS < 256 && DestAS < 256;
1818 }
1819
1820 //===----------------------------------------------------------------------===//
1821 //               Return Value Calling Convention Implementation
1822 //===----------------------------------------------------------------------===//
1823
1824 #include "X86GenCallingConv.inc"
1825
1826 bool
1827 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1828                                   MachineFunction &MF, bool isVarArg,
1829                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1830                         LLVMContext &Context) const {
1831   SmallVector<CCValAssign, 16> RVLocs;
1832   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1833                  RVLocs, Context);
1834   return CCInfo.CheckReturn(Outs, RetCC_X86);
1835 }
1836
1837 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1838   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1839   return ScratchRegs;
1840 }
1841
1842 SDValue
1843 X86TargetLowering::LowerReturn(SDValue Chain,
1844                                CallingConv::ID CallConv, bool isVarArg,
1845                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1846                                const SmallVectorImpl<SDValue> &OutVals,
1847                                SDLoc dl, SelectionDAG &DAG) const {
1848   MachineFunction &MF = DAG.getMachineFunction();
1849   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1850
1851   SmallVector<CCValAssign, 16> RVLocs;
1852   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1853                  RVLocs, *DAG.getContext());
1854   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1855
1856   SDValue Flag;
1857   SmallVector<SDValue, 6> RetOps;
1858   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1859   // Operand #1 = Bytes To Pop
1860   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1861                    MVT::i16));
1862
1863   // Copy the result values into the output registers.
1864   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1865     CCValAssign &VA = RVLocs[i];
1866     assert(VA.isRegLoc() && "Can only return in registers!");
1867     SDValue ValToCopy = OutVals[i];
1868     EVT ValVT = ValToCopy.getValueType();
1869
1870     // Promote values to the appropriate types
1871     if (VA.getLocInfo() == CCValAssign::SExt)
1872       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1873     else if (VA.getLocInfo() == CCValAssign::ZExt)
1874       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1875     else if (VA.getLocInfo() == CCValAssign::AExt)
1876       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1877     else if (VA.getLocInfo() == CCValAssign::BCvt)
1878       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1879
1880     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1881            "Unexpected FP-extend for return value.");  
1882
1883     // If this is x86-64, and we disabled SSE, we can't return FP values,
1884     // or SSE or MMX vectors.
1885     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1886          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1887           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1888       report_fatal_error("SSE register return with SSE disabled");
1889     }
1890     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1891     // llvm-gcc has never done it right and no one has noticed, so this
1892     // should be OK for now.
1893     if (ValVT == MVT::f64 &&
1894         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1895       report_fatal_error("SSE2 register return with SSE2 disabled");
1896
1897     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1898     // the RET instruction and handled by the FP Stackifier.
1899     if (VA.getLocReg() == X86::ST0 ||
1900         VA.getLocReg() == X86::ST1) {
1901       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1902       // change the value to the FP stack register class.
1903       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1904         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1905       RetOps.push_back(ValToCopy);
1906       // Don't emit a copytoreg.
1907       continue;
1908     }
1909
1910     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1911     // which is returned in RAX / RDX.
1912     if (Subtarget->is64Bit()) {
1913       if (ValVT == MVT::x86mmx) {
1914         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1915           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1916           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1917                                   ValToCopy);
1918           // If we don't have SSE2 available, convert to v4f32 so the generated
1919           // register is legal.
1920           if (!Subtarget->hasSSE2())
1921             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1922         }
1923       }
1924     }
1925
1926     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1927     Flag = Chain.getValue(1);
1928     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1929   }
1930
1931   // The x86-64 ABIs require that for returning structs by value we copy
1932   // the sret argument into %rax/%eax (depending on ABI) for the return.
1933   // Win32 requires us to put the sret argument to %eax as well.
1934   // We saved the argument into a virtual register in the entry block,
1935   // so now we copy the value out and into %rax/%eax.
1936   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1937       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1938     MachineFunction &MF = DAG.getMachineFunction();
1939     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1940     unsigned Reg = FuncInfo->getSRetReturnReg();
1941     assert(Reg &&
1942            "SRetReturnReg should have been set in LowerFormalArguments().");
1943     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1944
1945     unsigned RetValReg
1946         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1947           X86::RAX : X86::EAX;
1948     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1949     Flag = Chain.getValue(1);
1950
1951     // RAX/EAX now acts like a return value.
1952     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1953   }
1954
1955   RetOps[0] = Chain;  // Update chain.
1956
1957   // Add the flag if we have it.
1958   if (Flag.getNode())
1959     RetOps.push_back(Flag);
1960
1961   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1962 }
1963
1964 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1965   if (N->getNumValues() != 1)
1966     return false;
1967   if (!N->hasNUsesOfValue(1, 0))
1968     return false;
1969
1970   SDValue TCChain = Chain;
1971   SDNode *Copy = *N->use_begin();
1972   if (Copy->getOpcode() == ISD::CopyToReg) {
1973     // If the copy has a glue operand, we conservatively assume it isn't safe to
1974     // perform a tail call.
1975     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1976       return false;
1977     TCChain = Copy->getOperand(0);
1978   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1979     return false;
1980
1981   bool HasRet = false;
1982   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1983        UI != UE; ++UI) {
1984     if (UI->getOpcode() != X86ISD::RET_FLAG)
1985       return false;
1986     HasRet = true;
1987   }
1988
1989   if (!HasRet)
1990     return false;
1991
1992   Chain = TCChain;
1993   return true;
1994 }
1995
1996 MVT
1997 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1998                                             ISD::NodeType ExtendKind) const {
1999   MVT ReturnMVT;
2000   // TODO: Is this also valid on 32-bit?
2001   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2002     ReturnMVT = MVT::i8;
2003   else
2004     ReturnMVT = MVT::i32;
2005
2006   MVT MinVT = getRegisterType(ReturnMVT);
2007   return VT.bitsLT(MinVT) ? MinVT : VT;
2008 }
2009
2010 /// LowerCallResult - Lower the result values of a call into the
2011 /// appropriate copies out of appropriate physical registers.
2012 ///
2013 SDValue
2014 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2015                                    CallingConv::ID CallConv, bool isVarArg,
2016                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2017                                    SDLoc dl, SelectionDAG &DAG,
2018                                    SmallVectorImpl<SDValue> &InVals) const {
2019
2020   // Assign locations to each value returned by this call.
2021   SmallVector<CCValAssign, 16> RVLocs;
2022   bool Is64Bit = Subtarget->is64Bit();
2023   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2024                  getTargetMachine(), RVLocs, *DAG.getContext());
2025   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2026
2027   // Copy all of the result registers out of their specified physreg.
2028   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2029     CCValAssign &VA = RVLocs[i];
2030     EVT CopyVT = VA.getValVT();
2031
2032     // If this is x86-64, and we disabled SSE, we can't return FP values
2033     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2034         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2035       report_fatal_error("SSE register return with SSE disabled");
2036     }
2037
2038     SDValue Val;
2039
2040     // If this is a call to a function that returns an fp value on the floating
2041     // point stack, we must guarantee the value is popped from the stack, so
2042     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2043     // if the return value is not used. We use the FpPOP_RETVAL instruction
2044     // instead.
2045     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2046       // If we prefer to use the value in xmm registers, copy it out as f80 and
2047       // use a truncate to move it from fp stack reg to xmm reg.
2048       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2049       SDValue Ops[] = { Chain, InFlag };
2050       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2051                                          MVT::Other, MVT::Glue, Ops), 1);
2052       Val = Chain.getValue(0);
2053
2054       // Round the f80 to the right size, which also moves it to the appropriate
2055       // xmm register.
2056       if (CopyVT != VA.getValVT())
2057         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2058                           // This truncation won't change the value.
2059                           DAG.getIntPtrConstant(1));
2060     } else {
2061       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2062                                  CopyVT, InFlag).getValue(1);
2063       Val = Chain.getValue(0);
2064     }
2065     InFlag = Chain.getValue(2);
2066     InVals.push_back(Val);
2067   }
2068
2069   return Chain;
2070 }
2071
2072 //===----------------------------------------------------------------------===//
2073 //                C & StdCall & Fast Calling Convention implementation
2074 //===----------------------------------------------------------------------===//
2075 //  StdCall calling convention seems to be standard for many Windows' API
2076 //  routines and around. It differs from C calling convention just a little:
2077 //  callee should clean up the stack, not caller. Symbols should be also
2078 //  decorated in some fancy way :) It doesn't support any vector arguments.
2079 //  For info on fast calling convention see Fast Calling Convention (tail call)
2080 //  implementation LowerX86_32FastCCCallTo.
2081
2082 /// CallIsStructReturn - Determines whether a call uses struct return
2083 /// semantics.
2084 enum StructReturnType {
2085   NotStructReturn,
2086   RegStructReturn,
2087   StackStructReturn
2088 };
2089 static StructReturnType
2090 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2091   if (Outs.empty())
2092     return NotStructReturn;
2093
2094   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2095   if (!Flags.isSRet())
2096     return NotStructReturn;
2097   if (Flags.isInReg())
2098     return RegStructReturn;
2099   return StackStructReturn;
2100 }
2101
2102 /// ArgsAreStructReturn - Determines whether a function uses struct
2103 /// return semantics.
2104 static StructReturnType
2105 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2106   if (Ins.empty())
2107     return NotStructReturn;
2108
2109   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2110   if (!Flags.isSRet())
2111     return NotStructReturn;
2112   if (Flags.isInReg())
2113     return RegStructReturn;
2114   return StackStructReturn;
2115 }
2116
2117 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2118 /// by "Src" to address "Dst" with size and alignment information specified by
2119 /// the specific parameter attribute. The copy will be passed as a byval
2120 /// function parameter.
2121 static SDValue
2122 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2123                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2124                           SDLoc dl) {
2125   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2126
2127   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2128                        /*isVolatile*/false, /*AlwaysInline=*/true,
2129                        MachinePointerInfo(), MachinePointerInfo());
2130 }
2131
2132 /// IsTailCallConvention - Return true if the calling convention is one that
2133 /// supports tail call optimization.
2134 static bool IsTailCallConvention(CallingConv::ID CC) {
2135   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2136           CC == CallingConv::HiPE);
2137 }
2138
2139 /// \brief Return true if the calling convention is a C calling convention.
2140 static bool IsCCallConvention(CallingConv::ID CC) {
2141   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2142           CC == CallingConv::X86_64_SysV);
2143 }
2144
2145 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2146   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2147     return false;
2148
2149   CallSite CS(CI);
2150   CallingConv::ID CalleeCC = CS.getCallingConv();
2151   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2152     return false;
2153
2154   return true;
2155 }
2156
2157 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2158 /// a tailcall target by changing its ABI.
2159 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2160                                    bool GuaranteedTailCallOpt) {
2161   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2162 }
2163
2164 SDValue
2165 X86TargetLowering::LowerMemArgument(SDValue Chain,
2166                                     CallingConv::ID CallConv,
2167                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2168                                     SDLoc dl, SelectionDAG &DAG,
2169                                     const CCValAssign &VA,
2170                                     MachineFrameInfo *MFI,
2171                                     unsigned i) const {
2172   // Create the nodes corresponding to a load from this parameter slot.
2173   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2174   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2175                               getTargetMachine().Options.GuaranteedTailCallOpt);
2176   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2177   EVT ValVT;
2178
2179   // If value is passed by pointer we have address passed instead of the value
2180   // itself.
2181   if (VA.getLocInfo() == CCValAssign::Indirect)
2182     ValVT = VA.getLocVT();
2183   else
2184     ValVT = VA.getValVT();
2185
2186   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2187   // changed with more analysis.
2188   // In case of tail call optimization mark all arguments mutable. Since they
2189   // could be overwritten by lowering of arguments in case of a tail call.
2190   if (Flags.isByVal()) {
2191     unsigned Bytes = Flags.getByValSize();
2192     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2193     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2194     return DAG.getFrameIndex(FI, getPointerTy());
2195   } else {
2196     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2197                                     VA.getLocMemOffset(), isImmutable);
2198     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2199     return DAG.getLoad(ValVT, dl, Chain, FIN,
2200                        MachinePointerInfo::getFixedStack(FI),
2201                        false, false, false, 0);
2202   }
2203 }
2204
2205 SDValue
2206 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2207                                         CallingConv::ID CallConv,
2208                                         bool isVarArg,
2209                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2210                                         SDLoc dl,
2211                                         SelectionDAG &DAG,
2212                                         SmallVectorImpl<SDValue> &InVals)
2213                                           const {
2214   MachineFunction &MF = DAG.getMachineFunction();
2215   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2216
2217   const Function* Fn = MF.getFunction();
2218   if (Fn->hasExternalLinkage() &&
2219       Subtarget->isTargetCygMing() &&
2220       Fn->getName() == "main")
2221     FuncInfo->setForceFramePointer(true);
2222
2223   MachineFrameInfo *MFI = MF.getFrameInfo();
2224   bool Is64Bit = Subtarget->is64Bit();
2225   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2226
2227   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2228          "Var args not supported with calling convention fastcc, ghc or hipe");
2229
2230   // Assign locations to all of the incoming arguments.
2231   SmallVector<CCValAssign, 16> ArgLocs;
2232   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2233                  ArgLocs, *DAG.getContext());
2234
2235   // Allocate shadow area for Win64
2236   if (IsWin64)
2237     CCInfo.AllocateStack(32, 8);
2238
2239   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2240
2241   unsigned LastVal = ~0U;
2242   SDValue ArgValue;
2243   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2244     CCValAssign &VA = ArgLocs[i];
2245     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2246     // places.
2247     assert(VA.getValNo() != LastVal &&
2248            "Don't support value assigned to multiple locs yet");
2249     (void)LastVal;
2250     LastVal = VA.getValNo();
2251
2252     if (VA.isRegLoc()) {
2253       EVT RegVT = VA.getLocVT();
2254       const TargetRegisterClass *RC;
2255       if (RegVT == MVT::i32)
2256         RC = &X86::GR32RegClass;
2257       else if (Is64Bit && RegVT == MVT::i64)
2258         RC = &X86::GR64RegClass;
2259       else if (RegVT == MVT::f32)
2260         RC = &X86::FR32RegClass;
2261       else if (RegVT == MVT::f64)
2262         RC = &X86::FR64RegClass;
2263       else if (RegVT.is512BitVector())
2264         RC = &X86::VR512RegClass;
2265       else if (RegVT.is256BitVector())
2266         RC = &X86::VR256RegClass;
2267       else if (RegVT.is128BitVector())
2268         RC = &X86::VR128RegClass;
2269       else if (RegVT == MVT::x86mmx)
2270         RC = &X86::VR64RegClass;
2271       else if (RegVT == MVT::i1)
2272         RC = &X86::VK1RegClass;
2273       else if (RegVT == MVT::v8i1)
2274         RC = &X86::VK8RegClass;
2275       else if (RegVT == MVT::v16i1)
2276         RC = &X86::VK16RegClass;
2277       else
2278         llvm_unreachable("Unknown argument type!");
2279
2280       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2281       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2282
2283       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2284       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2285       // right size.
2286       if (VA.getLocInfo() == CCValAssign::SExt)
2287         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2288                                DAG.getValueType(VA.getValVT()));
2289       else if (VA.getLocInfo() == CCValAssign::ZExt)
2290         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2291                                DAG.getValueType(VA.getValVT()));
2292       else if (VA.getLocInfo() == CCValAssign::BCvt)
2293         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2294
2295       if (VA.isExtInLoc()) {
2296         // Handle MMX values passed in XMM regs.
2297         if (RegVT.isVector())
2298           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2299         else
2300           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2301       }
2302     } else {
2303       assert(VA.isMemLoc());
2304       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2305     }
2306
2307     // If value is passed via pointer - do a load.
2308     if (VA.getLocInfo() == CCValAssign::Indirect)
2309       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2310                              MachinePointerInfo(), false, false, false, 0);
2311
2312     InVals.push_back(ArgValue);
2313   }
2314
2315   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2316     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2317       // The x86-64 ABIs require that for returning structs by value we copy
2318       // the sret argument into %rax/%eax (depending on ABI) for the return.
2319       // Win32 requires us to put the sret argument to %eax as well.
2320       // Save the argument into a virtual register so that we can access it
2321       // from the return points.
2322       if (Ins[i].Flags.isSRet()) {
2323         unsigned Reg = FuncInfo->getSRetReturnReg();
2324         if (!Reg) {
2325           MVT PtrTy = getPointerTy();
2326           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2327           FuncInfo->setSRetReturnReg(Reg);
2328         }
2329         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2330         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2331         break;
2332       }
2333     }
2334   }
2335
2336   unsigned StackSize = CCInfo.getNextStackOffset();
2337   // Align stack specially for tail calls.
2338   if (FuncIsMadeTailCallSafe(CallConv,
2339                              MF.getTarget().Options.GuaranteedTailCallOpt))
2340     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2341
2342   // If the function takes variable number of arguments, make a frame index for
2343   // the start of the first vararg value... for expansion of llvm.va_start.
2344   if (isVarArg) {
2345     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2346                     CallConv != CallingConv::X86_ThisCall)) {
2347       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2348     }
2349     if (Is64Bit) {
2350       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2351
2352       // FIXME: We should really autogenerate these arrays
2353       static const MCPhysReg GPR64ArgRegsWin64[] = {
2354         X86::RCX, X86::RDX, X86::R8,  X86::R9
2355       };
2356       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2357         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2358       };
2359       static const MCPhysReg XMMArgRegs64Bit[] = {
2360         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2361         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2362       };
2363       const MCPhysReg *GPR64ArgRegs;
2364       unsigned NumXMMRegs = 0;
2365
2366       if (IsWin64) {
2367         // The XMM registers which might contain var arg parameters are shadowed
2368         // in their paired GPR.  So we only need to save the GPR to their home
2369         // slots.
2370         TotalNumIntRegs = 4;
2371         GPR64ArgRegs = GPR64ArgRegsWin64;
2372       } else {
2373         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2374         GPR64ArgRegs = GPR64ArgRegs64Bit;
2375
2376         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2377                                                 TotalNumXMMRegs);
2378       }
2379       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2380                                                        TotalNumIntRegs);
2381
2382       bool NoImplicitFloatOps = Fn->getAttributes().
2383         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2384       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2385              "SSE register cannot be used when SSE is disabled!");
2386       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2387                NoImplicitFloatOps) &&
2388              "SSE register cannot be used when SSE is disabled!");
2389       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2390           !Subtarget->hasSSE1())
2391         // Kernel mode asks for SSE to be disabled, so don't push them
2392         // on the stack.
2393         TotalNumXMMRegs = 0;
2394
2395       if (IsWin64) {
2396         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2397         // Get to the caller-allocated home save location.  Add 8 to account
2398         // for the return address.
2399         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2400         FuncInfo->setRegSaveFrameIndex(
2401           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2402         // Fixup to set vararg frame on shadow area (4 x i64).
2403         if (NumIntRegs < 4)
2404           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2405       } else {
2406         // For X86-64, if there are vararg parameters that are passed via
2407         // registers, then we must store them to their spots on the stack so
2408         // they may be loaded by deferencing the result of va_next.
2409         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2410         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2411         FuncInfo->setRegSaveFrameIndex(
2412           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2413                                false));
2414       }
2415
2416       // Store the integer parameter registers.
2417       SmallVector<SDValue, 8> MemOps;
2418       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2419                                         getPointerTy());
2420       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2421       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2422         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2423                                   DAG.getIntPtrConstant(Offset));
2424         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2425                                      &X86::GR64RegClass);
2426         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2427         SDValue Store =
2428           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2429                        MachinePointerInfo::getFixedStack(
2430                          FuncInfo->getRegSaveFrameIndex(), Offset),
2431                        false, false, 0);
2432         MemOps.push_back(Store);
2433         Offset += 8;
2434       }
2435
2436       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2437         // Now store the XMM (fp + vector) parameter registers.
2438         SmallVector<SDValue, 11> SaveXMMOps;
2439         SaveXMMOps.push_back(Chain);
2440
2441         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2442         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2443         SaveXMMOps.push_back(ALVal);
2444
2445         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2446                                FuncInfo->getRegSaveFrameIndex()));
2447         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2448                                FuncInfo->getVarArgsFPOffset()));
2449
2450         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2451           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2452                                        &X86::VR128RegClass);
2453           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2454           SaveXMMOps.push_back(Val);
2455         }
2456         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2457                                      MVT::Other, SaveXMMOps));
2458       }
2459
2460       if (!MemOps.empty())
2461         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2462     }
2463   }
2464
2465   // Some CCs need callee pop.
2466   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2467                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2468     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2469   } else {
2470     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2471     // If this is an sret function, the return should pop the hidden pointer.
2472     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2473         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2474         argsAreStructReturn(Ins) == StackStructReturn)
2475       FuncInfo->setBytesToPopOnReturn(4);
2476   }
2477
2478   if (!Is64Bit) {
2479     // RegSaveFrameIndex is X86-64 only.
2480     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2481     if (CallConv == CallingConv::X86_FastCall ||
2482         CallConv == CallingConv::X86_ThisCall)
2483       // fastcc functions can't have varargs.
2484       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2485   }
2486
2487   FuncInfo->setArgumentStackSize(StackSize);
2488
2489   return Chain;
2490 }
2491
2492 SDValue
2493 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2494                                     SDValue StackPtr, SDValue Arg,
2495                                     SDLoc dl, SelectionDAG &DAG,
2496                                     const CCValAssign &VA,
2497                                     ISD::ArgFlagsTy Flags) const {
2498   unsigned LocMemOffset = VA.getLocMemOffset();
2499   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2500   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2501   if (Flags.isByVal())
2502     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2503
2504   return DAG.getStore(Chain, dl, Arg, PtrOff,
2505                       MachinePointerInfo::getStack(LocMemOffset),
2506                       false, false, 0);
2507 }
2508
2509 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2510 /// optimization is performed and it is required.
2511 SDValue
2512 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2513                                            SDValue &OutRetAddr, SDValue Chain,
2514                                            bool IsTailCall, bool Is64Bit,
2515                                            int FPDiff, SDLoc dl) const {
2516   // Adjust the Return address stack slot.
2517   EVT VT = getPointerTy();
2518   OutRetAddr = getReturnAddressFrameIndex(DAG);
2519
2520   // Load the "old" Return address.
2521   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2522                            false, false, false, 0);
2523   return SDValue(OutRetAddr.getNode(), 1);
2524 }
2525
2526 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2527 /// optimization is performed and it is required (FPDiff!=0).
2528 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2529                                         SDValue Chain, SDValue RetAddrFrIdx,
2530                                         EVT PtrVT, unsigned SlotSize,
2531                                         int FPDiff, SDLoc dl) {
2532   // Store the return address to the appropriate stack slot.
2533   if (!FPDiff) return Chain;
2534   // Calculate the new stack slot for the return address.
2535   int NewReturnAddrFI =
2536     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2537                                          false);
2538   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2539   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2540                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2541                        false, false, 0);
2542   return Chain;
2543 }
2544
2545 SDValue
2546 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2547                              SmallVectorImpl<SDValue> &InVals) const {
2548   SelectionDAG &DAG                     = CLI.DAG;
2549   SDLoc &dl                             = CLI.DL;
2550   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2551   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2552   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2553   SDValue Chain                         = CLI.Chain;
2554   SDValue Callee                        = CLI.Callee;
2555   CallingConv::ID CallConv              = CLI.CallConv;
2556   bool &isTailCall                      = CLI.IsTailCall;
2557   bool isVarArg                         = CLI.IsVarArg;
2558
2559   MachineFunction &MF = DAG.getMachineFunction();
2560   bool Is64Bit        = Subtarget->is64Bit();
2561   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2562   StructReturnType SR = callIsStructReturn(Outs);
2563   bool IsSibcall      = false;
2564
2565   if (MF.getTarget().Options.DisableTailCalls)
2566     isTailCall = false;
2567
2568   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2569   if (IsMustTail) {
2570     // Force this to be a tail call.  The verifier rules are enough to ensure
2571     // that we can lower this successfully without moving the return address
2572     // around.
2573     isTailCall = true;
2574   } else if (isTailCall) {
2575     // Check if it's really possible to do a tail call.
2576     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2577                     isVarArg, SR != NotStructReturn,
2578                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2579                     Outs, OutVals, Ins, DAG);
2580
2581     // Sibcalls are automatically detected tailcalls which do not require
2582     // ABI changes.
2583     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2584       IsSibcall = true;
2585
2586     if (isTailCall)
2587       ++NumTailCalls;
2588   }
2589
2590   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2591          "Var args not supported with calling convention fastcc, ghc or hipe");
2592
2593   // Analyze operands of the call, assigning locations to each operand.
2594   SmallVector<CCValAssign, 16> ArgLocs;
2595   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2596                  ArgLocs, *DAG.getContext());
2597
2598   // Allocate shadow area for Win64
2599   if (IsWin64)
2600     CCInfo.AllocateStack(32, 8);
2601
2602   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2603
2604   // Get a count of how many bytes are to be pushed on the stack.
2605   unsigned NumBytes = CCInfo.getNextStackOffset();
2606   if (IsSibcall)
2607     // This is a sibcall. The memory operands are available in caller's
2608     // own caller's stack.
2609     NumBytes = 0;
2610   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2611            IsTailCallConvention(CallConv))
2612     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2613
2614   int FPDiff = 0;
2615   if (isTailCall && !IsSibcall && !IsMustTail) {
2616     // Lower arguments at fp - stackoffset + fpdiff.
2617     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2618     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2619
2620     FPDiff = NumBytesCallerPushed - NumBytes;
2621
2622     // Set the delta of movement of the returnaddr stackslot.
2623     // But only set if delta is greater than previous delta.
2624     if (FPDiff < X86Info->getTCReturnAddrDelta())
2625       X86Info->setTCReturnAddrDelta(FPDiff);
2626   }
2627
2628   unsigned NumBytesToPush = NumBytes;
2629   unsigned NumBytesToPop = NumBytes;
2630
2631   // If we have an inalloca argument, all stack space has already been allocated
2632   // for us and be right at the top of the stack.  We don't support multiple
2633   // arguments passed in memory when using inalloca.
2634   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2635     NumBytesToPush = 0;
2636     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2637            "an inalloca argument must be the only memory argument");
2638   }
2639
2640   if (!IsSibcall)
2641     Chain = DAG.getCALLSEQ_START(
2642         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2643
2644   SDValue RetAddrFrIdx;
2645   // Load return address for tail calls.
2646   if (isTailCall && FPDiff)
2647     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2648                                     Is64Bit, FPDiff, dl);
2649
2650   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2651   SmallVector<SDValue, 8> MemOpChains;
2652   SDValue StackPtr;
2653
2654   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2655   // of tail call optimization arguments are handle later.
2656   const X86RegisterInfo *RegInfo =
2657     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2658   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2659     // Skip inalloca arguments, they have already been written.
2660     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2661     if (Flags.isInAlloca())
2662       continue;
2663
2664     CCValAssign &VA = ArgLocs[i];
2665     EVT RegVT = VA.getLocVT();
2666     SDValue Arg = OutVals[i];
2667     bool isByVal = Flags.isByVal();
2668
2669     // Promote the value if needed.
2670     switch (VA.getLocInfo()) {
2671     default: llvm_unreachable("Unknown loc info!");
2672     case CCValAssign::Full: break;
2673     case CCValAssign::SExt:
2674       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2675       break;
2676     case CCValAssign::ZExt:
2677       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2678       break;
2679     case CCValAssign::AExt:
2680       if (RegVT.is128BitVector()) {
2681         // Special case: passing MMX values in XMM registers.
2682         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2683         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2684         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2685       } else
2686         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2687       break;
2688     case CCValAssign::BCvt:
2689       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2690       break;
2691     case CCValAssign::Indirect: {
2692       // Store the argument.
2693       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2694       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2695       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2696                            MachinePointerInfo::getFixedStack(FI),
2697                            false, false, 0);
2698       Arg = SpillSlot;
2699       break;
2700     }
2701     }
2702
2703     if (VA.isRegLoc()) {
2704       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2705       if (isVarArg && IsWin64) {
2706         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2707         // shadow reg if callee is a varargs function.
2708         unsigned ShadowReg = 0;
2709         switch (VA.getLocReg()) {
2710         case X86::XMM0: ShadowReg = X86::RCX; break;
2711         case X86::XMM1: ShadowReg = X86::RDX; break;
2712         case X86::XMM2: ShadowReg = X86::R8; break;
2713         case X86::XMM3: ShadowReg = X86::R9; break;
2714         }
2715         if (ShadowReg)
2716           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2717       }
2718     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2719       assert(VA.isMemLoc());
2720       if (!StackPtr.getNode())
2721         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2722                                       getPointerTy());
2723       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2724                                              dl, DAG, VA, Flags));
2725     }
2726   }
2727
2728   if (!MemOpChains.empty())
2729     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2730
2731   if (Subtarget->isPICStyleGOT()) {
2732     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2733     // GOT pointer.
2734     if (!isTailCall) {
2735       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2736                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2737     } else {
2738       // If we are tail calling and generating PIC/GOT style code load the
2739       // address of the callee into ECX. The value in ecx is used as target of
2740       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2741       // for tail calls on PIC/GOT architectures. Normally we would just put the
2742       // address of GOT into ebx and then call target@PLT. But for tail calls
2743       // ebx would be restored (since ebx is callee saved) before jumping to the
2744       // target@PLT.
2745
2746       // Note: The actual moving to ECX is done further down.
2747       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2748       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2749           !G->getGlobal()->hasProtectedVisibility())
2750         Callee = LowerGlobalAddress(Callee, DAG);
2751       else if (isa<ExternalSymbolSDNode>(Callee))
2752         Callee = LowerExternalSymbol(Callee, DAG);
2753     }
2754   }
2755
2756   if (Is64Bit && isVarArg && !IsWin64) {
2757     // From AMD64 ABI document:
2758     // For calls that may call functions that use varargs or stdargs
2759     // (prototype-less calls or calls to functions containing ellipsis (...) in
2760     // the declaration) %al is used as hidden argument to specify the number
2761     // of SSE registers used. The contents of %al do not need to match exactly
2762     // the number of registers, but must be an ubound on the number of SSE
2763     // registers used and is in the range 0 - 8 inclusive.
2764
2765     // Count the number of XMM registers allocated.
2766     static const MCPhysReg XMMArgRegs[] = {
2767       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2768       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2769     };
2770     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2771     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2772            && "SSE registers cannot be used when SSE is disabled");
2773
2774     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2775                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2776   }
2777
2778   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2779   // don't need this because the eligibility check rejects calls that require
2780   // shuffling arguments passed in memory.
2781   if (!IsSibcall && isTailCall) {
2782     // Force all the incoming stack arguments to be loaded from the stack
2783     // before any new outgoing arguments are stored to the stack, because the
2784     // outgoing stack slots may alias the incoming argument stack slots, and
2785     // the alias isn't otherwise explicit. This is slightly more conservative
2786     // than necessary, because it means that each store effectively depends
2787     // on every argument instead of just those arguments it would clobber.
2788     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2789
2790     SmallVector<SDValue, 8> MemOpChains2;
2791     SDValue FIN;
2792     int FI = 0;
2793     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2794       CCValAssign &VA = ArgLocs[i];
2795       if (VA.isRegLoc())
2796         continue;
2797       assert(VA.isMemLoc());
2798       SDValue Arg = OutVals[i];
2799       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2800       // Skip inalloca arguments.  They don't require any work.
2801       if (Flags.isInAlloca())
2802         continue;
2803       // Create frame index.
2804       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2805       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2806       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2807       FIN = DAG.getFrameIndex(FI, getPointerTy());
2808
2809       if (Flags.isByVal()) {
2810         // Copy relative to framepointer.
2811         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2812         if (!StackPtr.getNode())
2813           StackPtr = DAG.getCopyFromReg(Chain, dl,
2814                                         RegInfo->getStackRegister(),
2815                                         getPointerTy());
2816         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2817
2818         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2819                                                          ArgChain,
2820                                                          Flags, DAG, dl));
2821       } else {
2822         // Store relative to framepointer.
2823         MemOpChains2.push_back(
2824           DAG.getStore(ArgChain, dl, Arg, FIN,
2825                        MachinePointerInfo::getFixedStack(FI),
2826                        false, false, 0));
2827       }
2828     }
2829
2830     if (!MemOpChains2.empty())
2831       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2832
2833     // Store the return address to the appropriate stack slot.
2834     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2835                                      getPointerTy(), RegInfo->getSlotSize(),
2836                                      FPDiff, dl);
2837   }
2838
2839   // Build a sequence of copy-to-reg nodes chained together with token chain
2840   // and flag operands which copy the outgoing args into registers.
2841   SDValue InFlag;
2842   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2843     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2844                              RegsToPass[i].second, InFlag);
2845     InFlag = Chain.getValue(1);
2846   }
2847
2848   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2849     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2850     // In the 64-bit large code model, we have to make all calls
2851     // through a register, since the call instruction's 32-bit
2852     // pc-relative offset may not be large enough to hold the whole
2853     // address.
2854   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2855     // If the callee is a GlobalAddress node (quite common, every direct call
2856     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2857     // it.
2858
2859     // We should use extra load for direct calls to dllimported functions in
2860     // non-JIT mode.
2861     const GlobalValue *GV = G->getGlobal();
2862     if (!GV->hasDLLImportStorageClass()) {
2863       unsigned char OpFlags = 0;
2864       bool ExtraLoad = false;
2865       unsigned WrapperKind = ISD::DELETED_NODE;
2866
2867       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2868       // external symbols most go through the PLT in PIC mode.  If the symbol
2869       // has hidden or protected visibility, or if it is static or local, then
2870       // we don't need to use the PLT - we can directly call it.
2871       if (Subtarget->isTargetELF() &&
2872           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2873           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2874         OpFlags = X86II::MO_PLT;
2875       } else if (Subtarget->isPICStyleStubAny() &&
2876                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2877                  (!Subtarget->getTargetTriple().isMacOSX() ||
2878                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2879         // PC-relative references to external symbols should go through $stub,
2880         // unless we're building with the leopard linker or later, which
2881         // automatically synthesizes these stubs.
2882         OpFlags = X86II::MO_DARWIN_STUB;
2883       } else if (Subtarget->isPICStyleRIPRel() &&
2884                  isa<Function>(GV) &&
2885                  cast<Function>(GV)->getAttributes().
2886                    hasAttribute(AttributeSet::FunctionIndex,
2887                                 Attribute::NonLazyBind)) {
2888         // If the function is marked as non-lazy, generate an indirect call
2889         // which loads from the GOT directly. This avoids runtime overhead
2890         // at the cost of eager binding (and one extra byte of encoding).
2891         OpFlags = X86II::MO_GOTPCREL;
2892         WrapperKind = X86ISD::WrapperRIP;
2893         ExtraLoad = true;
2894       }
2895
2896       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2897                                           G->getOffset(), OpFlags);
2898
2899       // Add a wrapper if needed.
2900       if (WrapperKind != ISD::DELETED_NODE)
2901         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2902       // Add extra indirection if needed.
2903       if (ExtraLoad)
2904         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2905                              MachinePointerInfo::getGOT(),
2906                              false, false, false, 0);
2907     }
2908   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2909     unsigned char OpFlags = 0;
2910
2911     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2912     // external symbols should go through the PLT.
2913     if (Subtarget->isTargetELF() &&
2914         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2915       OpFlags = X86II::MO_PLT;
2916     } else if (Subtarget->isPICStyleStubAny() &&
2917                (!Subtarget->getTargetTriple().isMacOSX() ||
2918                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2919       // PC-relative references to external symbols should go through $stub,
2920       // unless we're building with the leopard linker or later, which
2921       // automatically synthesizes these stubs.
2922       OpFlags = X86II::MO_DARWIN_STUB;
2923     }
2924
2925     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2926                                          OpFlags);
2927   }
2928
2929   // Returns a chain & a flag for retval copy to use.
2930   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2931   SmallVector<SDValue, 8> Ops;
2932
2933   if (!IsSibcall && isTailCall) {
2934     Chain = DAG.getCALLSEQ_END(Chain,
2935                                DAG.getIntPtrConstant(NumBytesToPop, true),
2936                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2937     InFlag = Chain.getValue(1);
2938   }
2939
2940   Ops.push_back(Chain);
2941   Ops.push_back(Callee);
2942
2943   if (isTailCall)
2944     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2945
2946   // Add argument registers to the end of the list so that they are known live
2947   // into the call.
2948   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2949     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2950                                   RegsToPass[i].second.getValueType()));
2951
2952   // Add a register mask operand representing the call-preserved registers.
2953   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2954   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2955   assert(Mask && "Missing call preserved mask for calling convention");
2956   Ops.push_back(DAG.getRegisterMask(Mask));
2957
2958   if (InFlag.getNode())
2959     Ops.push_back(InFlag);
2960
2961   if (isTailCall) {
2962     // We used to do:
2963     //// If this is the first return lowered for this function, add the regs
2964     //// to the liveout set for the function.
2965     // This isn't right, although it's probably harmless on x86; liveouts
2966     // should be computed from returns not tail calls.  Consider a void
2967     // function making a tail call to a function returning int.
2968     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2969   }
2970
2971   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2972   InFlag = Chain.getValue(1);
2973
2974   // Create the CALLSEQ_END node.
2975   unsigned NumBytesForCalleeToPop;
2976   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2977                        getTargetMachine().Options.GuaranteedTailCallOpt))
2978     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2979   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2980            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2981            SR == StackStructReturn)
2982     // If this is a call to a struct-return function, the callee
2983     // pops the hidden struct pointer, so we have to push it back.
2984     // This is common for Darwin/X86, Linux & Mingw32 targets.
2985     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2986     NumBytesForCalleeToPop = 4;
2987   else
2988     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2989
2990   // Returns a flag for retval copy to use.
2991   if (!IsSibcall) {
2992     Chain = DAG.getCALLSEQ_END(Chain,
2993                                DAG.getIntPtrConstant(NumBytesToPop, true),
2994                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2995                                                      true),
2996                                InFlag, dl);
2997     InFlag = Chain.getValue(1);
2998   }
2999
3000   // Handle result values, copying them out of physregs into vregs that we
3001   // return.
3002   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3003                          Ins, dl, DAG, InVals);
3004 }
3005
3006 //===----------------------------------------------------------------------===//
3007 //                Fast Calling Convention (tail call) implementation
3008 //===----------------------------------------------------------------------===//
3009
3010 //  Like std call, callee cleans arguments, convention except that ECX is
3011 //  reserved for storing the tail called function address. Only 2 registers are
3012 //  free for argument passing (inreg). Tail call optimization is performed
3013 //  provided:
3014 //                * tailcallopt is enabled
3015 //                * caller/callee are fastcc
3016 //  On X86_64 architecture with GOT-style position independent code only local
3017 //  (within module) calls are supported at the moment.
3018 //  To keep the stack aligned according to platform abi the function
3019 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3020 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3021 //  If a tail called function callee has more arguments than the caller the
3022 //  caller needs to make sure that there is room to move the RETADDR to. This is
3023 //  achieved by reserving an area the size of the argument delta right after the
3024 //  original REtADDR, but before the saved framepointer or the spilled registers
3025 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3026 //  stack layout:
3027 //    arg1
3028 //    arg2
3029 //    RETADDR
3030 //    [ new RETADDR
3031 //      move area ]
3032 //    (possible EBP)
3033 //    ESI
3034 //    EDI
3035 //    local1 ..
3036
3037 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3038 /// for a 16 byte align requirement.
3039 unsigned
3040 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3041                                                SelectionDAG& DAG) const {
3042   MachineFunction &MF = DAG.getMachineFunction();
3043   const TargetMachine &TM = MF.getTarget();
3044   const X86RegisterInfo *RegInfo =
3045     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3046   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3047   unsigned StackAlignment = TFI.getStackAlignment();
3048   uint64_t AlignMask = StackAlignment - 1;
3049   int64_t Offset = StackSize;
3050   unsigned SlotSize = RegInfo->getSlotSize();
3051   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3052     // Number smaller than 12 so just add the difference.
3053     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3054   } else {
3055     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3056     Offset = ((~AlignMask) & Offset) + StackAlignment +
3057       (StackAlignment-SlotSize);
3058   }
3059   return Offset;
3060 }
3061
3062 /// MatchingStackOffset - Return true if the given stack call argument is
3063 /// already available in the same position (relatively) of the caller's
3064 /// incoming argument stack.
3065 static
3066 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3067                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3068                          const X86InstrInfo *TII) {
3069   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3070   int FI = INT_MAX;
3071   if (Arg.getOpcode() == ISD::CopyFromReg) {
3072     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3073     if (!TargetRegisterInfo::isVirtualRegister(VR))
3074       return false;
3075     MachineInstr *Def = MRI->getVRegDef(VR);
3076     if (!Def)
3077       return false;
3078     if (!Flags.isByVal()) {
3079       if (!TII->isLoadFromStackSlot(Def, FI))
3080         return false;
3081     } else {
3082       unsigned Opcode = Def->getOpcode();
3083       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3084           Def->getOperand(1).isFI()) {
3085         FI = Def->getOperand(1).getIndex();
3086         Bytes = Flags.getByValSize();
3087       } else
3088         return false;
3089     }
3090   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3091     if (Flags.isByVal())
3092       // ByVal argument is passed in as a pointer but it's now being
3093       // dereferenced. e.g.
3094       // define @foo(%struct.X* %A) {
3095       //   tail call @bar(%struct.X* byval %A)
3096       // }
3097       return false;
3098     SDValue Ptr = Ld->getBasePtr();
3099     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3100     if (!FINode)
3101       return false;
3102     FI = FINode->getIndex();
3103   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3104     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3105     FI = FINode->getIndex();
3106     Bytes = Flags.getByValSize();
3107   } else
3108     return false;
3109
3110   assert(FI != INT_MAX);
3111   if (!MFI->isFixedObjectIndex(FI))
3112     return false;
3113   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3114 }
3115
3116 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3117 /// for tail call optimization. Targets which want to do tail call
3118 /// optimization should implement this function.
3119 bool
3120 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3121                                                      CallingConv::ID CalleeCC,
3122                                                      bool isVarArg,
3123                                                      bool isCalleeStructRet,
3124                                                      bool isCallerStructRet,
3125                                                      Type *RetTy,
3126                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3127                                     const SmallVectorImpl<SDValue> &OutVals,
3128                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3129                                                      SelectionDAG &DAG) const {
3130   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3131     return false;
3132
3133   // If -tailcallopt is specified, make fastcc functions tail-callable.
3134   const MachineFunction &MF = DAG.getMachineFunction();
3135   const Function *CallerF = MF.getFunction();
3136
3137   // If the function return type is x86_fp80 and the callee return type is not,
3138   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3139   // perform a tailcall optimization here.
3140   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3141     return false;
3142
3143   CallingConv::ID CallerCC = CallerF->getCallingConv();
3144   bool CCMatch = CallerCC == CalleeCC;
3145   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3146   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3147
3148   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3149     if (IsTailCallConvention(CalleeCC) && CCMatch)
3150       return true;
3151     return false;
3152   }
3153
3154   // Look for obvious safe cases to perform tail call optimization that do not
3155   // require ABI changes. This is what gcc calls sibcall.
3156
3157   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3158   // emit a special epilogue.
3159   const X86RegisterInfo *RegInfo =
3160     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3161   if (RegInfo->needsStackRealignment(MF))
3162     return false;
3163
3164   // Also avoid sibcall optimization if either caller or callee uses struct
3165   // return semantics.
3166   if (isCalleeStructRet || isCallerStructRet)
3167     return false;
3168
3169   // An stdcall/thiscall caller is expected to clean up its arguments; the
3170   // callee isn't going to do that.
3171   // FIXME: this is more restrictive than needed. We could produce a tailcall
3172   // when the stack adjustment matches. For example, with a thiscall that takes
3173   // only one argument.
3174   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3175                    CallerCC == CallingConv::X86_ThisCall))
3176     return false;
3177
3178   // Do not sibcall optimize vararg calls unless all arguments are passed via
3179   // registers.
3180   if (isVarArg && !Outs.empty()) {
3181
3182     // Optimizing for varargs on Win64 is unlikely to be safe without
3183     // additional testing.
3184     if (IsCalleeWin64 || IsCallerWin64)
3185       return false;
3186
3187     SmallVector<CCValAssign, 16> ArgLocs;
3188     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3189                    getTargetMachine(), ArgLocs, *DAG.getContext());
3190
3191     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3192     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3193       if (!ArgLocs[i].isRegLoc())
3194         return false;
3195   }
3196
3197   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3198   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3199   // this into a sibcall.
3200   bool Unused = false;
3201   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3202     if (!Ins[i].Used) {
3203       Unused = true;
3204       break;
3205     }
3206   }
3207   if (Unused) {
3208     SmallVector<CCValAssign, 16> RVLocs;
3209     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3210                    getTargetMachine(), RVLocs, *DAG.getContext());
3211     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3212     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3213       CCValAssign &VA = RVLocs[i];
3214       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3215         return false;
3216     }
3217   }
3218
3219   // If the calling conventions do not match, then we'd better make sure the
3220   // results are returned in the same way as what the caller expects.
3221   if (!CCMatch) {
3222     SmallVector<CCValAssign, 16> RVLocs1;
3223     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3224                     getTargetMachine(), RVLocs1, *DAG.getContext());
3225     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3226
3227     SmallVector<CCValAssign, 16> RVLocs2;
3228     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3229                     getTargetMachine(), RVLocs2, *DAG.getContext());
3230     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3231
3232     if (RVLocs1.size() != RVLocs2.size())
3233       return false;
3234     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3235       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3236         return false;
3237       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3238         return false;
3239       if (RVLocs1[i].isRegLoc()) {
3240         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3241           return false;
3242       } else {
3243         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3244           return false;
3245       }
3246     }
3247   }
3248
3249   // If the callee takes no arguments then go on to check the results of the
3250   // call.
3251   if (!Outs.empty()) {
3252     // Check if stack adjustment is needed. For now, do not do this if any
3253     // argument is passed on the stack.
3254     SmallVector<CCValAssign, 16> ArgLocs;
3255     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3256                    getTargetMachine(), ArgLocs, *DAG.getContext());
3257
3258     // Allocate shadow area for Win64
3259     if (IsCalleeWin64)
3260       CCInfo.AllocateStack(32, 8);
3261
3262     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3263     if (CCInfo.getNextStackOffset()) {
3264       MachineFunction &MF = DAG.getMachineFunction();
3265       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3266         return false;
3267
3268       // Check if the arguments are already laid out in the right way as
3269       // the caller's fixed stack objects.
3270       MachineFrameInfo *MFI = MF.getFrameInfo();
3271       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3272       const X86InstrInfo *TII =
3273         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3274       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3275         CCValAssign &VA = ArgLocs[i];
3276         SDValue Arg = OutVals[i];
3277         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3278         if (VA.getLocInfo() == CCValAssign::Indirect)
3279           return false;
3280         if (!VA.isRegLoc()) {
3281           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3282                                    MFI, MRI, TII))
3283             return false;
3284         }
3285       }
3286     }
3287
3288     // If the tailcall address may be in a register, then make sure it's
3289     // possible to register allocate for it. In 32-bit, the call address can
3290     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3291     // callee-saved registers are restored. These happen to be the same
3292     // registers used to pass 'inreg' arguments so watch out for those.
3293     if (!Subtarget->is64Bit() &&
3294         ((!isa<GlobalAddressSDNode>(Callee) &&
3295           !isa<ExternalSymbolSDNode>(Callee)) ||
3296          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3297       unsigned NumInRegs = 0;
3298       // In PIC we need an extra register to formulate the address computation
3299       // for the callee.
3300       unsigned MaxInRegs =
3301           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3302
3303       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3304         CCValAssign &VA = ArgLocs[i];
3305         if (!VA.isRegLoc())
3306           continue;
3307         unsigned Reg = VA.getLocReg();
3308         switch (Reg) {
3309         default: break;
3310         case X86::EAX: case X86::EDX: case X86::ECX:
3311           if (++NumInRegs == MaxInRegs)
3312             return false;
3313           break;
3314         }
3315       }
3316     }
3317   }
3318
3319   return true;
3320 }
3321
3322 FastISel *
3323 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3324                                   const TargetLibraryInfo *libInfo) const {
3325   return X86::createFastISel(funcInfo, libInfo);
3326 }
3327
3328 //===----------------------------------------------------------------------===//
3329 //                           Other Lowering Hooks
3330 //===----------------------------------------------------------------------===//
3331
3332 static bool MayFoldLoad(SDValue Op) {
3333   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3334 }
3335
3336 static bool MayFoldIntoStore(SDValue Op) {
3337   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3338 }
3339
3340 static bool isTargetShuffle(unsigned Opcode) {
3341   switch(Opcode) {
3342   default: return false;
3343   case X86ISD::PSHUFD:
3344   case X86ISD::PSHUFHW:
3345   case X86ISD::PSHUFLW:
3346   case X86ISD::SHUFP:
3347   case X86ISD::PALIGNR:
3348   case X86ISD::MOVLHPS:
3349   case X86ISD::MOVLHPD:
3350   case X86ISD::MOVHLPS:
3351   case X86ISD::MOVLPS:
3352   case X86ISD::MOVLPD:
3353   case X86ISD::MOVSHDUP:
3354   case X86ISD::MOVSLDUP:
3355   case X86ISD::MOVDDUP:
3356   case X86ISD::MOVSS:
3357   case X86ISD::MOVSD:
3358   case X86ISD::UNPCKL:
3359   case X86ISD::UNPCKH:
3360   case X86ISD::VPERMILP:
3361   case X86ISD::VPERM2X128:
3362   case X86ISD::VPERMI:
3363     return true;
3364   }
3365 }
3366
3367 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3368                                     SDValue V1, SelectionDAG &DAG) {
3369   switch(Opc) {
3370   default: llvm_unreachable("Unknown x86 shuffle node");
3371   case X86ISD::MOVSHDUP:
3372   case X86ISD::MOVSLDUP:
3373   case X86ISD::MOVDDUP:
3374     return DAG.getNode(Opc, dl, VT, V1);
3375   }
3376 }
3377
3378 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3379                                     SDValue V1, unsigned TargetMask,
3380                                     SelectionDAG &DAG) {
3381   switch(Opc) {
3382   default: llvm_unreachable("Unknown x86 shuffle node");
3383   case X86ISD::PSHUFD:
3384   case X86ISD::PSHUFHW:
3385   case X86ISD::PSHUFLW:
3386   case X86ISD::VPERMILP:
3387   case X86ISD::VPERMI:
3388     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3389   }
3390 }
3391
3392 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3393                                     SDValue V1, SDValue V2, unsigned TargetMask,
3394                                     SelectionDAG &DAG) {
3395   switch(Opc) {
3396   default: llvm_unreachable("Unknown x86 shuffle node");
3397   case X86ISD::PALIGNR:
3398   case X86ISD::SHUFP:
3399   case X86ISD::VPERM2X128:
3400     return DAG.getNode(Opc, dl, VT, V1, V2,
3401                        DAG.getConstant(TargetMask, MVT::i8));
3402   }
3403 }
3404
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3407   switch(Opc) {
3408   default: llvm_unreachable("Unknown x86 shuffle node");
3409   case X86ISD::MOVLHPS:
3410   case X86ISD::MOVLHPD:
3411   case X86ISD::MOVHLPS:
3412   case X86ISD::MOVLPS:
3413   case X86ISD::MOVLPD:
3414   case X86ISD::MOVSS:
3415   case X86ISD::MOVSD:
3416   case X86ISD::UNPCKL:
3417   case X86ISD::UNPCKH:
3418     return DAG.getNode(Opc, dl, VT, V1, V2);
3419   }
3420 }
3421
3422 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3423   MachineFunction &MF = DAG.getMachineFunction();
3424   const X86RegisterInfo *RegInfo =
3425     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3426   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3427   int ReturnAddrIndex = FuncInfo->getRAIndex();
3428
3429   if (ReturnAddrIndex == 0) {
3430     // Set up a frame object for the return address.
3431     unsigned SlotSize = RegInfo->getSlotSize();
3432     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3433                                                            -(int64_t)SlotSize,
3434                                                            false);
3435     FuncInfo->setRAIndex(ReturnAddrIndex);
3436   }
3437
3438   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3439 }
3440
3441 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3442                                        bool hasSymbolicDisplacement) {
3443   // Offset should fit into 32 bit immediate field.
3444   if (!isInt<32>(Offset))
3445     return false;
3446
3447   // If we don't have a symbolic displacement - we don't have any extra
3448   // restrictions.
3449   if (!hasSymbolicDisplacement)
3450     return true;
3451
3452   // FIXME: Some tweaks might be needed for medium code model.
3453   if (M != CodeModel::Small && M != CodeModel::Kernel)
3454     return false;
3455
3456   // For small code model we assume that latest object is 16MB before end of 31
3457   // bits boundary. We may also accept pretty large negative constants knowing
3458   // that all objects are in the positive half of address space.
3459   if (M == CodeModel::Small && Offset < 16*1024*1024)
3460     return true;
3461
3462   // For kernel code model we know that all object resist in the negative half
3463   // of 32bits address space. We may not accept negative offsets, since they may
3464   // be just off and we may accept pretty large positive ones.
3465   if (M == CodeModel::Kernel && Offset > 0)
3466     return true;
3467
3468   return false;
3469 }
3470
3471 /// isCalleePop - Determines whether the callee is required to pop its
3472 /// own arguments. Callee pop is necessary to support tail calls.
3473 bool X86::isCalleePop(CallingConv::ID CallingConv,
3474                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3475   if (IsVarArg)
3476     return false;
3477
3478   switch (CallingConv) {
3479   default:
3480     return false;
3481   case CallingConv::X86_StdCall:
3482     return !is64Bit;
3483   case CallingConv::X86_FastCall:
3484     return !is64Bit;
3485   case CallingConv::X86_ThisCall:
3486     return !is64Bit;
3487   case CallingConv::Fast:
3488     return TailCallOpt;
3489   case CallingConv::GHC:
3490     return TailCallOpt;
3491   case CallingConv::HiPE:
3492     return TailCallOpt;
3493   }
3494 }
3495
3496 /// \brief Return true if the condition is an unsigned comparison operation.
3497 static bool isX86CCUnsigned(unsigned X86CC) {
3498   switch (X86CC) {
3499   default: llvm_unreachable("Invalid integer condition!");
3500   case X86::COND_E:     return true;
3501   case X86::COND_G:     return false;
3502   case X86::COND_GE:    return false;
3503   case X86::COND_L:     return false;
3504   case X86::COND_LE:    return false;
3505   case X86::COND_NE:    return true;
3506   case X86::COND_B:     return true;
3507   case X86::COND_A:     return true;
3508   case X86::COND_BE:    return true;
3509   case X86::COND_AE:    return true;
3510   }
3511   llvm_unreachable("covered switch fell through?!");
3512 }
3513
3514 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3515 /// specific condition code, returning the condition code and the LHS/RHS of the
3516 /// comparison to make.
3517 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3518                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3519   if (!isFP) {
3520     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3521       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3522         // X > -1   -> X == 0, jump !sign.
3523         RHS = DAG.getConstant(0, RHS.getValueType());
3524         return X86::COND_NS;
3525       }
3526       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3527         // X < 0   -> X == 0, jump on sign.
3528         return X86::COND_S;
3529       }
3530       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3531         // X < 1   -> X <= 0
3532         RHS = DAG.getConstant(0, RHS.getValueType());
3533         return X86::COND_LE;
3534       }
3535     }
3536
3537     switch (SetCCOpcode) {
3538     default: llvm_unreachable("Invalid integer condition!");
3539     case ISD::SETEQ:  return X86::COND_E;
3540     case ISD::SETGT:  return X86::COND_G;
3541     case ISD::SETGE:  return X86::COND_GE;
3542     case ISD::SETLT:  return X86::COND_L;
3543     case ISD::SETLE:  return X86::COND_LE;
3544     case ISD::SETNE:  return X86::COND_NE;
3545     case ISD::SETULT: return X86::COND_B;
3546     case ISD::SETUGT: return X86::COND_A;
3547     case ISD::SETULE: return X86::COND_BE;
3548     case ISD::SETUGE: return X86::COND_AE;
3549     }
3550   }
3551
3552   // First determine if it is required or is profitable to flip the operands.
3553
3554   // If LHS is a foldable load, but RHS is not, flip the condition.
3555   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3556       !ISD::isNON_EXTLoad(RHS.getNode())) {
3557     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3558     std::swap(LHS, RHS);
3559   }
3560
3561   switch (SetCCOpcode) {
3562   default: break;
3563   case ISD::SETOLT:
3564   case ISD::SETOLE:
3565   case ISD::SETUGT:
3566   case ISD::SETUGE:
3567     std::swap(LHS, RHS);
3568     break;
3569   }
3570
3571   // On a floating point condition, the flags are set as follows:
3572   // ZF  PF  CF   op
3573   //  0 | 0 | 0 | X > Y
3574   //  0 | 0 | 1 | X < Y
3575   //  1 | 0 | 0 | X == Y
3576   //  1 | 1 | 1 | unordered
3577   switch (SetCCOpcode) {
3578   default: llvm_unreachable("Condcode should be pre-legalized away");
3579   case ISD::SETUEQ:
3580   case ISD::SETEQ:   return X86::COND_E;
3581   case ISD::SETOLT:              // flipped
3582   case ISD::SETOGT:
3583   case ISD::SETGT:   return X86::COND_A;
3584   case ISD::SETOLE:              // flipped
3585   case ISD::SETOGE:
3586   case ISD::SETGE:   return X86::COND_AE;
3587   case ISD::SETUGT:              // flipped
3588   case ISD::SETULT:
3589   case ISD::SETLT:   return X86::COND_B;
3590   case ISD::SETUGE:              // flipped
3591   case ISD::SETULE:
3592   case ISD::SETLE:   return X86::COND_BE;
3593   case ISD::SETONE:
3594   case ISD::SETNE:   return X86::COND_NE;
3595   case ISD::SETUO:   return X86::COND_P;
3596   case ISD::SETO:    return X86::COND_NP;
3597   case ISD::SETOEQ:
3598   case ISD::SETUNE:  return X86::COND_INVALID;
3599   }
3600 }
3601
3602 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3603 /// code. Current x86 isa includes the following FP cmov instructions:
3604 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3605 static bool hasFPCMov(unsigned X86CC) {
3606   switch (X86CC) {
3607   default:
3608     return false;
3609   case X86::COND_B:
3610   case X86::COND_BE:
3611   case X86::COND_E:
3612   case X86::COND_P:
3613   case X86::COND_A:
3614   case X86::COND_AE:
3615   case X86::COND_NE:
3616   case X86::COND_NP:
3617     return true;
3618   }
3619 }
3620
3621 /// isFPImmLegal - Returns true if the target can instruction select the
3622 /// specified FP immediate natively. If false, the legalizer will
3623 /// materialize the FP immediate as a load from a constant pool.
3624 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3625   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3626     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3627       return true;
3628   }
3629   return false;
3630 }
3631
3632 /// \brief Returns true if it is beneficial to convert a load of a constant
3633 /// to just the constant itself.
3634 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3635                                                           Type *Ty) const {
3636   assert(Ty->isIntegerTy());
3637
3638   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3639   if (BitSize == 0 || BitSize > 64)
3640     return false;
3641   return true;
3642 }
3643
3644 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3645 /// the specified range (L, H].
3646 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3647   return (Val < 0) || (Val >= Low && Val < Hi);
3648 }
3649
3650 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3651 /// specified value.
3652 static bool isUndefOrEqual(int Val, int CmpVal) {
3653   return (Val < 0 || Val == CmpVal);
3654 }
3655
3656 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3657 /// from position Pos and ending in Pos+Size, falls within the specified
3658 /// sequential range (L, L+Pos]. or is undef.
3659 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3660                                        unsigned Pos, unsigned Size, int Low) {
3661   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3662     if (!isUndefOrEqual(Mask[i], Low))
3663       return false;
3664   return true;
3665 }
3666
3667 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3668 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3669 /// the second operand.
3670 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3671   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3672     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3673   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3674     return (Mask[0] < 2 && Mask[1] < 2);
3675   return false;
3676 }
3677
3678 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3679 /// is suitable for input to PSHUFHW.
3680 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3681   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3682     return false;
3683
3684   // Lower quadword copied in order or undef.
3685   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3686     return false;
3687
3688   // Upper quadword shuffled.
3689   for (unsigned i = 4; i != 8; ++i)
3690     if (!isUndefOrInRange(Mask[i], 4, 8))
3691       return false;
3692
3693   if (VT == MVT::v16i16) {
3694     // Lower quadword copied in order or undef.
3695     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3696       return false;
3697
3698     // Upper quadword shuffled.
3699     for (unsigned i = 12; i != 16; ++i)
3700       if (!isUndefOrInRange(Mask[i], 12, 16))
3701         return false;
3702   }
3703
3704   return true;
3705 }
3706
3707 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3708 /// is suitable for input to PSHUFLW.
3709 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3710   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3711     return false;
3712
3713   // Upper quadword copied in order.
3714   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3715     return false;
3716
3717   // Lower quadword shuffled.
3718   for (unsigned i = 0; i != 4; ++i)
3719     if (!isUndefOrInRange(Mask[i], 0, 4))
3720       return false;
3721
3722   if (VT == MVT::v16i16) {
3723     // Upper quadword copied in order.
3724     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3725       return false;
3726
3727     // Lower quadword shuffled.
3728     for (unsigned i = 8; i != 12; ++i)
3729       if (!isUndefOrInRange(Mask[i], 8, 12))
3730         return false;
3731   }
3732
3733   return true;
3734 }
3735
3736 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3737 /// is suitable for input to PALIGNR.
3738 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3739                           const X86Subtarget *Subtarget) {
3740   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3741       (VT.is256BitVector() && !Subtarget->hasInt256()))
3742     return false;
3743
3744   unsigned NumElts = VT.getVectorNumElements();
3745   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3746   unsigned NumLaneElts = NumElts/NumLanes;
3747
3748   // Do not handle 64-bit element shuffles with palignr.
3749   if (NumLaneElts == 2)
3750     return false;
3751
3752   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3753     unsigned i;
3754     for (i = 0; i != NumLaneElts; ++i) {
3755       if (Mask[i+l] >= 0)
3756         break;
3757     }
3758
3759     // Lane is all undef, go to next lane
3760     if (i == NumLaneElts)
3761       continue;
3762
3763     int Start = Mask[i+l];
3764
3765     // Make sure its in this lane in one of the sources
3766     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3767         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3768       return false;
3769
3770     // If not lane 0, then we must match lane 0
3771     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3772       return false;
3773
3774     // Correct second source to be contiguous with first source
3775     if (Start >= (int)NumElts)
3776       Start -= NumElts - NumLaneElts;
3777
3778     // Make sure we're shifting in the right direction.
3779     if (Start <= (int)(i+l))
3780       return false;
3781
3782     Start -= i;
3783
3784     // Check the rest of the elements to see if they are consecutive.
3785     for (++i; i != NumLaneElts; ++i) {
3786       int Idx = Mask[i+l];
3787
3788       // Make sure its in this lane
3789       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3790           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3791         return false;
3792
3793       // If not lane 0, then we must match lane 0
3794       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3795         return false;
3796
3797       if (Idx >= (int)NumElts)
3798         Idx -= NumElts - NumLaneElts;
3799
3800       if (!isUndefOrEqual(Idx, Start+i))
3801         return false;
3802
3803     }
3804   }
3805
3806   return true;
3807 }
3808
3809 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3810 /// the two vector operands have swapped position.
3811 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3812                                      unsigned NumElems) {
3813   for (unsigned i = 0; i != NumElems; ++i) {
3814     int idx = Mask[i];
3815     if (idx < 0)
3816       continue;
3817     else if (idx < (int)NumElems)
3818       Mask[i] = idx + NumElems;
3819     else
3820       Mask[i] = idx - NumElems;
3821   }
3822 }
3823
3824 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3825 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3826 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3827 /// reverse of what x86 shuffles want.
3828 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3829
3830   unsigned NumElems = VT.getVectorNumElements();
3831   unsigned NumLanes = VT.getSizeInBits()/128;
3832   unsigned NumLaneElems = NumElems/NumLanes;
3833
3834   if (NumLaneElems != 2 && NumLaneElems != 4)
3835     return false;
3836
3837   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3838   bool symetricMaskRequired =
3839     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3840
3841   // VSHUFPSY divides the resulting vector into 4 chunks.
3842   // The sources are also splitted into 4 chunks, and each destination
3843   // chunk must come from a different source chunk.
3844   //
3845   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3846   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3847   //
3848   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3849   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3850   //
3851   // VSHUFPDY divides the resulting vector into 4 chunks.
3852   // The sources are also splitted into 4 chunks, and each destination
3853   // chunk must come from a different source chunk.
3854   //
3855   //  SRC1 =>      X3       X2       X1       X0
3856   //  SRC2 =>      Y3       Y2       Y1       Y0
3857   //
3858   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3859   //
3860   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3861   unsigned HalfLaneElems = NumLaneElems/2;
3862   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3863     for (unsigned i = 0; i != NumLaneElems; ++i) {
3864       int Idx = Mask[i+l];
3865       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3866       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3867         return false;
3868       // For VSHUFPSY, the mask of the second half must be the same as the
3869       // first but with the appropriate offsets. This works in the same way as
3870       // VPERMILPS works with masks.
3871       if (!symetricMaskRequired || Idx < 0)
3872         continue;
3873       if (MaskVal[i] < 0) {
3874         MaskVal[i] = Idx - l;
3875         continue;
3876       }
3877       if ((signed)(Idx - l) != MaskVal[i])
3878         return false;
3879     }
3880   }
3881
3882   return true;
3883 }
3884
3885 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3886 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3887 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3888   if (!VT.is128BitVector())
3889     return false;
3890
3891   unsigned NumElems = VT.getVectorNumElements();
3892
3893   if (NumElems != 4)
3894     return false;
3895
3896   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3897   return isUndefOrEqual(Mask[0], 6) &&
3898          isUndefOrEqual(Mask[1], 7) &&
3899          isUndefOrEqual(Mask[2], 2) &&
3900          isUndefOrEqual(Mask[3], 3);
3901 }
3902
3903 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3904 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3905 /// <2, 3, 2, 3>
3906 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3907   if (!VT.is128BitVector())
3908     return false;
3909
3910   unsigned NumElems = VT.getVectorNumElements();
3911
3912   if (NumElems != 4)
3913     return false;
3914
3915   return isUndefOrEqual(Mask[0], 2) &&
3916          isUndefOrEqual(Mask[1], 3) &&
3917          isUndefOrEqual(Mask[2], 2) &&
3918          isUndefOrEqual(Mask[3], 3);
3919 }
3920
3921 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3922 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3923 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3924   if (!VT.is128BitVector())
3925     return false;
3926
3927   unsigned NumElems = VT.getVectorNumElements();
3928
3929   if (NumElems != 2 && NumElems != 4)
3930     return false;
3931
3932   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3933     if (!isUndefOrEqual(Mask[i], i + NumElems))
3934       return false;
3935
3936   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3937     if (!isUndefOrEqual(Mask[i], i))
3938       return false;
3939
3940   return true;
3941 }
3942
3943 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3944 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3945 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3946   if (!VT.is128BitVector())
3947     return false;
3948
3949   unsigned NumElems = VT.getVectorNumElements();
3950
3951   if (NumElems != 2 && NumElems != 4)
3952     return false;
3953
3954   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3955     if (!isUndefOrEqual(Mask[i], i))
3956       return false;
3957
3958   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3959     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3960       return false;
3961
3962   return true;
3963 }
3964
3965 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3966 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3967 /// i. e: If all but one element come from the same vector.
3968 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3969   // TODO: Deal with AVX's VINSERTPS
3970   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3971     return false;
3972
3973   unsigned CorrectPosV1 = 0;
3974   unsigned CorrectPosV2 = 0;
3975   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3976     if (Mask[i] == -1) {
3977       ++CorrectPosV1;
3978       ++CorrectPosV2;
3979       continue;
3980     }
3981
3982     if (Mask[i] == i)
3983       ++CorrectPosV1;
3984     else if (Mask[i] == i + 4)
3985       ++CorrectPosV2;
3986   }
3987
3988   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3989     // We have 3 elements (undefs count as elements from any vector) from one
3990     // vector, and one from another.
3991     return true;
3992
3993   return false;
3994 }
3995
3996 //
3997 // Some special combinations that can be optimized.
3998 //
3999 static
4000 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4001                                SelectionDAG &DAG) {
4002   MVT VT = SVOp->getSimpleValueType(0);
4003   SDLoc dl(SVOp);
4004
4005   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4006     return SDValue();
4007
4008   ArrayRef<int> Mask = SVOp->getMask();
4009
4010   // These are the special masks that may be optimized.
4011   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4012   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4013   bool MatchEvenMask = true;
4014   bool MatchOddMask  = true;
4015   for (int i=0; i<8; ++i) {
4016     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4017       MatchEvenMask = false;
4018     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4019       MatchOddMask = false;
4020   }
4021
4022   if (!MatchEvenMask && !MatchOddMask)
4023     return SDValue();
4024
4025   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4026
4027   SDValue Op0 = SVOp->getOperand(0);
4028   SDValue Op1 = SVOp->getOperand(1);
4029
4030   if (MatchEvenMask) {
4031     // Shift the second operand right to 32 bits.
4032     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4033     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4034   } else {
4035     // Shift the first operand left to 32 bits.
4036     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4037     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4038   }
4039   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4040   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4041 }
4042
4043 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4044 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4045 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4046                          bool HasInt256, bool V2IsSplat = false) {
4047
4048   assert(VT.getSizeInBits() >= 128 &&
4049          "Unsupported vector type for unpckl");
4050
4051   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4052   unsigned NumLanes;
4053   unsigned NumOf256BitLanes;
4054   unsigned NumElts = VT.getVectorNumElements();
4055   if (VT.is256BitVector()) {
4056     if (NumElts != 4 && NumElts != 8 &&
4057         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4058     return false;
4059     NumLanes = 2;
4060     NumOf256BitLanes = 1;
4061   } else if (VT.is512BitVector()) {
4062     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4063            "Unsupported vector type for unpckh");
4064     NumLanes = 2;
4065     NumOf256BitLanes = 2;
4066   } else {
4067     NumLanes = 1;
4068     NumOf256BitLanes = 1;
4069   }
4070
4071   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4072   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4073
4074   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4075     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4076       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4077         int BitI  = Mask[l256*NumEltsInStride+l+i];
4078         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4079         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4080           return false;
4081         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4082           return false;
4083         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4084           return false;
4085       }
4086     }
4087   }
4088   return true;
4089 }
4090
4091 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4092 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4093 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4094                          bool HasInt256, bool V2IsSplat = false) {
4095   assert(VT.getSizeInBits() >= 128 &&
4096          "Unsupported vector type for unpckh");
4097
4098   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4099   unsigned NumLanes;
4100   unsigned NumOf256BitLanes;
4101   unsigned NumElts = VT.getVectorNumElements();
4102   if (VT.is256BitVector()) {
4103     if (NumElts != 4 && NumElts != 8 &&
4104         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4105     return false;
4106     NumLanes = 2;
4107     NumOf256BitLanes = 1;
4108   } else if (VT.is512BitVector()) {
4109     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4110            "Unsupported vector type for unpckh");
4111     NumLanes = 2;
4112     NumOf256BitLanes = 2;
4113   } else {
4114     NumLanes = 1;
4115     NumOf256BitLanes = 1;
4116   }
4117
4118   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4119   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4120
4121   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4122     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4123       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4124         int BitI  = Mask[l256*NumEltsInStride+l+i];
4125         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4126         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4127           return false;
4128         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4129           return false;
4130         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4131           return false;
4132       }
4133     }
4134   }
4135   return true;
4136 }
4137
4138 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4139 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4140 /// <0, 0, 1, 1>
4141 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4142   unsigned NumElts = VT.getVectorNumElements();
4143   bool Is256BitVec = VT.is256BitVector();
4144
4145   if (VT.is512BitVector())
4146     return false;
4147   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4148          "Unsupported vector type for unpckh");
4149
4150   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4151       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4152     return false;
4153
4154   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4155   // FIXME: Need a better way to get rid of this, there's no latency difference
4156   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4157   // the former later. We should also remove the "_undef" special mask.
4158   if (NumElts == 4 && Is256BitVec)
4159     return false;
4160
4161   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4162   // independently on 128-bit lanes.
4163   unsigned NumLanes = VT.getSizeInBits()/128;
4164   unsigned NumLaneElts = NumElts/NumLanes;
4165
4166   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4167     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4168       int BitI  = Mask[l+i];
4169       int BitI1 = Mask[l+i+1];
4170
4171       if (!isUndefOrEqual(BitI, j))
4172         return false;
4173       if (!isUndefOrEqual(BitI1, j))
4174         return false;
4175     }
4176   }
4177
4178   return true;
4179 }
4180
4181 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4182 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4183 /// <2, 2, 3, 3>
4184 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4185   unsigned NumElts = VT.getVectorNumElements();
4186
4187   if (VT.is512BitVector())
4188     return false;
4189
4190   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4191          "Unsupported vector type for unpckh");
4192
4193   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4194       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4195     return false;
4196
4197   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4198   // independently on 128-bit lanes.
4199   unsigned NumLanes = VT.getSizeInBits()/128;
4200   unsigned NumLaneElts = NumElts/NumLanes;
4201
4202   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4203     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4204       int BitI  = Mask[l+i];
4205       int BitI1 = Mask[l+i+1];
4206       if (!isUndefOrEqual(BitI, j))
4207         return false;
4208       if (!isUndefOrEqual(BitI1, j))
4209         return false;
4210     }
4211   }
4212   return true;
4213 }
4214
4215 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4216 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4217 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4218   if (!VT.is512BitVector())
4219     return false;
4220
4221   unsigned NumElts = VT.getVectorNumElements();
4222   unsigned HalfSize = NumElts/2;
4223   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4224     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4225       *Imm = 1;
4226       return true;
4227     }
4228   }
4229   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4230     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4231       *Imm = 0;
4232       return true;
4233     }
4234   }
4235   return false;
4236 }
4237
4238 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4239 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4240 /// MOVSD, and MOVD, i.e. setting the lowest element.
4241 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4242   if (VT.getVectorElementType().getSizeInBits() < 32)
4243     return false;
4244   if (!VT.is128BitVector())
4245     return false;
4246
4247   unsigned NumElts = VT.getVectorNumElements();
4248
4249   if (!isUndefOrEqual(Mask[0], NumElts))
4250     return false;
4251
4252   for (unsigned i = 1; i != NumElts; ++i)
4253     if (!isUndefOrEqual(Mask[i], i))
4254       return false;
4255
4256   return true;
4257 }
4258
4259 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4260 /// as permutations between 128-bit chunks or halves. As an example: this
4261 /// shuffle bellow:
4262 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4263 /// The first half comes from the second half of V1 and the second half from the
4264 /// the second half of V2.
4265 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4266   if (!HasFp256 || !VT.is256BitVector())
4267     return false;
4268
4269   // The shuffle result is divided into half A and half B. In total the two
4270   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4271   // B must come from C, D, E or F.
4272   unsigned HalfSize = VT.getVectorNumElements()/2;
4273   bool MatchA = false, MatchB = false;
4274
4275   // Check if A comes from one of C, D, E, F.
4276   for (unsigned Half = 0; Half != 4; ++Half) {
4277     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4278       MatchA = true;
4279       break;
4280     }
4281   }
4282
4283   // Check if B comes from one of C, D, E, F.
4284   for (unsigned Half = 0; Half != 4; ++Half) {
4285     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4286       MatchB = true;
4287       break;
4288     }
4289   }
4290
4291   return MatchA && MatchB;
4292 }
4293
4294 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4295 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4296 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4297   MVT VT = SVOp->getSimpleValueType(0);
4298
4299   unsigned HalfSize = VT.getVectorNumElements()/2;
4300
4301   unsigned FstHalf = 0, SndHalf = 0;
4302   for (unsigned i = 0; i < HalfSize; ++i) {
4303     if (SVOp->getMaskElt(i) > 0) {
4304       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4305       break;
4306     }
4307   }
4308   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4309     if (SVOp->getMaskElt(i) > 0) {
4310       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4311       break;
4312     }
4313   }
4314
4315   return (FstHalf | (SndHalf << 4));
4316 }
4317
4318 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4319 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4320   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4321   if (EltSize < 32)
4322     return false;
4323
4324   unsigned NumElts = VT.getVectorNumElements();
4325   Imm8 = 0;
4326   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4327     for (unsigned i = 0; i != NumElts; ++i) {
4328       if (Mask[i] < 0)
4329         continue;
4330       Imm8 |= Mask[i] << (i*2);
4331     }
4332     return true;
4333   }
4334
4335   unsigned LaneSize = 4;
4336   SmallVector<int, 4> MaskVal(LaneSize, -1);
4337
4338   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4339     for (unsigned i = 0; i != LaneSize; ++i) {
4340       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4341         return false;
4342       if (Mask[i+l] < 0)
4343         continue;
4344       if (MaskVal[i] < 0) {
4345         MaskVal[i] = Mask[i+l] - l;
4346         Imm8 |= MaskVal[i] << (i*2);
4347         continue;
4348       }
4349       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4350         return false;
4351     }
4352   }
4353   return true;
4354 }
4355
4356 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4357 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4358 /// Note that VPERMIL mask matching is different depending whether theunderlying
4359 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4360 /// to the same elements of the low, but to the higher half of the source.
4361 /// In VPERMILPD the two lanes could be shuffled independently of each other
4362 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4363 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4364   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4365   if (VT.getSizeInBits() < 256 || EltSize < 32)
4366     return false;
4367   bool symetricMaskRequired = (EltSize == 32);
4368   unsigned NumElts = VT.getVectorNumElements();
4369
4370   unsigned NumLanes = VT.getSizeInBits()/128;
4371   unsigned LaneSize = NumElts/NumLanes;
4372   // 2 or 4 elements in one lane
4373
4374   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4375   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4376     for (unsigned i = 0; i != LaneSize; ++i) {
4377       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4378         return false;
4379       if (symetricMaskRequired) {
4380         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4381           ExpectedMaskVal[i] = Mask[i+l] - l;
4382           continue;
4383         }
4384         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4385           return false;
4386       }
4387     }
4388   }
4389   return true;
4390 }
4391
4392 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4393 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4394 /// element of vector 2 and the other elements to come from vector 1 in order.
4395 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4396                                bool V2IsSplat = false, bool V2IsUndef = false) {
4397   if (!VT.is128BitVector())
4398     return false;
4399
4400   unsigned NumOps = VT.getVectorNumElements();
4401   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4402     return false;
4403
4404   if (!isUndefOrEqual(Mask[0], 0))
4405     return false;
4406
4407   for (unsigned i = 1; i != NumOps; ++i)
4408     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4409           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4410           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4411       return false;
4412
4413   return true;
4414 }
4415
4416 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4417 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4418 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4419 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4420                            const X86Subtarget *Subtarget) {
4421   if (!Subtarget->hasSSE3())
4422     return false;
4423
4424   unsigned NumElems = VT.getVectorNumElements();
4425
4426   if ((VT.is128BitVector() && NumElems != 4) ||
4427       (VT.is256BitVector() && NumElems != 8) ||
4428       (VT.is512BitVector() && NumElems != 16))
4429     return false;
4430
4431   // "i+1" is the value the indexed mask element must have
4432   for (unsigned i = 0; i != NumElems; i += 2)
4433     if (!isUndefOrEqual(Mask[i], i+1) ||
4434         !isUndefOrEqual(Mask[i+1], i+1))
4435       return false;
4436
4437   return true;
4438 }
4439
4440 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4441 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4442 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4443 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4444                            const X86Subtarget *Subtarget) {
4445   if (!Subtarget->hasSSE3())
4446     return false;
4447
4448   unsigned NumElems = VT.getVectorNumElements();
4449
4450   if ((VT.is128BitVector() && NumElems != 4) ||
4451       (VT.is256BitVector() && NumElems != 8) ||
4452       (VT.is512BitVector() && NumElems != 16))
4453     return false;
4454
4455   // "i" is the value the indexed mask element must have
4456   for (unsigned i = 0; i != NumElems; i += 2)
4457     if (!isUndefOrEqual(Mask[i], i) ||
4458         !isUndefOrEqual(Mask[i+1], i))
4459       return false;
4460
4461   return true;
4462 }
4463
4464 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4465 /// specifies a shuffle of elements that is suitable for input to 256-bit
4466 /// version of MOVDDUP.
4467 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4468   if (!HasFp256 || !VT.is256BitVector())
4469     return false;
4470
4471   unsigned NumElts = VT.getVectorNumElements();
4472   if (NumElts != 4)
4473     return false;
4474
4475   for (unsigned i = 0; i != NumElts/2; ++i)
4476     if (!isUndefOrEqual(Mask[i], 0))
4477       return false;
4478   for (unsigned i = NumElts/2; i != NumElts; ++i)
4479     if (!isUndefOrEqual(Mask[i], NumElts/2))
4480       return false;
4481   return true;
4482 }
4483
4484 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4485 /// specifies a shuffle of elements that is suitable for input to 128-bit
4486 /// version of MOVDDUP.
4487 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4488   if (!VT.is128BitVector())
4489     return false;
4490
4491   unsigned e = VT.getVectorNumElements() / 2;
4492   for (unsigned i = 0; i != e; ++i)
4493     if (!isUndefOrEqual(Mask[i], i))
4494       return false;
4495   for (unsigned i = 0; i != e; ++i)
4496     if (!isUndefOrEqual(Mask[e+i], i))
4497       return false;
4498   return true;
4499 }
4500
4501 /// isVEXTRACTIndex - Return true if the specified
4502 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4503 /// suitable for instruction that extract 128 or 256 bit vectors
4504 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4505   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4506   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4507     return false;
4508
4509   // The index should be aligned on a vecWidth-bit boundary.
4510   uint64_t Index =
4511     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4512
4513   MVT VT = N->getSimpleValueType(0);
4514   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4515   bool Result = (Index * ElSize) % vecWidth == 0;
4516
4517   return Result;
4518 }
4519
4520 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4521 /// operand specifies a subvector insert that is suitable for input to
4522 /// insertion of 128 or 256-bit subvectors
4523 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4524   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4525   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4526     return false;
4527   // The index should be aligned on a vecWidth-bit boundary.
4528   uint64_t Index =
4529     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4530
4531   MVT VT = N->getSimpleValueType(0);
4532   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4533   bool Result = (Index * ElSize) % vecWidth == 0;
4534
4535   return Result;
4536 }
4537
4538 bool X86::isVINSERT128Index(SDNode *N) {
4539   return isVINSERTIndex(N, 128);
4540 }
4541
4542 bool X86::isVINSERT256Index(SDNode *N) {
4543   return isVINSERTIndex(N, 256);
4544 }
4545
4546 bool X86::isVEXTRACT128Index(SDNode *N) {
4547   return isVEXTRACTIndex(N, 128);
4548 }
4549
4550 bool X86::isVEXTRACT256Index(SDNode *N) {
4551   return isVEXTRACTIndex(N, 256);
4552 }
4553
4554 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4555 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4556 /// Handles 128-bit and 256-bit.
4557 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4558   MVT VT = N->getSimpleValueType(0);
4559
4560   assert((VT.getSizeInBits() >= 128) &&
4561          "Unsupported vector type for PSHUF/SHUFP");
4562
4563   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4564   // independently on 128-bit lanes.
4565   unsigned NumElts = VT.getVectorNumElements();
4566   unsigned NumLanes = VT.getSizeInBits()/128;
4567   unsigned NumLaneElts = NumElts/NumLanes;
4568
4569   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4570          "Only supports 2, 4 or 8 elements per lane");
4571
4572   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4573   unsigned Mask = 0;
4574   for (unsigned i = 0; i != NumElts; ++i) {
4575     int Elt = N->getMaskElt(i);
4576     if (Elt < 0) continue;
4577     Elt &= NumLaneElts - 1;
4578     unsigned ShAmt = (i << Shift) % 8;
4579     Mask |= Elt << ShAmt;
4580   }
4581
4582   return Mask;
4583 }
4584
4585 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4586 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4587 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4588   MVT VT = N->getSimpleValueType(0);
4589
4590   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4591          "Unsupported vector type for PSHUFHW");
4592
4593   unsigned NumElts = VT.getVectorNumElements();
4594
4595   unsigned Mask = 0;
4596   for (unsigned l = 0; l != NumElts; l += 8) {
4597     // 8 nodes per lane, but we only care about the last 4.
4598     for (unsigned i = 0; i < 4; ++i) {
4599       int Elt = N->getMaskElt(l+i+4);
4600       if (Elt < 0) continue;
4601       Elt &= 0x3; // only 2-bits.
4602       Mask |= Elt << (i * 2);
4603     }
4604   }
4605
4606   return Mask;
4607 }
4608
4609 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4610 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4611 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4612   MVT VT = N->getSimpleValueType(0);
4613
4614   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4615          "Unsupported vector type for PSHUFHW");
4616
4617   unsigned NumElts = VT.getVectorNumElements();
4618
4619   unsigned Mask = 0;
4620   for (unsigned l = 0; l != NumElts; l += 8) {
4621     // 8 nodes per lane, but we only care about the first 4.
4622     for (unsigned i = 0; i < 4; ++i) {
4623       int Elt = N->getMaskElt(l+i);
4624       if (Elt < 0) continue;
4625       Elt &= 0x3; // only 2-bits
4626       Mask |= Elt << (i * 2);
4627     }
4628   }
4629
4630   return Mask;
4631 }
4632
4633 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4634 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4635 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4636   MVT VT = SVOp->getSimpleValueType(0);
4637   unsigned EltSize = VT.is512BitVector() ? 1 :
4638     VT.getVectorElementType().getSizeInBits() >> 3;
4639
4640   unsigned NumElts = VT.getVectorNumElements();
4641   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4642   unsigned NumLaneElts = NumElts/NumLanes;
4643
4644   int Val = 0;
4645   unsigned i;
4646   for (i = 0; i != NumElts; ++i) {
4647     Val = SVOp->getMaskElt(i);
4648     if (Val >= 0)
4649       break;
4650   }
4651   if (Val >= (int)NumElts)
4652     Val -= NumElts - NumLaneElts;
4653
4654   assert(Val - i > 0 && "PALIGNR imm should be positive");
4655   return (Val - i) * EltSize;
4656 }
4657
4658 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4659   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4660   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4661     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4662
4663   uint64_t Index =
4664     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4665
4666   MVT VecVT = N->getOperand(0).getSimpleValueType();
4667   MVT ElVT = VecVT.getVectorElementType();
4668
4669   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4670   return Index / NumElemsPerChunk;
4671 }
4672
4673 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4674   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4675   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4676     llvm_unreachable("Illegal insert subvector for VINSERT");
4677
4678   uint64_t Index =
4679     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4680
4681   MVT VecVT = N->getSimpleValueType(0);
4682   MVT ElVT = VecVT.getVectorElementType();
4683
4684   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4685   return Index / NumElemsPerChunk;
4686 }
4687
4688 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4689 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4690 /// and VINSERTI128 instructions.
4691 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4692   return getExtractVEXTRACTImmediate(N, 128);
4693 }
4694
4695 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4696 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4697 /// and VINSERTI64x4 instructions.
4698 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4699   return getExtractVEXTRACTImmediate(N, 256);
4700 }
4701
4702 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4703 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4704 /// and VINSERTI128 instructions.
4705 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4706   return getInsertVINSERTImmediate(N, 128);
4707 }
4708
4709 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4710 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4711 /// and VINSERTI64x4 instructions.
4712 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4713   return getInsertVINSERTImmediate(N, 256);
4714 }
4715
4716 /// isZero - Returns true if Elt is a constant integer zero
4717 static bool isZero(SDValue V) {
4718   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4719   return C && C->isNullValue();
4720 }
4721
4722 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4723 /// constant +0.0.
4724 bool X86::isZeroNode(SDValue Elt) {
4725   if (isZero(Elt))
4726     return true;
4727   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4728     return CFP->getValueAPF().isPosZero();
4729   return false;
4730 }
4731
4732 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4733 /// their permute mask.
4734 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4735                                     SelectionDAG &DAG) {
4736   MVT VT = SVOp->getSimpleValueType(0);
4737   unsigned NumElems = VT.getVectorNumElements();
4738   SmallVector<int, 8> MaskVec;
4739
4740   for (unsigned i = 0; i != NumElems; ++i) {
4741     int Idx = SVOp->getMaskElt(i);
4742     if (Idx >= 0) {
4743       if (Idx < (int)NumElems)
4744         Idx += NumElems;
4745       else
4746         Idx -= NumElems;
4747     }
4748     MaskVec.push_back(Idx);
4749   }
4750   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4751                               SVOp->getOperand(0), &MaskVec[0]);
4752 }
4753
4754 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4755 /// match movhlps. The lower half elements should come from upper half of
4756 /// V1 (and in order), and the upper half elements should come from the upper
4757 /// half of V2 (and in order).
4758 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4759   if (!VT.is128BitVector())
4760     return false;
4761   if (VT.getVectorNumElements() != 4)
4762     return false;
4763   for (unsigned i = 0, e = 2; i != e; ++i)
4764     if (!isUndefOrEqual(Mask[i], i+2))
4765       return false;
4766   for (unsigned i = 2; i != 4; ++i)
4767     if (!isUndefOrEqual(Mask[i], i+4))
4768       return false;
4769   return true;
4770 }
4771
4772 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4773 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4774 /// required.
4775 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4776   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4777     return false;
4778   N = N->getOperand(0).getNode();
4779   if (!ISD::isNON_EXTLoad(N))
4780     return false;
4781   if (LD)
4782     *LD = cast<LoadSDNode>(N);
4783   return true;
4784 }
4785
4786 // Test whether the given value is a vector value which will be legalized
4787 // into a load.
4788 static bool WillBeConstantPoolLoad(SDNode *N) {
4789   if (N->getOpcode() != ISD::BUILD_VECTOR)
4790     return false;
4791
4792   // Check for any non-constant elements.
4793   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4794     switch (N->getOperand(i).getNode()->getOpcode()) {
4795     case ISD::UNDEF:
4796     case ISD::ConstantFP:
4797     case ISD::Constant:
4798       break;
4799     default:
4800       return false;
4801     }
4802
4803   // Vectors of all-zeros and all-ones are materialized with special
4804   // instructions rather than being loaded.
4805   return !ISD::isBuildVectorAllZeros(N) &&
4806          !ISD::isBuildVectorAllOnes(N);
4807 }
4808
4809 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4810 /// match movlp{s|d}. The lower half elements should come from lower half of
4811 /// V1 (and in order), and the upper half elements should come from the upper
4812 /// half of V2 (and in order). And since V1 will become the source of the
4813 /// MOVLP, it must be either a vector load or a scalar load to vector.
4814 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4815                                ArrayRef<int> Mask, MVT VT) {
4816   if (!VT.is128BitVector())
4817     return false;
4818
4819   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4820     return false;
4821   // Is V2 is a vector load, don't do this transformation. We will try to use
4822   // load folding shufps op.
4823   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4824     return false;
4825
4826   unsigned NumElems = VT.getVectorNumElements();
4827
4828   if (NumElems != 2 && NumElems != 4)
4829     return false;
4830   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4831     if (!isUndefOrEqual(Mask[i], i))
4832       return false;
4833   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4834     if (!isUndefOrEqual(Mask[i], i+NumElems))
4835       return false;
4836   return true;
4837 }
4838
4839 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4840 /// all the same.
4841 static bool isSplatVector(SDNode *N) {
4842   if (N->getOpcode() != ISD::BUILD_VECTOR)
4843     return false;
4844
4845   SDValue SplatValue = N->getOperand(0);
4846   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4847     if (N->getOperand(i) != SplatValue)
4848       return false;
4849   return true;
4850 }
4851
4852 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4853 /// to an zero vector.
4854 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4855 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4856   SDValue V1 = N->getOperand(0);
4857   SDValue V2 = N->getOperand(1);
4858   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4859   for (unsigned i = 0; i != NumElems; ++i) {
4860     int Idx = N->getMaskElt(i);
4861     if (Idx >= (int)NumElems) {
4862       unsigned Opc = V2.getOpcode();
4863       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4864         continue;
4865       if (Opc != ISD::BUILD_VECTOR ||
4866           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4867         return false;
4868     } else if (Idx >= 0) {
4869       unsigned Opc = V1.getOpcode();
4870       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4871         continue;
4872       if (Opc != ISD::BUILD_VECTOR ||
4873           !X86::isZeroNode(V1.getOperand(Idx)))
4874         return false;
4875     }
4876   }
4877   return true;
4878 }
4879
4880 /// getZeroVector - Returns a vector of specified type with all zero elements.
4881 ///
4882 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4883                              SelectionDAG &DAG, SDLoc dl) {
4884   assert(VT.isVector() && "Expected a vector type");
4885
4886   // Always build SSE zero vectors as <4 x i32> bitcasted
4887   // to their dest type. This ensures they get CSE'd.
4888   SDValue Vec;
4889   if (VT.is128BitVector()) {  // SSE
4890     if (Subtarget->hasSSE2()) {  // SSE2
4891       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4892       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4893     } else { // SSE1
4894       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4895       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4896     }
4897   } else if (VT.is256BitVector()) { // AVX
4898     if (Subtarget->hasInt256()) { // AVX2
4899       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4900       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4901       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4902     } else {
4903       // 256-bit logic and arithmetic instructions in AVX are all
4904       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4905       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4906       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4907       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4908     }
4909   } else if (VT.is512BitVector()) { // AVX-512
4910       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4911       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4912                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4913       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4914   } else if (VT.getScalarType() == MVT::i1) {
4915     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4916     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4917     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4918     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4919   } else
4920     llvm_unreachable("Unexpected vector type");
4921
4922   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4923 }
4924
4925 /// getOnesVector - Returns a vector of specified type with all bits set.
4926 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4927 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4928 /// Then bitcast to their original type, ensuring they get CSE'd.
4929 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4930                              SDLoc dl) {
4931   assert(VT.isVector() && "Expected a vector type");
4932
4933   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4934   SDValue Vec;
4935   if (VT.is256BitVector()) {
4936     if (HasInt256) { // AVX2
4937       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4938       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4939     } else { // AVX
4940       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4941       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4942     }
4943   } else if (VT.is128BitVector()) {
4944     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4945   } else
4946     llvm_unreachable("Unexpected vector type");
4947
4948   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4949 }
4950
4951 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4952 /// that point to V2 points to its first element.
4953 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4954   for (unsigned i = 0; i != NumElems; ++i) {
4955     if (Mask[i] > (int)NumElems) {
4956       Mask[i] = NumElems;
4957     }
4958   }
4959 }
4960
4961 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4962 /// operation of specified width.
4963 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4964                        SDValue V2) {
4965   unsigned NumElems = VT.getVectorNumElements();
4966   SmallVector<int, 8> Mask;
4967   Mask.push_back(NumElems);
4968   for (unsigned i = 1; i != NumElems; ++i)
4969     Mask.push_back(i);
4970   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4971 }
4972
4973 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4974 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4975                           SDValue V2) {
4976   unsigned NumElems = VT.getVectorNumElements();
4977   SmallVector<int, 8> Mask;
4978   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4979     Mask.push_back(i);
4980     Mask.push_back(i + NumElems);
4981   }
4982   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4983 }
4984
4985 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4986 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4987                           SDValue V2) {
4988   unsigned NumElems = VT.getVectorNumElements();
4989   SmallVector<int, 8> Mask;
4990   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4991     Mask.push_back(i + Half);
4992     Mask.push_back(i + NumElems + Half);
4993   }
4994   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4995 }
4996
4997 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4998 // a generic shuffle instruction because the target has no such instructions.
4999 // Generate shuffles which repeat i16 and i8 several times until they can be
5000 // represented by v4f32 and then be manipulated by target suported shuffles.
5001 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5002   MVT VT = V.getSimpleValueType();
5003   int NumElems = VT.getVectorNumElements();
5004   SDLoc dl(V);
5005
5006   while (NumElems > 4) {
5007     if (EltNo < NumElems/2) {
5008       V = getUnpackl(DAG, dl, VT, V, V);
5009     } else {
5010       V = getUnpackh(DAG, dl, VT, V, V);
5011       EltNo -= NumElems/2;
5012     }
5013     NumElems >>= 1;
5014   }
5015   return V;
5016 }
5017
5018 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5019 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5020   MVT VT = V.getSimpleValueType();
5021   SDLoc dl(V);
5022
5023   if (VT.is128BitVector()) {
5024     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5025     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5026     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5027                              &SplatMask[0]);
5028   } else if (VT.is256BitVector()) {
5029     // To use VPERMILPS to splat scalars, the second half of indicies must
5030     // refer to the higher part, which is a duplication of the lower one,
5031     // because VPERMILPS can only handle in-lane permutations.
5032     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5033                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5034
5035     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5036     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5037                              &SplatMask[0]);
5038   } else
5039     llvm_unreachable("Vector size not supported");
5040
5041   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5042 }
5043
5044 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5045 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5046   MVT SrcVT = SV->getSimpleValueType(0);
5047   SDValue V1 = SV->getOperand(0);
5048   SDLoc dl(SV);
5049
5050   int EltNo = SV->getSplatIndex();
5051   int NumElems = SrcVT.getVectorNumElements();
5052   bool Is256BitVec = SrcVT.is256BitVector();
5053
5054   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5055          "Unknown how to promote splat for type");
5056
5057   // Extract the 128-bit part containing the splat element and update
5058   // the splat element index when it refers to the higher register.
5059   if (Is256BitVec) {
5060     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5061     if (EltNo >= NumElems/2)
5062       EltNo -= NumElems/2;
5063   }
5064
5065   // All i16 and i8 vector types can't be used directly by a generic shuffle
5066   // instruction because the target has no such instruction. Generate shuffles
5067   // which repeat i16 and i8 several times until they fit in i32, and then can
5068   // be manipulated by target suported shuffles.
5069   MVT EltVT = SrcVT.getVectorElementType();
5070   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5071     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5072
5073   // Recreate the 256-bit vector and place the same 128-bit vector
5074   // into the low and high part. This is necessary because we want
5075   // to use VPERM* to shuffle the vectors
5076   if (Is256BitVec) {
5077     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5078   }
5079
5080   return getLegalSplat(DAG, V1, EltNo);
5081 }
5082
5083 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5084 /// vector of zero or undef vector.  This produces a shuffle where the low
5085 /// element of V2 is swizzled into the zero/undef vector, landing at element
5086 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5087 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5088                                            bool IsZero,
5089                                            const X86Subtarget *Subtarget,
5090                                            SelectionDAG &DAG) {
5091   MVT VT = V2.getSimpleValueType();
5092   SDValue V1 = IsZero
5093     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5094   unsigned NumElems = VT.getVectorNumElements();
5095   SmallVector<int, 16> MaskVec;
5096   for (unsigned i = 0; i != NumElems; ++i)
5097     // If this is the insertion idx, put the low elt of V2 here.
5098     MaskVec.push_back(i == Idx ? NumElems : i);
5099   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5100 }
5101
5102 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5103 /// target specific opcode. Returns true if the Mask could be calculated.
5104 /// Sets IsUnary to true if only uses one source.
5105 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5106                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5107   unsigned NumElems = VT.getVectorNumElements();
5108   SDValue ImmN;
5109
5110   IsUnary = false;
5111   switch(N->getOpcode()) {
5112   case X86ISD::SHUFP:
5113     ImmN = N->getOperand(N->getNumOperands()-1);
5114     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5115     break;
5116   case X86ISD::UNPCKH:
5117     DecodeUNPCKHMask(VT, Mask);
5118     break;
5119   case X86ISD::UNPCKL:
5120     DecodeUNPCKLMask(VT, Mask);
5121     break;
5122   case X86ISD::MOVHLPS:
5123     DecodeMOVHLPSMask(NumElems, Mask);
5124     break;
5125   case X86ISD::MOVLHPS:
5126     DecodeMOVLHPSMask(NumElems, Mask);
5127     break;
5128   case X86ISD::PALIGNR:
5129     ImmN = N->getOperand(N->getNumOperands()-1);
5130     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5131     break;
5132   case X86ISD::PSHUFD:
5133   case X86ISD::VPERMILP:
5134     ImmN = N->getOperand(N->getNumOperands()-1);
5135     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5136     IsUnary = true;
5137     break;
5138   case X86ISD::PSHUFHW:
5139     ImmN = N->getOperand(N->getNumOperands()-1);
5140     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5141     IsUnary = true;
5142     break;
5143   case X86ISD::PSHUFLW:
5144     ImmN = N->getOperand(N->getNumOperands()-1);
5145     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5146     IsUnary = true;
5147     break;
5148   case X86ISD::VPERMI:
5149     ImmN = N->getOperand(N->getNumOperands()-1);
5150     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5151     IsUnary = true;
5152     break;
5153   case X86ISD::MOVSS:
5154   case X86ISD::MOVSD: {
5155     // The index 0 always comes from the first element of the second source,
5156     // this is why MOVSS and MOVSD are used in the first place. The other
5157     // elements come from the other positions of the first source vector
5158     Mask.push_back(NumElems);
5159     for (unsigned i = 1; i != NumElems; ++i) {
5160       Mask.push_back(i);
5161     }
5162     break;
5163   }
5164   case X86ISD::VPERM2X128:
5165     ImmN = N->getOperand(N->getNumOperands()-1);
5166     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5167     if (Mask.empty()) return false;
5168     break;
5169   case X86ISD::MOVDDUP:
5170   case X86ISD::MOVLHPD:
5171   case X86ISD::MOVLPD:
5172   case X86ISD::MOVLPS:
5173   case X86ISD::MOVSHDUP:
5174   case X86ISD::MOVSLDUP:
5175     // Not yet implemented
5176     return false;
5177   default: llvm_unreachable("unknown target shuffle node");
5178   }
5179
5180   return true;
5181 }
5182
5183 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5184 /// element of the result of the vector shuffle.
5185 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5186                                    unsigned Depth) {
5187   if (Depth == 6)
5188     return SDValue();  // Limit search depth.
5189
5190   SDValue V = SDValue(N, 0);
5191   EVT VT = V.getValueType();
5192   unsigned Opcode = V.getOpcode();
5193
5194   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5195   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5196     int Elt = SV->getMaskElt(Index);
5197
5198     if (Elt < 0)
5199       return DAG.getUNDEF(VT.getVectorElementType());
5200
5201     unsigned NumElems = VT.getVectorNumElements();
5202     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5203                                          : SV->getOperand(1);
5204     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5205   }
5206
5207   // Recurse into target specific vector shuffles to find scalars.
5208   if (isTargetShuffle(Opcode)) {
5209     MVT ShufVT = V.getSimpleValueType();
5210     unsigned NumElems = ShufVT.getVectorNumElements();
5211     SmallVector<int, 16> ShuffleMask;
5212     bool IsUnary;
5213
5214     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5215       return SDValue();
5216
5217     int Elt = ShuffleMask[Index];
5218     if (Elt < 0)
5219       return DAG.getUNDEF(ShufVT.getVectorElementType());
5220
5221     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5222                                          : N->getOperand(1);
5223     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5224                                Depth+1);
5225   }
5226
5227   // Actual nodes that may contain scalar elements
5228   if (Opcode == ISD::BITCAST) {
5229     V = V.getOperand(0);
5230     EVT SrcVT = V.getValueType();
5231     unsigned NumElems = VT.getVectorNumElements();
5232
5233     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5234       return SDValue();
5235   }
5236
5237   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5238     return (Index == 0) ? V.getOperand(0)
5239                         : DAG.getUNDEF(VT.getVectorElementType());
5240
5241   if (V.getOpcode() == ISD::BUILD_VECTOR)
5242     return V.getOperand(Index);
5243
5244   return SDValue();
5245 }
5246
5247 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5248 /// shuffle operation which come from a consecutively from a zero. The
5249 /// search can start in two different directions, from left or right.
5250 /// We count undefs as zeros until PreferredNum is reached.
5251 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5252                                          unsigned NumElems, bool ZerosFromLeft,
5253                                          SelectionDAG &DAG,
5254                                          unsigned PreferredNum = -1U) {
5255   unsigned NumZeros = 0;
5256   for (unsigned i = 0; i != NumElems; ++i) {
5257     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5258     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5259     if (!Elt.getNode())
5260       break;
5261
5262     if (X86::isZeroNode(Elt))
5263       ++NumZeros;
5264     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5265       NumZeros = std::min(NumZeros + 1, PreferredNum);
5266     else
5267       break;
5268   }
5269
5270   return NumZeros;
5271 }
5272
5273 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5274 /// correspond consecutively to elements from one of the vector operands,
5275 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5276 static
5277 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5278                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5279                               unsigned NumElems, unsigned &OpNum) {
5280   bool SeenV1 = false;
5281   bool SeenV2 = false;
5282
5283   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5284     int Idx = SVOp->getMaskElt(i);
5285     // Ignore undef indicies
5286     if (Idx < 0)
5287       continue;
5288
5289     if (Idx < (int)NumElems)
5290       SeenV1 = true;
5291     else
5292       SeenV2 = true;
5293
5294     // Only accept consecutive elements from the same vector
5295     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5296       return false;
5297   }
5298
5299   OpNum = SeenV1 ? 0 : 1;
5300   return true;
5301 }
5302
5303 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5304 /// logical left shift of a vector.
5305 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5306                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5307   unsigned NumElems =
5308     SVOp->getSimpleValueType(0).getVectorNumElements();
5309   unsigned NumZeros = getNumOfConsecutiveZeros(
5310       SVOp, NumElems, false /* check zeros from right */, DAG,
5311       SVOp->getMaskElt(0));
5312   unsigned OpSrc;
5313
5314   if (!NumZeros)
5315     return false;
5316
5317   // Considering the elements in the mask that are not consecutive zeros,
5318   // check if they consecutively come from only one of the source vectors.
5319   //
5320   //               V1 = {X, A, B, C}     0
5321   //                         \  \  \    /
5322   //   vector_shuffle V1, V2 <1, 2, 3, X>
5323   //
5324   if (!isShuffleMaskConsecutive(SVOp,
5325             0,                   // Mask Start Index
5326             NumElems-NumZeros,   // Mask End Index(exclusive)
5327             NumZeros,            // Where to start looking in the src vector
5328             NumElems,            // Number of elements in vector
5329             OpSrc))              // Which source operand ?
5330     return false;
5331
5332   isLeft = false;
5333   ShAmt = NumZeros;
5334   ShVal = SVOp->getOperand(OpSrc);
5335   return true;
5336 }
5337
5338 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5339 /// logical left shift of a vector.
5340 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5341                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5342   unsigned NumElems =
5343     SVOp->getSimpleValueType(0).getVectorNumElements();
5344   unsigned NumZeros = getNumOfConsecutiveZeros(
5345       SVOp, NumElems, true /* check zeros from left */, DAG,
5346       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5347   unsigned OpSrc;
5348
5349   if (!NumZeros)
5350     return false;
5351
5352   // Considering the elements in the mask that are not consecutive zeros,
5353   // check if they consecutively come from only one of the source vectors.
5354   //
5355   //                           0    { A, B, X, X } = V2
5356   //                          / \    /  /
5357   //   vector_shuffle V1, V2 <X, X, 4, 5>
5358   //
5359   if (!isShuffleMaskConsecutive(SVOp,
5360             NumZeros,     // Mask Start Index
5361             NumElems,     // Mask End Index(exclusive)
5362             0,            // Where to start looking in the src vector
5363             NumElems,     // Number of elements in vector
5364             OpSrc))       // Which source operand ?
5365     return false;
5366
5367   isLeft = true;
5368   ShAmt = NumZeros;
5369   ShVal = SVOp->getOperand(OpSrc);
5370   return true;
5371 }
5372
5373 /// isVectorShift - Returns true if the shuffle can be implemented as a
5374 /// logical left or right shift of a vector.
5375 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5376                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5377   // Although the logic below support any bitwidth size, there are no
5378   // shift instructions which handle more than 128-bit vectors.
5379   if (!SVOp->getSimpleValueType(0).is128BitVector())
5380     return false;
5381
5382   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5383       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5384     return true;
5385
5386   return false;
5387 }
5388
5389 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5390 ///
5391 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5392                                        unsigned NumNonZero, unsigned NumZero,
5393                                        SelectionDAG &DAG,
5394                                        const X86Subtarget* Subtarget,
5395                                        const TargetLowering &TLI) {
5396   if (NumNonZero > 8)
5397     return SDValue();
5398
5399   SDLoc dl(Op);
5400   SDValue V;
5401   bool First = true;
5402   for (unsigned i = 0; i < 16; ++i) {
5403     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5404     if (ThisIsNonZero && First) {
5405       if (NumZero)
5406         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5407       else
5408         V = DAG.getUNDEF(MVT::v8i16);
5409       First = false;
5410     }
5411
5412     if ((i & 1) != 0) {
5413       SDValue ThisElt, LastElt;
5414       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5415       if (LastIsNonZero) {
5416         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5417                               MVT::i16, Op.getOperand(i-1));
5418       }
5419       if (ThisIsNonZero) {
5420         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5421         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5422                               ThisElt, DAG.getConstant(8, MVT::i8));
5423         if (LastIsNonZero)
5424           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5425       } else
5426         ThisElt = LastElt;
5427
5428       if (ThisElt.getNode())
5429         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5430                         DAG.getIntPtrConstant(i/2));
5431     }
5432   }
5433
5434   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5435 }
5436
5437 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5438 ///
5439 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5440                                      unsigned NumNonZero, unsigned NumZero,
5441                                      SelectionDAG &DAG,
5442                                      const X86Subtarget* Subtarget,
5443                                      const TargetLowering &TLI) {
5444   if (NumNonZero > 4)
5445     return SDValue();
5446
5447   SDLoc dl(Op);
5448   SDValue V;
5449   bool First = true;
5450   for (unsigned i = 0; i < 8; ++i) {
5451     bool isNonZero = (NonZeros & (1 << i)) != 0;
5452     if (isNonZero) {
5453       if (First) {
5454         if (NumZero)
5455           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5456         else
5457           V = DAG.getUNDEF(MVT::v8i16);
5458         First = false;
5459       }
5460       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5461                       MVT::v8i16, V, Op.getOperand(i),
5462                       DAG.getIntPtrConstant(i));
5463     }
5464   }
5465
5466   return V;
5467 }
5468
5469 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5470 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5471                                      unsigned NonZeros, unsigned NumNonZero,
5472                                      unsigned NumZero, SelectionDAG &DAG,
5473                                      const X86Subtarget *Subtarget,
5474                                      const TargetLowering &TLI) {
5475   // We know there's at least one non-zero element
5476   unsigned FirstNonZeroIdx = 0;
5477   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5478   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5479          X86::isZeroNode(FirstNonZero)) {
5480     ++FirstNonZeroIdx;
5481     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5482   }
5483
5484   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5485       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5486     return SDValue();
5487
5488   SDValue V = FirstNonZero.getOperand(0);
5489   MVT VVT = V.getSimpleValueType();
5490   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5491     return SDValue();
5492
5493   unsigned FirstNonZeroDst =
5494       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5495   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5496   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5497   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5498
5499   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5500     SDValue Elem = Op.getOperand(Idx);
5501     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5502       continue;
5503
5504     // TODO: What else can be here? Deal with it.
5505     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5506       return SDValue();
5507
5508     // TODO: Some optimizations are still possible here
5509     // ex: Getting one element from a vector, and the rest from another.
5510     if (Elem.getOperand(0) != V)
5511       return SDValue();
5512
5513     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5514     if (Dst == Idx)
5515       ++CorrectIdx;
5516     else if (IncorrectIdx == -1U) {
5517       IncorrectIdx = Idx;
5518       IncorrectDst = Dst;
5519     } else
5520       // There was already one element with an incorrect index.
5521       // We can't optimize this case to an insertps.
5522       return SDValue();
5523   }
5524
5525   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5526     SDLoc dl(Op);
5527     EVT VT = Op.getSimpleValueType();
5528     unsigned ElementMoveMask = 0;
5529     if (IncorrectIdx == -1U)
5530       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5531     else
5532       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5533
5534     SDValue InsertpsMask =
5535         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5536     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5537   }
5538
5539   return SDValue();
5540 }
5541
5542 /// getVShift - Return a vector logical shift node.
5543 ///
5544 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5545                          unsigned NumBits, SelectionDAG &DAG,
5546                          const TargetLowering &TLI, SDLoc dl) {
5547   assert(VT.is128BitVector() && "Unknown type for VShift");
5548   EVT ShVT = MVT::v2i64;
5549   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5550   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5551   return DAG.getNode(ISD::BITCAST, dl, VT,
5552                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5553                              DAG.getConstant(NumBits,
5554                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5555 }
5556
5557 static SDValue
5558 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5559
5560   // Check if the scalar load can be widened into a vector load. And if
5561   // the address is "base + cst" see if the cst can be "absorbed" into
5562   // the shuffle mask.
5563   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5564     SDValue Ptr = LD->getBasePtr();
5565     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5566       return SDValue();
5567     EVT PVT = LD->getValueType(0);
5568     if (PVT != MVT::i32 && PVT != MVT::f32)
5569       return SDValue();
5570
5571     int FI = -1;
5572     int64_t Offset = 0;
5573     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5574       FI = FINode->getIndex();
5575       Offset = 0;
5576     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5577                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5578       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5579       Offset = Ptr.getConstantOperandVal(1);
5580       Ptr = Ptr.getOperand(0);
5581     } else {
5582       return SDValue();
5583     }
5584
5585     // FIXME: 256-bit vector instructions don't require a strict alignment,
5586     // improve this code to support it better.
5587     unsigned RequiredAlign = VT.getSizeInBits()/8;
5588     SDValue Chain = LD->getChain();
5589     // Make sure the stack object alignment is at least 16 or 32.
5590     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5591     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5592       if (MFI->isFixedObjectIndex(FI)) {
5593         // Can't change the alignment. FIXME: It's possible to compute
5594         // the exact stack offset and reference FI + adjust offset instead.
5595         // If someone *really* cares about this. That's the way to implement it.
5596         return SDValue();
5597       } else {
5598         MFI->setObjectAlignment(FI, RequiredAlign);
5599       }
5600     }
5601
5602     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5603     // Ptr + (Offset & ~15).
5604     if (Offset < 0)
5605       return SDValue();
5606     if ((Offset % RequiredAlign) & 3)
5607       return SDValue();
5608     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5609     if (StartOffset)
5610       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5611                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5612
5613     int EltNo = (Offset - StartOffset) >> 2;
5614     unsigned NumElems = VT.getVectorNumElements();
5615
5616     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5617     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5618                              LD->getPointerInfo().getWithOffset(StartOffset),
5619                              false, false, false, 0);
5620
5621     SmallVector<int, 8> Mask;
5622     for (unsigned i = 0; i != NumElems; ++i)
5623       Mask.push_back(EltNo);
5624
5625     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5626   }
5627
5628   return SDValue();
5629 }
5630
5631 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5632 /// vector of type 'VT', see if the elements can be replaced by a single large
5633 /// load which has the same value as a build_vector whose operands are 'elts'.
5634 ///
5635 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5636 ///
5637 /// FIXME: we'd also like to handle the case where the last elements are zero
5638 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5639 /// There's even a handy isZeroNode for that purpose.
5640 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5641                                         SDLoc &DL, SelectionDAG &DAG,
5642                                         bool isAfterLegalize) {
5643   EVT EltVT = VT.getVectorElementType();
5644   unsigned NumElems = Elts.size();
5645
5646   LoadSDNode *LDBase = nullptr;
5647   unsigned LastLoadedElt = -1U;
5648
5649   // For each element in the initializer, see if we've found a load or an undef.
5650   // If we don't find an initial load element, or later load elements are
5651   // non-consecutive, bail out.
5652   for (unsigned i = 0; i < NumElems; ++i) {
5653     SDValue Elt = Elts[i];
5654
5655     if (!Elt.getNode() ||
5656         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5657       return SDValue();
5658     if (!LDBase) {
5659       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5660         return SDValue();
5661       LDBase = cast<LoadSDNode>(Elt.getNode());
5662       LastLoadedElt = i;
5663       continue;
5664     }
5665     if (Elt.getOpcode() == ISD::UNDEF)
5666       continue;
5667
5668     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5669     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5670       return SDValue();
5671     LastLoadedElt = i;
5672   }
5673
5674   // If we have found an entire vector of loads and undefs, then return a large
5675   // load of the entire vector width starting at the base pointer.  If we found
5676   // consecutive loads for the low half, generate a vzext_load node.
5677   if (LastLoadedElt == NumElems - 1) {
5678
5679     if (isAfterLegalize &&
5680         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5681       return SDValue();
5682
5683     SDValue NewLd = SDValue();
5684
5685     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5686       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5687                           LDBase->getPointerInfo(),
5688                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5689                           LDBase->isInvariant(), 0);
5690     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5691                         LDBase->getPointerInfo(),
5692                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5693                         LDBase->isInvariant(), LDBase->getAlignment());
5694
5695     if (LDBase->hasAnyUseOfValue(1)) {
5696       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5697                                      SDValue(LDBase, 1),
5698                                      SDValue(NewLd.getNode(), 1));
5699       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5700       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5701                              SDValue(NewLd.getNode(), 1));
5702     }
5703
5704     return NewLd;
5705   }
5706   if (NumElems == 4 && LastLoadedElt == 1 &&
5707       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5708     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5709     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5710     SDValue ResNode =
5711         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5712                                 LDBase->getPointerInfo(),
5713                                 LDBase->getAlignment(),
5714                                 false/*isVolatile*/, true/*ReadMem*/,
5715                                 false/*WriteMem*/);
5716
5717     // Make sure the newly-created LOAD is in the same position as LDBase in
5718     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5719     // update uses of LDBase's output chain to use the TokenFactor.
5720     if (LDBase->hasAnyUseOfValue(1)) {
5721       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5722                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5723       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5724       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5725                              SDValue(ResNode.getNode(), 1));
5726     }
5727
5728     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5729   }
5730   return SDValue();
5731 }
5732
5733 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5734 /// to generate a splat value for the following cases:
5735 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5736 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5737 /// a scalar load, or a constant.
5738 /// The VBROADCAST node is returned when a pattern is found,
5739 /// or SDValue() otherwise.
5740 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5741                                     SelectionDAG &DAG) {
5742   if (!Subtarget->hasFp256())
5743     return SDValue();
5744
5745   MVT VT = Op.getSimpleValueType();
5746   SDLoc dl(Op);
5747
5748   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5749          "Unsupported vector type for broadcast.");
5750
5751   SDValue Ld;
5752   bool ConstSplatVal;
5753
5754   switch (Op.getOpcode()) {
5755     default:
5756       // Unknown pattern found.
5757       return SDValue();
5758
5759     case ISD::BUILD_VECTOR: {
5760       // The BUILD_VECTOR node must be a splat.
5761       if (!isSplatVector(Op.getNode()))
5762         return SDValue();
5763
5764       Ld = Op.getOperand(0);
5765       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5766                      Ld.getOpcode() == ISD::ConstantFP);
5767
5768       // The suspected load node has several users. Make sure that all
5769       // of its users are from the BUILD_VECTOR node.
5770       // Constants may have multiple users.
5771       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5772         return SDValue();
5773       break;
5774     }
5775
5776     case ISD::VECTOR_SHUFFLE: {
5777       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5778
5779       // Shuffles must have a splat mask where the first element is
5780       // broadcasted.
5781       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5782         return SDValue();
5783
5784       SDValue Sc = Op.getOperand(0);
5785       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5786           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5787
5788         if (!Subtarget->hasInt256())
5789           return SDValue();
5790
5791         // Use the register form of the broadcast instruction available on AVX2.
5792         if (VT.getSizeInBits() >= 256)
5793           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5794         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5795       }
5796
5797       Ld = Sc.getOperand(0);
5798       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5799                        Ld.getOpcode() == ISD::ConstantFP);
5800
5801       // The scalar_to_vector node and the suspected
5802       // load node must have exactly one user.
5803       // Constants may have multiple users.
5804
5805       // AVX-512 has register version of the broadcast
5806       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5807         Ld.getValueType().getSizeInBits() >= 32;
5808       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5809           !hasRegVer))
5810         return SDValue();
5811       break;
5812     }
5813   }
5814
5815   bool IsGE256 = (VT.getSizeInBits() >= 256);
5816
5817   // Handle the broadcasting a single constant scalar from the constant pool
5818   // into a vector. On Sandybridge it is still better to load a constant vector
5819   // from the constant pool and not to broadcast it from a scalar.
5820   if (ConstSplatVal && Subtarget->hasInt256()) {
5821     EVT CVT = Ld.getValueType();
5822     assert(!CVT.isVector() && "Must not broadcast a vector type");
5823     unsigned ScalarSize = CVT.getSizeInBits();
5824
5825     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5826       const Constant *C = nullptr;
5827       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5828         C = CI->getConstantIntValue();
5829       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5830         C = CF->getConstantFPValue();
5831
5832       assert(C && "Invalid constant type");
5833
5834       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5835       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5836       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5837       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5838                        MachinePointerInfo::getConstantPool(),
5839                        false, false, false, Alignment);
5840
5841       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5842     }
5843   }
5844
5845   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5846   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5847
5848   // Handle AVX2 in-register broadcasts.
5849   if (!IsLoad && Subtarget->hasInt256() &&
5850       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5851     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5852
5853   // The scalar source must be a normal load.
5854   if (!IsLoad)
5855     return SDValue();
5856
5857   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5858     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5859
5860   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5861   // double since there is no vbroadcastsd xmm
5862   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5863     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5864       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5865   }
5866
5867   // Unsupported broadcast.
5868   return SDValue();
5869 }
5870
5871 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5872 /// underlying vector and index.
5873 ///
5874 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5875 /// index.
5876 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5877                                          SDValue ExtIdx) {
5878   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5879   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5880     return Idx;
5881
5882   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5883   // lowered this:
5884   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5885   // to:
5886   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5887   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5888   //                           undef)
5889   //                       Constant<0>)
5890   // In this case the vector is the extract_subvector expression and the index
5891   // is 2, as specified by the shuffle.
5892   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5893   SDValue ShuffleVec = SVOp->getOperand(0);
5894   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5895   assert(ShuffleVecVT.getVectorElementType() ==
5896          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5897
5898   int ShuffleIdx = SVOp->getMaskElt(Idx);
5899   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5900     ExtractedFromVec = ShuffleVec;
5901     return ShuffleIdx;
5902   }
5903   return Idx;
5904 }
5905
5906 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5907   MVT VT = Op.getSimpleValueType();
5908
5909   // Skip if insert_vec_elt is not supported.
5910   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5911   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5912     return SDValue();
5913
5914   SDLoc DL(Op);
5915   unsigned NumElems = Op.getNumOperands();
5916
5917   SDValue VecIn1;
5918   SDValue VecIn2;
5919   SmallVector<unsigned, 4> InsertIndices;
5920   SmallVector<int, 8> Mask(NumElems, -1);
5921
5922   for (unsigned i = 0; i != NumElems; ++i) {
5923     unsigned Opc = Op.getOperand(i).getOpcode();
5924
5925     if (Opc == ISD::UNDEF)
5926       continue;
5927
5928     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5929       // Quit if more than 1 elements need inserting.
5930       if (InsertIndices.size() > 1)
5931         return SDValue();
5932
5933       InsertIndices.push_back(i);
5934       continue;
5935     }
5936
5937     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5938     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5939     // Quit if non-constant index.
5940     if (!isa<ConstantSDNode>(ExtIdx))
5941       return SDValue();
5942     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5943
5944     // Quit if extracted from vector of different type.
5945     if (ExtractedFromVec.getValueType() != VT)
5946       return SDValue();
5947
5948     if (!VecIn1.getNode())
5949       VecIn1 = ExtractedFromVec;
5950     else if (VecIn1 != ExtractedFromVec) {
5951       if (!VecIn2.getNode())
5952         VecIn2 = ExtractedFromVec;
5953       else if (VecIn2 != ExtractedFromVec)
5954         // Quit if more than 2 vectors to shuffle
5955         return SDValue();
5956     }
5957
5958     if (ExtractedFromVec == VecIn1)
5959       Mask[i] = Idx;
5960     else if (ExtractedFromVec == VecIn2)
5961       Mask[i] = Idx + NumElems;
5962   }
5963
5964   if (!VecIn1.getNode())
5965     return SDValue();
5966
5967   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5968   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5969   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5970     unsigned Idx = InsertIndices[i];
5971     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5972                      DAG.getIntPtrConstant(Idx));
5973   }
5974
5975   return NV;
5976 }
5977
5978 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5979 SDValue
5980 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5981
5982   MVT VT = Op.getSimpleValueType();
5983   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5984          "Unexpected type in LowerBUILD_VECTORvXi1!");
5985
5986   SDLoc dl(Op);
5987   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5988     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5989     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5990     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5991   }
5992
5993   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5994     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5995     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5996     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5997   }
5998
5999   bool AllContants = true;
6000   uint64_t Immediate = 0;
6001   int NonConstIdx = -1;
6002   bool IsSplat = true;
6003   unsigned NumNonConsts = 0;
6004   unsigned NumConsts = 0;
6005   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6006     SDValue In = Op.getOperand(idx);
6007     if (In.getOpcode() == ISD::UNDEF)
6008       continue;
6009     if (!isa<ConstantSDNode>(In)) {
6010       AllContants = false;
6011       NonConstIdx = idx;
6012       NumNonConsts++;
6013     }
6014     else {
6015       NumConsts++;
6016       if (cast<ConstantSDNode>(In)->getZExtValue())
6017       Immediate |= (1ULL << idx);
6018     }
6019     if (In != Op.getOperand(0))
6020       IsSplat = false;
6021   }
6022
6023   if (AllContants) {
6024     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6025       DAG.getConstant(Immediate, MVT::i16));
6026     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6027                        DAG.getIntPtrConstant(0));
6028   }
6029
6030   if (NumNonConsts == 1 && NonConstIdx != 0) {
6031     SDValue DstVec;
6032     if (NumConsts) {
6033       SDValue VecAsImm = DAG.getConstant(Immediate,
6034                                          MVT::getIntegerVT(VT.getSizeInBits()));
6035       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6036     }
6037     else 
6038       DstVec = DAG.getUNDEF(VT);
6039     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6040                        Op.getOperand(NonConstIdx),
6041                        DAG.getIntPtrConstant(NonConstIdx));
6042   }
6043   if (!IsSplat && (NonConstIdx != 0))
6044     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6045   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6046   SDValue Select;
6047   if (IsSplat)
6048     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6049                           DAG.getConstant(-1, SelectVT),
6050                           DAG.getConstant(0, SelectVT));
6051   else
6052     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6053                          DAG.getConstant((Immediate | 1), SelectVT),
6054                          DAG.getConstant(Immediate, SelectVT));
6055   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6056 }
6057
6058 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6059                                           const X86Subtarget *Subtarget) {
6060   EVT VT = N->getValueType(0);
6061
6062   // Try to match a horizontal ADD or SUB.
6063   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) ||
6064       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget->hasAVX()) ||
6065       ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) ||
6066       ((VT == MVT::v8i32 || VT == MVT::v16i16) && Subtarget->hasAVX2())) {
6067     unsigned NumOperands = N->getNumOperands();
6068     unsigned Opcode = N->getOperand(0)->getOpcode();
6069     bool isCommutable = false;
6070     bool CanFold = false;
6071     switch (Opcode) {
6072     default : break;
6073     case ISD::ADD :
6074     case ISD::FADD :
6075       isCommutable = true;
6076       // FALL-THROUGH
6077     case ISD::SUB :
6078     case ISD::FSUB :
6079       CanFold = true;
6080     }
6081
6082     // Verify that operands have the same opcode; also, the opcode can only
6083     // be either of: ADD, FADD, SUB, FSUB.
6084     SDValue InVec0, InVec1;
6085     for (unsigned i = 0, e = NumOperands; i != e && CanFold; ++i) {
6086       SDValue Op = N->getOperand(i);
6087       CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6088
6089       if (!CanFold)
6090         break;
6091
6092       SDValue Op0 = Op.getOperand(0);
6093       SDValue Op1 = Op.getOperand(1);
6094
6095       // Try to match the following pattern:
6096       // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6097       CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6098           Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6099           Op0.getOperand(0) == Op1.getOperand(0) &&
6100           isa<ConstantSDNode>(Op0.getOperand(1)) &&
6101           isa<ConstantSDNode>(Op1.getOperand(1)));
6102       if (!CanFold)
6103         break;
6104
6105       unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6106       unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6107       unsigned ExpectedIndex = (i * 2) % NumOperands;
6108  
6109       if (i == 0)
6110         InVec0 = Op0.getOperand(0);
6111       else if (i * 2 == NumOperands)
6112         InVec1 = Op0.getOperand(0);
6113
6114       SDValue Expected = (i * 2 < NumOperands) ? InVec0 : InVec1;
6115       if (I0 == ExpectedIndex)
6116         CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6117       else if (isCommutable && I1 == ExpectedIndex) {
6118         // Try to see if we can match the following dag sequence:
6119         // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6120         CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6121       }
6122     }
6123
6124     if (CanFold) {
6125       unsigned NewOpcode;
6126       switch (Opcode) {
6127       default : llvm_unreachable("Unexpected opcode found!");
6128       case ISD::ADD : NewOpcode = X86ISD::HADD; break;
6129       case ISD::FADD : NewOpcode = X86ISD::FHADD; break;
6130       case ISD::SUB : NewOpcode = X86ISD::HSUB; break;
6131       case ISD::FSUB : NewOpcode = X86ISD::FHSUB; break;
6132       }
6133  
6134       return DAG.getNode(NewOpcode, SDLoc(N), VT, InVec0, InVec1);
6135     }
6136   }
6137
6138   return SDValue();
6139 }
6140
6141 SDValue
6142 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6143   SDLoc dl(Op);
6144
6145   MVT VT = Op.getSimpleValueType();
6146   MVT ExtVT = VT.getVectorElementType();
6147   unsigned NumElems = Op.getNumOperands();
6148
6149   // Generate vectors for predicate vectors.
6150   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6151     return LowerBUILD_VECTORvXi1(Op, DAG);
6152
6153   // Vectors containing all zeros can be matched by pxor and xorps later
6154   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6155     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6156     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6157     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6158       return Op;
6159
6160     return getZeroVector(VT, Subtarget, DAG, dl);
6161   }
6162
6163   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6164   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6165   // vpcmpeqd on 256-bit vectors.
6166   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6167     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6168       return Op;
6169
6170     if (!VT.is512BitVector())
6171       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6172   }
6173
6174   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6175   if (Broadcast.getNode())
6176     return Broadcast;
6177
6178   unsigned EVTBits = ExtVT.getSizeInBits();
6179
6180   unsigned NumZero  = 0;
6181   unsigned NumNonZero = 0;
6182   unsigned NonZeros = 0;
6183   bool IsAllConstants = true;
6184   SmallSet<SDValue, 8> Values;
6185   for (unsigned i = 0; i < NumElems; ++i) {
6186     SDValue Elt = Op.getOperand(i);
6187     if (Elt.getOpcode() == ISD::UNDEF)
6188       continue;
6189     Values.insert(Elt);
6190     if (Elt.getOpcode() != ISD::Constant &&
6191         Elt.getOpcode() != ISD::ConstantFP)
6192       IsAllConstants = false;
6193     if (X86::isZeroNode(Elt))
6194       NumZero++;
6195     else {
6196       NonZeros |= (1 << i);
6197       NumNonZero++;
6198     }
6199   }
6200
6201   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6202   if (NumNonZero == 0)
6203     return DAG.getUNDEF(VT);
6204
6205   // Special case for single non-zero, non-undef, element.
6206   if (NumNonZero == 1) {
6207     unsigned Idx = countTrailingZeros(NonZeros);
6208     SDValue Item = Op.getOperand(Idx);
6209
6210     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6211     // the value are obviously zero, truncate the value to i32 and do the
6212     // insertion that way.  Only do this if the value is non-constant or if the
6213     // value is a constant being inserted into element 0.  It is cheaper to do
6214     // a constant pool load than it is to do a movd + shuffle.
6215     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6216         (!IsAllConstants || Idx == 0)) {
6217       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6218         // Handle SSE only.
6219         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6220         EVT VecVT = MVT::v4i32;
6221         unsigned VecElts = 4;
6222
6223         // Truncate the value (which may itself be a constant) to i32, and
6224         // convert it to a vector with movd (S2V+shuffle to zero extend).
6225         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6226         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6227         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6228
6229         // Now we have our 32-bit value zero extended in the low element of
6230         // a vector.  If Idx != 0, swizzle it into place.
6231         if (Idx != 0) {
6232           SmallVector<int, 4> Mask;
6233           Mask.push_back(Idx);
6234           for (unsigned i = 1; i != VecElts; ++i)
6235             Mask.push_back(i);
6236           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6237                                       &Mask[0]);
6238         }
6239         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6240       }
6241     }
6242
6243     // If we have a constant or non-constant insertion into the low element of
6244     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6245     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6246     // depending on what the source datatype is.
6247     if (Idx == 0) {
6248       if (NumZero == 0)
6249         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6250
6251       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6252           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6253         if (VT.is256BitVector() || VT.is512BitVector()) {
6254           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6255           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6256                              Item, DAG.getIntPtrConstant(0));
6257         }
6258         assert(VT.is128BitVector() && "Expected an SSE value type!");
6259         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6260         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6261         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6262       }
6263
6264       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6265         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6266         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6267         if (VT.is256BitVector()) {
6268           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6269           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6270         } else {
6271           assert(VT.is128BitVector() && "Expected an SSE value type!");
6272           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6273         }
6274         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6275       }
6276     }
6277
6278     // Is it a vector logical left shift?
6279     if (NumElems == 2 && Idx == 1 &&
6280         X86::isZeroNode(Op.getOperand(0)) &&
6281         !X86::isZeroNode(Op.getOperand(1))) {
6282       unsigned NumBits = VT.getSizeInBits();
6283       return getVShift(true, VT,
6284                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6285                                    VT, Op.getOperand(1)),
6286                        NumBits/2, DAG, *this, dl);
6287     }
6288
6289     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6290       return SDValue();
6291
6292     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6293     // is a non-constant being inserted into an element other than the low one,
6294     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6295     // movd/movss) to move this into the low element, then shuffle it into
6296     // place.
6297     if (EVTBits == 32) {
6298       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6299
6300       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6301       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6302       SmallVector<int, 8> MaskVec;
6303       for (unsigned i = 0; i != NumElems; ++i)
6304         MaskVec.push_back(i == Idx ? 0 : 1);
6305       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6306     }
6307   }
6308
6309   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6310   if (Values.size() == 1) {
6311     if (EVTBits == 32) {
6312       // Instead of a shuffle like this:
6313       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6314       // Check if it's possible to issue this instead.
6315       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6316       unsigned Idx = countTrailingZeros(NonZeros);
6317       SDValue Item = Op.getOperand(Idx);
6318       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6319         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6320     }
6321     return SDValue();
6322   }
6323
6324   // A vector full of immediates; various special cases are already
6325   // handled, so this is best done with a single constant-pool load.
6326   if (IsAllConstants)
6327     return SDValue();
6328
6329   // For AVX-length vectors, build the individual 128-bit pieces and use
6330   // shuffles to put them in place.
6331   if (VT.is256BitVector() || VT.is512BitVector()) {
6332     SmallVector<SDValue, 64> V;
6333     for (unsigned i = 0; i != NumElems; ++i)
6334       V.push_back(Op.getOperand(i));
6335
6336     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6337
6338     // Build both the lower and upper subvector.
6339     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6340                                 makeArrayRef(&V[0], NumElems/2));
6341     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6342                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6343
6344     // Recreate the wider vector with the lower and upper part.
6345     if (VT.is256BitVector())
6346       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6347     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6348   }
6349
6350   // Let legalizer expand 2-wide build_vectors.
6351   if (EVTBits == 64) {
6352     if (NumNonZero == 1) {
6353       // One half is zero or undef.
6354       unsigned Idx = countTrailingZeros(NonZeros);
6355       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6356                                  Op.getOperand(Idx));
6357       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6358     }
6359     return SDValue();
6360   }
6361
6362   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6363   if (EVTBits == 8 && NumElems == 16) {
6364     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6365                                         Subtarget, *this);
6366     if (V.getNode()) return V;
6367   }
6368
6369   if (EVTBits == 16 && NumElems == 8) {
6370     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6371                                       Subtarget, *this);
6372     if (V.getNode()) return V;
6373   }
6374
6375   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6376   if (EVTBits == 32 && NumElems == 4) {
6377     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6378                                       NumZero, DAG, Subtarget, *this);
6379     if (V.getNode())
6380       return V;
6381   }
6382
6383   // If element VT is == 32 bits, turn it into a number of shuffles.
6384   SmallVector<SDValue, 8> V(NumElems);
6385   if (NumElems == 4 && NumZero > 0) {
6386     for (unsigned i = 0; i < 4; ++i) {
6387       bool isZero = !(NonZeros & (1 << i));
6388       if (isZero)
6389         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6390       else
6391         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6392     }
6393
6394     for (unsigned i = 0; i < 2; ++i) {
6395       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6396         default: break;
6397         case 0:
6398           V[i] = V[i*2];  // Must be a zero vector.
6399           break;
6400         case 1:
6401           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6402           break;
6403         case 2:
6404           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6405           break;
6406         case 3:
6407           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6408           break;
6409       }
6410     }
6411
6412     bool Reverse1 = (NonZeros & 0x3) == 2;
6413     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6414     int MaskVec[] = {
6415       Reverse1 ? 1 : 0,
6416       Reverse1 ? 0 : 1,
6417       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6418       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6419     };
6420     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6421   }
6422
6423   if (Values.size() > 1 && VT.is128BitVector()) {
6424     // Check for a build vector of consecutive loads.
6425     for (unsigned i = 0; i < NumElems; ++i)
6426       V[i] = Op.getOperand(i);
6427
6428     // Check for elements which are consecutive loads.
6429     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6430     if (LD.getNode())
6431       return LD;
6432
6433     // Check for a build vector from mostly shuffle plus few inserting.
6434     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6435     if (Sh.getNode())
6436       return Sh;
6437
6438     // For SSE 4.1, use insertps to put the high elements into the low element.
6439     if (getSubtarget()->hasSSE41()) {
6440       SDValue Result;
6441       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6442         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6443       else
6444         Result = DAG.getUNDEF(VT);
6445
6446       for (unsigned i = 1; i < NumElems; ++i) {
6447         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6448         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6449                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6450       }
6451       return Result;
6452     }
6453
6454     // Otherwise, expand into a number of unpckl*, start by extending each of
6455     // our (non-undef) elements to the full vector width with the element in the
6456     // bottom slot of the vector (which generates no code for SSE).
6457     for (unsigned i = 0; i < NumElems; ++i) {
6458       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6459         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6460       else
6461         V[i] = DAG.getUNDEF(VT);
6462     }
6463
6464     // Next, we iteratively mix elements, e.g. for v4f32:
6465     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6466     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6467     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6468     unsigned EltStride = NumElems >> 1;
6469     while (EltStride != 0) {
6470       for (unsigned i = 0; i < EltStride; ++i) {
6471         // If V[i+EltStride] is undef and this is the first round of mixing,
6472         // then it is safe to just drop this shuffle: V[i] is already in the
6473         // right place, the one element (since it's the first round) being
6474         // inserted as undef can be dropped.  This isn't safe for successive
6475         // rounds because they will permute elements within both vectors.
6476         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6477             EltStride == NumElems/2)
6478           continue;
6479
6480         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6481       }
6482       EltStride >>= 1;
6483     }
6484     return V[0];
6485   }
6486   return SDValue();
6487 }
6488
6489 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6490 // to create 256-bit vectors from two other 128-bit ones.
6491 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6492   SDLoc dl(Op);
6493   MVT ResVT = Op.getSimpleValueType();
6494
6495   assert((ResVT.is256BitVector() ||
6496           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6497
6498   SDValue V1 = Op.getOperand(0);
6499   SDValue V2 = Op.getOperand(1);
6500   unsigned NumElems = ResVT.getVectorNumElements();
6501   if(ResVT.is256BitVector())
6502     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6503
6504   if (Op.getNumOperands() == 4) {
6505     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6506                                 ResVT.getVectorNumElements()/2);
6507     SDValue V3 = Op.getOperand(2);
6508     SDValue V4 = Op.getOperand(3);
6509     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6510       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6511   }
6512   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6513 }
6514
6515 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6516   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6517   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6518          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6519           Op.getNumOperands() == 4)));
6520
6521   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6522   // from two other 128-bit ones.
6523
6524   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6525   return LowerAVXCONCAT_VECTORS(Op, DAG);
6526 }
6527
6528 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6529                         bool hasInt256, unsigned *MaskOut = nullptr) {
6530   MVT EltVT = VT.getVectorElementType();
6531
6532   // There is no blend with immediate in AVX-512.
6533   if (VT.is512BitVector())
6534     return false;
6535
6536   if (!hasSSE41 || EltVT == MVT::i8)
6537     return false;
6538   if (!hasInt256 && VT == MVT::v16i16)
6539     return false;
6540
6541   unsigned MaskValue = 0;
6542   unsigned NumElems = VT.getVectorNumElements();
6543   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6544   unsigned NumLanes = (NumElems - 1) / 8 + 1;
6545   unsigned NumElemsInLane = NumElems / NumLanes;
6546
6547   // Blend for v16i16 should be symetric for the both lanes.
6548   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6549
6550     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6551     int EltIdx = MaskVals[i];
6552
6553     if ((EltIdx < 0 || EltIdx == (int)i) &&
6554         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6555       continue;
6556
6557     if (((unsigned)EltIdx == (i + NumElems)) &&
6558         (SndLaneEltIdx < 0 ||
6559          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6560       MaskValue |= (1 << i);
6561     else
6562       return false;
6563   }
6564
6565   if (MaskOut)
6566     *MaskOut = MaskValue;
6567   return true;
6568 }
6569
6570 // Try to lower a shuffle node into a simple blend instruction.
6571 // This function assumes isBlendMask returns true for this
6572 // SuffleVectorSDNode
6573 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6574                                           unsigned MaskValue,
6575                                           const X86Subtarget *Subtarget,
6576                                           SelectionDAG &DAG) {
6577   MVT VT = SVOp->getSimpleValueType(0);
6578   MVT EltVT = VT.getVectorElementType();
6579   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6580                      Subtarget->hasInt256() && "Trying to lower a "
6581                                                "VECTOR_SHUFFLE to a Blend but "
6582                                                "with the wrong mask"));
6583   SDValue V1 = SVOp->getOperand(0);
6584   SDValue V2 = SVOp->getOperand(1);
6585   SDLoc dl(SVOp);
6586   unsigned NumElems = VT.getVectorNumElements();
6587
6588   // Convert i32 vectors to floating point if it is not AVX2.
6589   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6590   MVT BlendVT = VT;
6591   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6592     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6593                                NumElems);
6594     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6595     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6596   }
6597
6598   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6599                             DAG.getConstant(MaskValue, MVT::i32));
6600   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6601 }
6602
6603 /// In vector type \p VT, return true if the element at index \p InputIdx
6604 /// falls on a different 128-bit lane than \p OutputIdx.
6605 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6606                                      unsigned OutputIdx) {
6607   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6608   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6609 }
6610
6611 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6612 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6613 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6614 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6615 /// zero.
6616 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6617                          SelectionDAG &DAG) {
6618   MVT VT = V1.getSimpleValueType();
6619   assert(VT.is128BitVector() || VT.is256BitVector());
6620
6621   MVT EltVT = VT.getVectorElementType();
6622   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6623   unsigned NumElts = VT.getVectorNumElements();
6624
6625   SmallVector<SDValue, 32> PshufbMask;
6626   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6627     int InputIdx = MaskVals[OutputIdx];
6628     unsigned InputByteIdx;
6629
6630     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6631       InputByteIdx = 0x80;
6632     else {
6633       // Cross lane is not allowed.
6634       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6635         return SDValue();
6636       InputByteIdx = InputIdx * EltSizeInBytes;
6637       // Index is an byte offset within the 128-bit lane.
6638       InputByteIdx &= 0xf;
6639     }
6640
6641     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6642       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6643       if (InputByteIdx != 0x80)
6644         ++InputByteIdx;
6645     }
6646   }
6647
6648   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6649   if (ShufVT != VT)
6650     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6651   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6652                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6653 }
6654
6655 // v8i16 shuffles - Prefer shuffles in the following order:
6656 // 1. [all]   pshuflw, pshufhw, optional move
6657 // 2. [ssse3] 1 x pshufb
6658 // 3. [ssse3] 2 x pshufb + 1 x por
6659 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6660 static SDValue
6661 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6662                          SelectionDAG &DAG) {
6663   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6664   SDValue V1 = SVOp->getOperand(0);
6665   SDValue V2 = SVOp->getOperand(1);
6666   SDLoc dl(SVOp);
6667   SmallVector<int, 8> MaskVals;
6668
6669   // Determine if more than 1 of the words in each of the low and high quadwords
6670   // of the result come from the same quadword of one of the two inputs.  Undef
6671   // mask values count as coming from any quadword, for better codegen.
6672   //
6673   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6674   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6675   unsigned LoQuad[] = { 0, 0, 0, 0 };
6676   unsigned HiQuad[] = { 0, 0, 0, 0 };
6677   // Indices of quads used.
6678   std::bitset<4> InputQuads;
6679   for (unsigned i = 0; i < 8; ++i) {
6680     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6681     int EltIdx = SVOp->getMaskElt(i);
6682     MaskVals.push_back(EltIdx);
6683     if (EltIdx < 0) {
6684       ++Quad[0];
6685       ++Quad[1];
6686       ++Quad[2];
6687       ++Quad[3];
6688       continue;
6689     }
6690     ++Quad[EltIdx / 4];
6691     InputQuads.set(EltIdx / 4);
6692   }
6693
6694   int BestLoQuad = -1;
6695   unsigned MaxQuad = 1;
6696   for (unsigned i = 0; i < 4; ++i) {
6697     if (LoQuad[i] > MaxQuad) {
6698       BestLoQuad = i;
6699       MaxQuad = LoQuad[i];
6700     }
6701   }
6702
6703   int BestHiQuad = -1;
6704   MaxQuad = 1;
6705   for (unsigned i = 0; i < 4; ++i) {
6706     if (HiQuad[i] > MaxQuad) {
6707       BestHiQuad = i;
6708       MaxQuad = HiQuad[i];
6709     }
6710   }
6711
6712   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6713   // of the two input vectors, shuffle them into one input vector so only a
6714   // single pshufb instruction is necessary. If there are more than 2 input
6715   // quads, disable the next transformation since it does not help SSSE3.
6716   bool V1Used = InputQuads[0] || InputQuads[1];
6717   bool V2Used = InputQuads[2] || InputQuads[3];
6718   if (Subtarget->hasSSSE3()) {
6719     if (InputQuads.count() == 2 && V1Used && V2Used) {
6720       BestLoQuad = InputQuads[0] ? 0 : 1;
6721       BestHiQuad = InputQuads[2] ? 2 : 3;
6722     }
6723     if (InputQuads.count() > 2) {
6724       BestLoQuad = -1;
6725       BestHiQuad = -1;
6726     }
6727   }
6728
6729   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6730   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6731   // words from all 4 input quadwords.
6732   SDValue NewV;
6733   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6734     int MaskV[] = {
6735       BestLoQuad < 0 ? 0 : BestLoQuad,
6736       BestHiQuad < 0 ? 1 : BestHiQuad
6737     };
6738     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6739                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6740                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6741     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6742
6743     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6744     // source words for the shuffle, to aid later transformations.
6745     bool AllWordsInNewV = true;
6746     bool InOrder[2] = { true, true };
6747     for (unsigned i = 0; i != 8; ++i) {
6748       int idx = MaskVals[i];
6749       if (idx != (int)i)
6750         InOrder[i/4] = false;
6751       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6752         continue;
6753       AllWordsInNewV = false;
6754       break;
6755     }
6756
6757     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6758     if (AllWordsInNewV) {
6759       for (int i = 0; i != 8; ++i) {
6760         int idx = MaskVals[i];
6761         if (idx < 0)
6762           continue;
6763         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6764         if ((idx != i) && idx < 4)
6765           pshufhw = false;
6766         if ((idx != i) && idx > 3)
6767           pshuflw = false;
6768       }
6769       V1 = NewV;
6770       V2Used = false;
6771       BestLoQuad = 0;
6772       BestHiQuad = 1;
6773     }
6774
6775     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6776     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6777     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6778       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6779       unsigned TargetMask = 0;
6780       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6781                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6782       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6783       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6784                              getShufflePSHUFLWImmediate(SVOp);
6785       V1 = NewV.getOperand(0);
6786       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6787     }
6788   }
6789
6790   // Promote splats to a larger type which usually leads to more efficient code.
6791   // FIXME: Is this true if pshufb is available?
6792   if (SVOp->isSplat())
6793     return PromoteSplat(SVOp, DAG);
6794
6795   // If we have SSSE3, and all words of the result are from 1 input vector,
6796   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6797   // is present, fall back to case 4.
6798   if (Subtarget->hasSSSE3()) {
6799     SmallVector<SDValue,16> pshufbMask;
6800
6801     // If we have elements from both input vectors, set the high bit of the
6802     // shuffle mask element to zero out elements that come from V2 in the V1
6803     // mask, and elements that come from V1 in the V2 mask, so that the two
6804     // results can be OR'd together.
6805     bool TwoInputs = V1Used && V2Used;
6806     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6807     if (!TwoInputs)
6808       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6809
6810     // Calculate the shuffle mask for the second input, shuffle it, and
6811     // OR it with the first shuffled input.
6812     CommuteVectorShuffleMask(MaskVals, 8);
6813     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6814     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6815     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6816   }
6817
6818   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6819   // and update MaskVals with new element order.
6820   std::bitset<8> InOrder;
6821   if (BestLoQuad >= 0) {
6822     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6823     for (int i = 0; i != 4; ++i) {
6824       int idx = MaskVals[i];
6825       if (idx < 0) {
6826         InOrder.set(i);
6827       } else if ((idx / 4) == BestLoQuad) {
6828         MaskV[i] = idx & 3;
6829         InOrder.set(i);
6830       }
6831     }
6832     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6833                                 &MaskV[0]);
6834
6835     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6836       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6837       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6838                                   NewV.getOperand(0),
6839                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6840     }
6841   }
6842
6843   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6844   // and update MaskVals with the new element order.
6845   if (BestHiQuad >= 0) {
6846     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6847     for (unsigned i = 4; i != 8; ++i) {
6848       int idx = MaskVals[i];
6849       if (idx < 0) {
6850         InOrder.set(i);
6851       } else if ((idx / 4) == BestHiQuad) {
6852         MaskV[i] = (idx & 3) + 4;
6853         InOrder.set(i);
6854       }
6855     }
6856     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6857                                 &MaskV[0]);
6858
6859     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6860       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6861       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6862                                   NewV.getOperand(0),
6863                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6864     }
6865   }
6866
6867   // In case BestHi & BestLo were both -1, which means each quadword has a word
6868   // from each of the four input quadwords, calculate the InOrder bitvector now
6869   // before falling through to the insert/extract cleanup.
6870   if (BestLoQuad == -1 && BestHiQuad == -1) {
6871     NewV = V1;
6872     for (int i = 0; i != 8; ++i)
6873       if (MaskVals[i] < 0 || MaskVals[i] == i)
6874         InOrder.set(i);
6875   }
6876
6877   // The other elements are put in the right place using pextrw and pinsrw.
6878   for (unsigned i = 0; i != 8; ++i) {
6879     if (InOrder[i])
6880       continue;
6881     int EltIdx = MaskVals[i];
6882     if (EltIdx < 0)
6883       continue;
6884     SDValue ExtOp = (EltIdx < 8) ?
6885       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6886                   DAG.getIntPtrConstant(EltIdx)) :
6887       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6888                   DAG.getIntPtrConstant(EltIdx - 8));
6889     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6890                        DAG.getIntPtrConstant(i));
6891   }
6892   return NewV;
6893 }
6894
6895 /// \brief v16i16 shuffles
6896 ///
6897 /// FIXME: We only support generation of a single pshufb currently.  We can
6898 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6899 /// well (e.g 2 x pshufb + 1 x por).
6900 static SDValue
6901 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6902   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6903   SDValue V1 = SVOp->getOperand(0);
6904   SDValue V2 = SVOp->getOperand(1);
6905   SDLoc dl(SVOp);
6906
6907   if (V2.getOpcode() != ISD::UNDEF)
6908     return SDValue();
6909
6910   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6911   return getPSHUFB(MaskVals, V1, dl, DAG);
6912 }
6913
6914 // v16i8 shuffles - Prefer shuffles in the following order:
6915 // 1. [ssse3] 1 x pshufb
6916 // 2. [ssse3] 2 x pshufb + 1 x por
6917 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6918 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6919                                         const X86Subtarget* Subtarget,
6920                                         SelectionDAG &DAG) {
6921   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6922   SDValue V1 = SVOp->getOperand(0);
6923   SDValue V2 = SVOp->getOperand(1);
6924   SDLoc dl(SVOp);
6925   ArrayRef<int> MaskVals = SVOp->getMask();
6926
6927   // Promote splats to a larger type which usually leads to more efficient code.
6928   // FIXME: Is this true if pshufb is available?
6929   if (SVOp->isSplat())
6930     return PromoteSplat(SVOp, DAG);
6931
6932   // If we have SSSE3, case 1 is generated when all result bytes come from
6933   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6934   // present, fall back to case 3.
6935
6936   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6937   if (Subtarget->hasSSSE3()) {
6938     SmallVector<SDValue,16> pshufbMask;
6939
6940     // If all result elements are from one input vector, then only translate
6941     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6942     //
6943     // Otherwise, we have elements from both input vectors, and must zero out
6944     // elements that come from V2 in the first mask, and V1 in the second mask
6945     // so that we can OR them together.
6946     for (unsigned i = 0; i != 16; ++i) {
6947       int EltIdx = MaskVals[i];
6948       if (EltIdx < 0 || EltIdx >= 16)
6949         EltIdx = 0x80;
6950       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6951     }
6952     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6953                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6954                                  MVT::v16i8, pshufbMask));
6955
6956     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6957     // the 2nd operand if it's undefined or zero.
6958     if (V2.getOpcode() == ISD::UNDEF ||
6959         ISD::isBuildVectorAllZeros(V2.getNode()))
6960       return V1;
6961
6962     // Calculate the shuffle mask for the second input, shuffle it, and
6963     // OR it with the first shuffled input.
6964     pshufbMask.clear();
6965     for (unsigned i = 0; i != 16; ++i) {
6966       int EltIdx = MaskVals[i];
6967       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6968       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6969     }
6970     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6971                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6972                                  MVT::v16i8, pshufbMask));
6973     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6974   }
6975
6976   // No SSSE3 - Calculate in place words and then fix all out of place words
6977   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6978   // the 16 different words that comprise the two doublequadword input vectors.
6979   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6980   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6981   SDValue NewV = V1;
6982   for (int i = 0; i != 8; ++i) {
6983     int Elt0 = MaskVals[i*2];
6984     int Elt1 = MaskVals[i*2+1];
6985
6986     // This word of the result is all undef, skip it.
6987     if (Elt0 < 0 && Elt1 < 0)
6988       continue;
6989
6990     // This word of the result is already in the correct place, skip it.
6991     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6992       continue;
6993
6994     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6995     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6996     SDValue InsElt;
6997
6998     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6999     // using a single extract together, load it and store it.
7000     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7001       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7002                            DAG.getIntPtrConstant(Elt1 / 2));
7003       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7004                         DAG.getIntPtrConstant(i));
7005       continue;
7006     }
7007
7008     // If Elt1 is defined, extract it from the appropriate source.  If the
7009     // source byte is not also odd, shift the extracted word left 8 bits
7010     // otherwise clear the bottom 8 bits if we need to do an or.
7011     if (Elt1 >= 0) {
7012       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7013                            DAG.getIntPtrConstant(Elt1 / 2));
7014       if ((Elt1 & 1) == 0)
7015         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7016                              DAG.getConstant(8,
7017                                   TLI.getShiftAmountTy(InsElt.getValueType())));
7018       else if (Elt0 >= 0)
7019         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7020                              DAG.getConstant(0xFF00, MVT::i16));
7021     }
7022     // If Elt0 is defined, extract it from the appropriate source.  If the
7023     // source byte is not also even, shift the extracted word right 8 bits. If
7024     // Elt1 was also defined, OR the extracted values together before
7025     // inserting them in the result.
7026     if (Elt0 >= 0) {
7027       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7028                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7029       if ((Elt0 & 1) != 0)
7030         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7031                               DAG.getConstant(8,
7032                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
7033       else if (Elt1 >= 0)
7034         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7035                              DAG.getConstant(0x00FF, MVT::i16));
7036       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7037                          : InsElt0;
7038     }
7039     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7040                        DAG.getIntPtrConstant(i));
7041   }
7042   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7043 }
7044
7045 // v32i8 shuffles - Translate to VPSHUFB if possible.
7046 static
7047 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7048                                  const X86Subtarget *Subtarget,
7049                                  SelectionDAG &DAG) {
7050   MVT VT = SVOp->getSimpleValueType(0);
7051   SDValue V1 = SVOp->getOperand(0);
7052   SDValue V2 = SVOp->getOperand(1);
7053   SDLoc dl(SVOp);
7054   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7055
7056   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7057   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7058   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7059
7060   // VPSHUFB may be generated if
7061   // (1) one of input vector is undefined or zeroinitializer.
7062   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7063   // And (2) the mask indexes don't cross the 128-bit lane.
7064   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7065       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7066     return SDValue();
7067
7068   if (V1IsAllZero && !V2IsAllZero) {
7069     CommuteVectorShuffleMask(MaskVals, 32);
7070     V1 = V2;
7071   }
7072   return getPSHUFB(MaskVals, V1, dl, DAG);
7073 }
7074
7075 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7076 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7077 /// done when every pair / quad of shuffle mask elements point to elements in
7078 /// the right sequence. e.g.
7079 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7080 static
7081 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7082                                  SelectionDAG &DAG) {
7083   MVT VT = SVOp->getSimpleValueType(0);
7084   SDLoc dl(SVOp);
7085   unsigned NumElems = VT.getVectorNumElements();
7086   MVT NewVT;
7087   unsigned Scale;
7088   switch (VT.SimpleTy) {
7089   default: llvm_unreachable("Unexpected!");
7090   case MVT::v2i64:
7091   case MVT::v2f64:
7092            return SDValue(SVOp, 0);
7093   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
7094   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
7095   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
7096   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
7097   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7098   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
7099   }
7100
7101   SmallVector<int, 8> MaskVec;
7102   for (unsigned i = 0; i != NumElems; i += Scale) {
7103     int StartIdx = -1;
7104     for (unsigned j = 0; j != Scale; ++j) {
7105       int EltIdx = SVOp->getMaskElt(i+j);
7106       if (EltIdx < 0)
7107         continue;
7108       if (StartIdx < 0)
7109         StartIdx = (EltIdx / Scale);
7110       if (EltIdx != (int)(StartIdx*Scale + j))
7111         return SDValue();
7112     }
7113     MaskVec.push_back(StartIdx);
7114   }
7115
7116   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7117   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7118   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7119 }
7120
7121 /// getVZextMovL - Return a zero-extending vector move low node.
7122 ///
7123 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7124                             SDValue SrcOp, SelectionDAG &DAG,
7125                             const X86Subtarget *Subtarget, SDLoc dl) {
7126   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7127     LoadSDNode *LD = nullptr;
7128     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7129       LD = dyn_cast<LoadSDNode>(SrcOp);
7130     if (!LD) {
7131       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7132       // instead.
7133       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7134       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7135           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7136           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7137           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7138         // PR2108
7139         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7140         return DAG.getNode(ISD::BITCAST, dl, VT,
7141                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7142                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7143                                                    OpVT,
7144                                                    SrcOp.getOperand(0)
7145                                                           .getOperand(0))));
7146       }
7147     }
7148   }
7149
7150   return DAG.getNode(ISD::BITCAST, dl, VT,
7151                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7152                                  DAG.getNode(ISD::BITCAST, dl,
7153                                              OpVT, SrcOp)));
7154 }
7155
7156 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7157 /// which could not be matched by any known target speficic shuffle
7158 static SDValue
7159 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7160
7161   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7162   if (NewOp.getNode())
7163     return NewOp;
7164
7165   MVT VT = SVOp->getSimpleValueType(0);
7166
7167   unsigned NumElems = VT.getVectorNumElements();
7168   unsigned NumLaneElems = NumElems / 2;
7169
7170   SDLoc dl(SVOp);
7171   MVT EltVT = VT.getVectorElementType();
7172   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7173   SDValue Output[2];
7174
7175   SmallVector<int, 16> Mask;
7176   for (unsigned l = 0; l < 2; ++l) {
7177     // Build a shuffle mask for the output, discovering on the fly which
7178     // input vectors to use as shuffle operands (recorded in InputUsed).
7179     // If building a suitable shuffle vector proves too hard, then bail
7180     // out with UseBuildVector set.
7181     bool UseBuildVector = false;
7182     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7183     unsigned LaneStart = l * NumLaneElems;
7184     for (unsigned i = 0; i != NumLaneElems; ++i) {
7185       // The mask element.  This indexes into the input.
7186       int Idx = SVOp->getMaskElt(i+LaneStart);
7187       if (Idx < 0) {
7188         // the mask element does not index into any input vector.
7189         Mask.push_back(-1);
7190         continue;
7191       }
7192
7193       // The input vector this mask element indexes into.
7194       int Input = Idx / NumLaneElems;
7195
7196       // Turn the index into an offset from the start of the input vector.
7197       Idx -= Input * NumLaneElems;
7198
7199       // Find or create a shuffle vector operand to hold this input.
7200       unsigned OpNo;
7201       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7202         if (InputUsed[OpNo] == Input)
7203           // This input vector is already an operand.
7204           break;
7205         if (InputUsed[OpNo] < 0) {
7206           // Create a new operand for this input vector.
7207           InputUsed[OpNo] = Input;
7208           break;
7209         }
7210       }
7211
7212       if (OpNo >= array_lengthof(InputUsed)) {
7213         // More than two input vectors used!  Give up on trying to create a
7214         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7215         UseBuildVector = true;
7216         break;
7217       }
7218
7219       // Add the mask index for the new shuffle vector.
7220       Mask.push_back(Idx + OpNo * NumLaneElems);
7221     }
7222
7223     if (UseBuildVector) {
7224       SmallVector<SDValue, 16> SVOps;
7225       for (unsigned i = 0; i != NumLaneElems; ++i) {
7226         // The mask element.  This indexes into the input.
7227         int Idx = SVOp->getMaskElt(i+LaneStart);
7228         if (Idx < 0) {
7229           SVOps.push_back(DAG.getUNDEF(EltVT));
7230           continue;
7231         }
7232
7233         // The input vector this mask element indexes into.
7234         int Input = Idx / NumElems;
7235
7236         // Turn the index into an offset from the start of the input vector.
7237         Idx -= Input * NumElems;
7238
7239         // Extract the vector element by hand.
7240         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7241                                     SVOp->getOperand(Input),
7242                                     DAG.getIntPtrConstant(Idx)));
7243       }
7244
7245       // Construct the output using a BUILD_VECTOR.
7246       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7247     } else if (InputUsed[0] < 0) {
7248       // No input vectors were used! The result is undefined.
7249       Output[l] = DAG.getUNDEF(NVT);
7250     } else {
7251       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7252                                         (InputUsed[0] % 2) * NumLaneElems,
7253                                         DAG, dl);
7254       // If only one input was used, use an undefined vector for the other.
7255       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7256         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7257                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7258       // At least one input vector was used. Create a new shuffle vector.
7259       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7260     }
7261
7262     Mask.clear();
7263   }
7264
7265   // Concatenate the result back
7266   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7267 }
7268
7269 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7270 /// 4 elements, and match them with several different shuffle types.
7271 static SDValue
7272 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7273   SDValue V1 = SVOp->getOperand(0);
7274   SDValue V2 = SVOp->getOperand(1);
7275   SDLoc dl(SVOp);
7276   MVT VT = SVOp->getSimpleValueType(0);
7277
7278   assert(VT.is128BitVector() && "Unsupported vector size");
7279
7280   std::pair<int, int> Locs[4];
7281   int Mask1[] = { -1, -1, -1, -1 };
7282   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7283
7284   unsigned NumHi = 0;
7285   unsigned NumLo = 0;
7286   for (unsigned i = 0; i != 4; ++i) {
7287     int Idx = PermMask[i];
7288     if (Idx < 0) {
7289       Locs[i] = std::make_pair(-1, -1);
7290     } else {
7291       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7292       if (Idx < 4) {
7293         Locs[i] = std::make_pair(0, NumLo);
7294         Mask1[NumLo] = Idx;
7295         NumLo++;
7296       } else {
7297         Locs[i] = std::make_pair(1, NumHi);
7298         if (2+NumHi < 4)
7299           Mask1[2+NumHi] = Idx;
7300         NumHi++;
7301       }
7302     }
7303   }
7304
7305   if (NumLo <= 2 && NumHi <= 2) {
7306     // If no more than two elements come from either vector. This can be
7307     // implemented with two shuffles. First shuffle gather the elements.
7308     // The second shuffle, which takes the first shuffle as both of its
7309     // vector operands, put the elements into the right order.
7310     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7311
7312     int Mask2[] = { -1, -1, -1, -1 };
7313
7314     for (unsigned i = 0; i != 4; ++i)
7315       if (Locs[i].first != -1) {
7316         unsigned Idx = (i < 2) ? 0 : 4;
7317         Idx += Locs[i].first * 2 + Locs[i].second;
7318         Mask2[i] = Idx;
7319       }
7320
7321     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7322   }
7323
7324   if (NumLo == 3 || NumHi == 3) {
7325     // Otherwise, we must have three elements from one vector, call it X, and
7326     // one element from the other, call it Y.  First, use a shufps to build an
7327     // intermediate vector with the one element from Y and the element from X
7328     // that will be in the same half in the final destination (the indexes don't
7329     // matter). Then, use a shufps to build the final vector, taking the half
7330     // containing the element from Y from the intermediate, and the other half
7331     // from X.
7332     if (NumHi == 3) {
7333       // Normalize it so the 3 elements come from V1.
7334       CommuteVectorShuffleMask(PermMask, 4);
7335       std::swap(V1, V2);
7336     }
7337
7338     // Find the element from V2.
7339     unsigned HiIndex;
7340     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7341       int Val = PermMask[HiIndex];
7342       if (Val < 0)
7343         continue;
7344       if (Val >= 4)
7345         break;
7346     }
7347
7348     Mask1[0] = PermMask[HiIndex];
7349     Mask1[1] = -1;
7350     Mask1[2] = PermMask[HiIndex^1];
7351     Mask1[3] = -1;
7352     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7353
7354     if (HiIndex >= 2) {
7355       Mask1[0] = PermMask[0];
7356       Mask1[1] = PermMask[1];
7357       Mask1[2] = HiIndex & 1 ? 6 : 4;
7358       Mask1[3] = HiIndex & 1 ? 4 : 6;
7359       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7360     }
7361
7362     Mask1[0] = HiIndex & 1 ? 2 : 0;
7363     Mask1[1] = HiIndex & 1 ? 0 : 2;
7364     Mask1[2] = PermMask[2];
7365     Mask1[3] = PermMask[3];
7366     if (Mask1[2] >= 0)
7367       Mask1[2] += 4;
7368     if (Mask1[3] >= 0)
7369       Mask1[3] += 4;
7370     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7371   }
7372
7373   // Break it into (shuffle shuffle_hi, shuffle_lo).
7374   int LoMask[] = { -1, -1, -1, -1 };
7375   int HiMask[] = { -1, -1, -1, -1 };
7376
7377   int *MaskPtr = LoMask;
7378   unsigned MaskIdx = 0;
7379   unsigned LoIdx = 0;
7380   unsigned HiIdx = 2;
7381   for (unsigned i = 0; i != 4; ++i) {
7382     if (i == 2) {
7383       MaskPtr = HiMask;
7384       MaskIdx = 1;
7385       LoIdx = 0;
7386       HiIdx = 2;
7387     }
7388     int Idx = PermMask[i];
7389     if (Idx < 0) {
7390       Locs[i] = std::make_pair(-1, -1);
7391     } else if (Idx < 4) {
7392       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7393       MaskPtr[LoIdx] = Idx;
7394       LoIdx++;
7395     } else {
7396       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7397       MaskPtr[HiIdx] = Idx;
7398       HiIdx++;
7399     }
7400   }
7401
7402   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7403   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7404   int MaskOps[] = { -1, -1, -1, -1 };
7405   for (unsigned i = 0; i != 4; ++i)
7406     if (Locs[i].first != -1)
7407       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7408   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7409 }
7410
7411 static bool MayFoldVectorLoad(SDValue V) {
7412   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7413     V = V.getOperand(0);
7414
7415   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7416     V = V.getOperand(0);
7417   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7418       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7419     // BUILD_VECTOR (load), undef
7420     V = V.getOperand(0);
7421
7422   return MayFoldLoad(V);
7423 }
7424
7425 static
7426 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7427   MVT VT = Op.getSimpleValueType();
7428
7429   // Canonizalize to v2f64.
7430   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7431   return DAG.getNode(ISD::BITCAST, dl, VT,
7432                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7433                                           V1, DAG));
7434 }
7435
7436 static
7437 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7438                         bool HasSSE2) {
7439   SDValue V1 = Op.getOperand(0);
7440   SDValue V2 = Op.getOperand(1);
7441   MVT VT = Op.getSimpleValueType();
7442
7443   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7444
7445   if (HasSSE2 && VT == MVT::v2f64)
7446     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7447
7448   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7449   return DAG.getNode(ISD::BITCAST, dl, VT,
7450                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7451                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7452                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7453 }
7454
7455 static
7456 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7457   SDValue V1 = Op.getOperand(0);
7458   SDValue V2 = Op.getOperand(1);
7459   MVT VT = Op.getSimpleValueType();
7460
7461   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7462          "unsupported shuffle type");
7463
7464   if (V2.getOpcode() == ISD::UNDEF)
7465     V2 = V1;
7466
7467   // v4i32 or v4f32
7468   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7469 }
7470
7471 static
7472 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7473   SDValue V1 = Op.getOperand(0);
7474   SDValue V2 = Op.getOperand(1);
7475   MVT VT = Op.getSimpleValueType();
7476   unsigned NumElems = VT.getVectorNumElements();
7477
7478   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7479   // operand of these instructions is only memory, so check if there's a
7480   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7481   // same masks.
7482   bool CanFoldLoad = false;
7483
7484   // Trivial case, when V2 comes from a load.
7485   if (MayFoldVectorLoad(V2))
7486     CanFoldLoad = true;
7487
7488   // When V1 is a load, it can be folded later into a store in isel, example:
7489   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7490   //    turns into:
7491   //  (MOVLPSmr addr:$src1, VR128:$src2)
7492   // So, recognize this potential and also use MOVLPS or MOVLPD
7493   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7494     CanFoldLoad = true;
7495
7496   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7497   if (CanFoldLoad) {
7498     if (HasSSE2 && NumElems == 2)
7499       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7500
7501     if (NumElems == 4)
7502       // If we don't care about the second element, proceed to use movss.
7503       if (SVOp->getMaskElt(1) != -1)
7504         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7505   }
7506
7507   // movl and movlp will both match v2i64, but v2i64 is never matched by
7508   // movl earlier because we make it strict to avoid messing with the movlp load
7509   // folding logic (see the code above getMOVLP call). Match it here then,
7510   // this is horrible, but will stay like this until we move all shuffle
7511   // matching to x86 specific nodes. Note that for the 1st condition all
7512   // types are matched with movsd.
7513   if (HasSSE2) {
7514     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7515     // as to remove this logic from here, as much as possible
7516     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7517       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7518     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7519   }
7520
7521   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7522
7523   // Invert the operand order and use SHUFPS to match it.
7524   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7525                               getShuffleSHUFImmediate(SVOp), DAG);
7526 }
7527
7528 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7529                                          SelectionDAG &DAG) {
7530   SDLoc dl(Load);
7531   MVT VT = Load->getSimpleValueType(0);
7532   MVT EVT = VT.getVectorElementType();
7533   SDValue Addr = Load->getOperand(1);
7534   SDValue NewAddr = DAG.getNode(
7535       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7536       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7537
7538   SDValue NewLoad =
7539       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7540                   DAG.getMachineFunction().getMachineMemOperand(
7541                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7542   return NewLoad;
7543 }
7544
7545 // It is only safe to call this function if isINSERTPSMask is true for
7546 // this shufflevector mask.
7547 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7548                            SelectionDAG &DAG) {
7549   // Generate an insertps instruction when inserting an f32 from memory onto a
7550   // v4f32 or when copying a member from one v4f32 to another.
7551   // We also use it for transferring i32 from one register to another,
7552   // since it simply copies the same bits.
7553   // If we're transferring an i32 from memory to a specific element in a
7554   // register, we output a generic DAG that will match the PINSRD
7555   // instruction.
7556   MVT VT = SVOp->getSimpleValueType(0);
7557   MVT EVT = VT.getVectorElementType();
7558   SDValue V1 = SVOp->getOperand(0);
7559   SDValue V2 = SVOp->getOperand(1);
7560   auto Mask = SVOp->getMask();
7561   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7562          "unsupported vector type for insertps/pinsrd");
7563
7564   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7565   auto FromV2Predicate = [](const int &i) { return i >= 4; };
7566   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7567
7568   SDValue From;
7569   SDValue To;
7570   unsigned DestIndex;
7571   if (FromV1 == 1) {
7572     From = V1;
7573     To = V2;
7574     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7575                 Mask.begin();
7576   } else {
7577     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7578            "More than one element from V1 and from V2, or no elements from one "
7579            "of the vectors. This case should not have returned true from "
7580            "isINSERTPSMask");
7581     From = V2;
7582     To = V1;
7583     DestIndex =
7584         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7585   }
7586
7587   if (MayFoldLoad(From)) {
7588     // Trivial case, when From comes from a load and is only used by the
7589     // shuffle. Make it use insertps from the vector that we need from that
7590     // load.
7591     SDValue NewLoad =
7592         NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7593     if (!NewLoad.getNode())
7594       return SDValue();
7595
7596     if (EVT == MVT::f32) {
7597       // Create this as a scalar to vector to match the instruction pattern.
7598       SDValue LoadScalarToVector =
7599           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7600       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7601       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7602                          InsertpsMask);
7603     } else { // EVT == MVT::i32
7604       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7605       // instruction, to match the PINSRD instruction, which loads an i32 to a
7606       // certain vector element.
7607       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7608                          DAG.getConstant(DestIndex, MVT::i32));
7609     }
7610   }
7611
7612   // Vector-element-to-vector
7613   unsigned SrcIndex = Mask[DestIndex] % 4;
7614   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7615   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7616 }
7617
7618 // Reduce a vector shuffle to zext.
7619 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7620                                     SelectionDAG &DAG) {
7621   // PMOVZX is only available from SSE41.
7622   if (!Subtarget->hasSSE41())
7623     return SDValue();
7624
7625   MVT VT = Op.getSimpleValueType();
7626
7627   // Only AVX2 support 256-bit vector integer extending.
7628   if (!Subtarget->hasInt256() && VT.is256BitVector())
7629     return SDValue();
7630
7631   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7632   SDLoc DL(Op);
7633   SDValue V1 = Op.getOperand(0);
7634   SDValue V2 = Op.getOperand(1);
7635   unsigned NumElems = VT.getVectorNumElements();
7636
7637   // Extending is an unary operation and the element type of the source vector
7638   // won't be equal to or larger than i64.
7639   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7640       VT.getVectorElementType() == MVT::i64)
7641     return SDValue();
7642
7643   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7644   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7645   while ((1U << Shift) < NumElems) {
7646     if (SVOp->getMaskElt(1U << Shift) == 1)
7647       break;
7648     Shift += 1;
7649     // The maximal ratio is 8, i.e. from i8 to i64.
7650     if (Shift > 3)
7651       return SDValue();
7652   }
7653
7654   // Check the shuffle mask.
7655   unsigned Mask = (1U << Shift) - 1;
7656   for (unsigned i = 0; i != NumElems; ++i) {
7657     int EltIdx = SVOp->getMaskElt(i);
7658     if ((i & Mask) != 0 && EltIdx != -1)
7659       return SDValue();
7660     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7661       return SDValue();
7662   }
7663
7664   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7665   MVT NeVT = MVT::getIntegerVT(NBits);
7666   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7667
7668   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7669     return SDValue();
7670
7671   // Simplify the operand as it's prepared to be fed into shuffle.
7672   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7673   if (V1.getOpcode() == ISD::BITCAST &&
7674       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7675       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7676       V1.getOperand(0).getOperand(0)
7677         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7678     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7679     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7680     ConstantSDNode *CIdx =
7681       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7682     // If it's foldable, i.e. normal load with single use, we will let code
7683     // selection to fold it. Otherwise, we will short the conversion sequence.
7684     if (CIdx && CIdx->getZExtValue() == 0 &&
7685         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7686       MVT FullVT = V.getSimpleValueType();
7687       MVT V1VT = V1.getSimpleValueType();
7688       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7689         // The "ext_vec_elt" node is wider than the result node.
7690         // In this case we should extract subvector from V.
7691         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7692         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7693         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7694                                         FullVT.getVectorNumElements()/Ratio);
7695         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7696                         DAG.getIntPtrConstant(0));
7697       }
7698       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7699     }
7700   }
7701
7702   return DAG.getNode(ISD::BITCAST, DL, VT,
7703                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7704 }
7705
7706 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7707                                       SelectionDAG &DAG) {
7708   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7709   MVT VT = Op.getSimpleValueType();
7710   SDLoc dl(Op);
7711   SDValue V1 = Op.getOperand(0);
7712   SDValue V2 = Op.getOperand(1);
7713
7714   if (isZeroShuffle(SVOp))
7715     return getZeroVector(VT, Subtarget, DAG, dl);
7716
7717   // Handle splat operations
7718   if (SVOp->isSplat()) {
7719     // Use vbroadcast whenever the splat comes from a foldable load
7720     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7721     if (Broadcast.getNode())
7722       return Broadcast;
7723   }
7724
7725   // Check integer expanding shuffles.
7726   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7727   if (NewOp.getNode())
7728     return NewOp;
7729
7730   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7731   // do it!
7732   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7733       VT == MVT::v32i8) {
7734     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7735     if (NewOp.getNode())
7736       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7737   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7738     // FIXME: Figure out a cleaner way to do this.
7739     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7740       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7741       if (NewOp.getNode()) {
7742         MVT NewVT = NewOp.getSimpleValueType();
7743         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7744                                NewVT, true, false))
7745           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7746                               dl);
7747       }
7748     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7749       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7750       if (NewOp.getNode()) {
7751         MVT NewVT = NewOp.getSimpleValueType();
7752         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7753           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7754                               dl);
7755       }
7756     }
7757   }
7758   return SDValue();
7759 }
7760
7761 SDValue
7762 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7763   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7764   SDValue V1 = Op.getOperand(0);
7765   SDValue V2 = Op.getOperand(1);
7766   MVT VT = Op.getSimpleValueType();
7767   SDLoc dl(Op);
7768   unsigned NumElems = VT.getVectorNumElements();
7769   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7770   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7771   bool V1IsSplat = false;
7772   bool V2IsSplat = false;
7773   bool HasSSE2 = Subtarget->hasSSE2();
7774   bool HasFp256    = Subtarget->hasFp256();
7775   bool HasInt256   = Subtarget->hasInt256();
7776   MachineFunction &MF = DAG.getMachineFunction();
7777   bool OptForSize = MF.getFunction()->getAttributes().
7778     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7779
7780   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7781
7782   if (V1IsUndef && V2IsUndef)
7783     return DAG.getUNDEF(VT);
7784
7785   // When we create a shuffle node we put the UNDEF node to second operand,
7786   // but in some cases the first operand may be transformed to UNDEF.
7787   // In this case we should just commute the node.
7788   if (V1IsUndef)
7789     return CommuteVectorShuffle(SVOp, DAG);
7790
7791   // Vector shuffle lowering takes 3 steps:
7792   //
7793   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7794   //    narrowing and commutation of operands should be handled.
7795   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7796   //    shuffle nodes.
7797   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7798   //    so the shuffle can be broken into other shuffles and the legalizer can
7799   //    try the lowering again.
7800   //
7801   // The general idea is that no vector_shuffle operation should be left to
7802   // be matched during isel, all of them must be converted to a target specific
7803   // node here.
7804
7805   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7806   // narrowing and commutation of operands should be handled. The actual code
7807   // doesn't include all of those, work in progress...
7808   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7809   if (NewOp.getNode())
7810     return NewOp;
7811
7812   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7813
7814   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7815   // unpckh_undef). Only use pshufd if speed is more important than size.
7816   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7817     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7818   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7819     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7820
7821   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7822       V2IsUndef && MayFoldVectorLoad(V1))
7823     return getMOVDDup(Op, dl, V1, DAG);
7824
7825   if (isMOVHLPS_v_undef_Mask(M, VT))
7826     return getMOVHighToLow(Op, dl, DAG);
7827
7828   // Use to match splats
7829   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7830       (VT == MVT::v2f64 || VT == MVT::v2i64))
7831     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7832
7833   if (isPSHUFDMask(M, VT)) {
7834     // The actual implementation will match the mask in the if above and then
7835     // during isel it can match several different instructions, not only pshufd
7836     // as its name says, sad but true, emulate the behavior for now...
7837     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7838       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7839
7840     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7841
7842     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7843       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7844
7845     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7846       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7847                                   DAG);
7848
7849     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7850                                 TargetMask, DAG);
7851   }
7852
7853   if (isPALIGNRMask(M, VT, Subtarget))
7854     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7855                                 getShufflePALIGNRImmediate(SVOp),
7856                                 DAG);
7857
7858   // Check if this can be converted into a logical shift.
7859   bool isLeft = false;
7860   unsigned ShAmt = 0;
7861   SDValue ShVal;
7862   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7863   if (isShift && ShVal.hasOneUse()) {
7864     // If the shifted value has multiple uses, it may be cheaper to use
7865     // v_set0 + movlhps or movhlps, etc.
7866     MVT EltVT = VT.getVectorElementType();
7867     ShAmt *= EltVT.getSizeInBits();
7868     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7869   }
7870
7871   if (isMOVLMask(M, VT)) {
7872     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7873       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7874     if (!isMOVLPMask(M, VT)) {
7875       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7876         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7877
7878       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7879         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7880     }
7881   }
7882
7883   // FIXME: fold these into legal mask.
7884   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7885     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7886
7887   if (isMOVHLPSMask(M, VT))
7888     return getMOVHighToLow(Op, dl, DAG);
7889
7890   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7891     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7892
7893   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7894     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7895
7896   if (isMOVLPMask(M, VT))
7897     return getMOVLP(Op, dl, DAG, HasSSE2);
7898
7899   if (ShouldXformToMOVHLPS(M, VT) ||
7900       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7901     return CommuteVectorShuffle(SVOp, DAG);
7902
7903   if (isShift) {
7904     // No better options. Use a vshldq / vsrldq.
7905     MVT EltVT = VT.getVectorElementType();
7906     ShAmt *= EltVT.getSizeInBits();
7907     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7908   }
7909
7910   bool Commuted = false;
7911   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7912   // 1,1,1,1 -> v8i16 though.
7913   V1IsSplat = isSplatVector(V1.getNode());
7914   V2IsSplat = isSplatVector(V2.getNode());
7915
7916   // Canonicalize the splat or undef, if present, to be on the RHS.
7917   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7918     CommuteVectorShuffleMask(M, NumElems);
7919     std::swap(V1, V2);
7920     std::swap(V1IsSplat, V2IsSplat);
7921     Commuted = true;
7922   }
7923
7924   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7925     // Shuffling low element of v1 into undef, just return v1.
7926     if (V2IsUndef)
7927       return V1;
7928     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7929     // the instruction selector will not match, so get a canonical MOVL with
7930     // swapped operands to undo the commute.
7931     return getMOVL(DAG, dl, VT, V2, V1);
7932   }
7933
7934   if (isUNPCKLMask(M, VT, HasInt256))
7935     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7936
7937   if (isUNPCKHMask(M, VT, HasInt256))
7938     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7939
7940   if (V2IsSplat) {
7941     // Normalize mask so all entries that point to V2 points to its first
7942     // element then try to match unpck{h|l} again. If match, return a
7943     // new vector_shuffle with the corrected mask.p
7944     SmallVector<int, 8> NewMask(M.begin(), M.end());
7945     NormalizeMask(NewMask, NumElems);
7946     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7947       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7948     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7949       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7950   }
7951
7952   if (Commuted) {
7953     // Commute is back and try unpck* again.
7954     // FIXME: this seems wrong.
7955     CommuteVectorShuffleMask(M, NumElems);
7956     std::swap(V1, V2);
7957     std::swap(V1IsSplat, V2IsSplat);
7958
7959     if (isUNPCKLMask(M, VT, HasInt256))
7960       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7961
7962     if (isUNPCKHMask(M, VT, HasInt256))
7963       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7964   }
7965
7966   // Normalize the node to match x86 shuffle ops if needed
7967   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7968     return CommuteVectorShuffle(SVOp, DAG);
7969
7970   // The checks below are all present in isShuffleMaskLegal, but they are
7971   // inlined here right now to enable us to directly emit target specific
7972   // nodes, and remove one by one until they don't return Op anymore.
7973
7974   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7975       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7976     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7977       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7978   }
7979
7980   if (isPSHUFHWMask(M, VT, HasInt256))
7981     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7982                                 getShufflePSHUFHWImmediate(SVOp),
7983                                 DAG);
7984
7985   if (isPSHUFLWMask(M, VT, HasInt256))
7986     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7987                                 getShufflePSHUFLWImmediate(SVOp),
7988                                 DAG);
7989
7990   if (isSHUFPMask(M, VT))
7991     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7992                                 getShuffleSHUFImmediate(SVOp), DAG);
7993
7994   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7995     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7996   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7997     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7998
7999   //===--------------------------------------------------------------------===//
8000   // Generate target specific nodes for 128 or 256-bit shuffles only
8001   // supported in the AVX instruction set.
8002   //
8003
8004   // Handle VMOVDDUPY permutations
8005   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8006     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8007
8008   // Handle VPERMILPS/D* permutations
8009   if (isVPERMILPMask(M, VT)) {
8010     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8011       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8012                                   getShuffleSHUFImmediate(SVOp), DAG);
8013     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8014                                 getShuffleSHUFImmediate(SVOp), DAG);
8015   }
8016
8017   unsigned Idx;
8018   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8019     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8020                               Idx*(NumElems/2), DAG, dl);
8021
8022   // Handle VPERM2F128/VPERM2I128 permutations
8023   if (isVPERM2X128Mask(M, VT, HasFp256))
8024     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8025                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8026
8027   unsigned MaskValue;
8028   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8029                   &MaskValue))
8030     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8031
8032   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8033     return getINSERTPS(SVOp, dl, DAG);
8034
8035   unsigned Imm8;
8036   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8037     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8038
8039   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8040       VT.is512BitVector()) {
8041     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8042     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8043     SmallVector<SDValue, 16> permclMask;
8044     for (unsigned i = 0; i != NumElems; ++i) {
8045       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8046     }
8047
8048     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8049     if (V2IsUndef)
8050       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8051       return DAG.getNode(X86ISD::VPERMV, dl, VT,
8052                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8053     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8054                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8055   }
8056
8057   //===--------------------------------------------------------------------===//
8058   // Since no target specific shuffle was selected for this generic one,
8059   // lower it into other known shuffles. FIXME: this isn't true yet, but
8060   // this is the plan.
8061   //
8062
8063   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8064   if (VT == MVT::v8i16) {
8065     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8066     if (NewOp.getNode())
8067       return NewOp;
8068   }
8069
8070   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8071     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8072     if (NewOp.getNode())
8073       return NewOp;
8074   }
8075
8076   if (VT == MVT::v16i8) {
8077     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8078     if (NewOp.getNode())
8079       return NewOp;
8080   }
8081
8082   if (VT == MVT::v32i8) {
8083     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8084     if (NewOp.getNode())
8085       return NewOp;
8086   }
8087
8088   // Handle all 128-bit wide vectors with 4 elements, and match them with
8089   // several different shuffle types.
8090   if (NumElems == 4 && VT.is128BitVector())
8091     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8092
8093   // Handle general 256-bit shuffles
8094   if (VT.is256BitVector())
8095     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8096
8097   return SDValue();
8098 }
8099
8100 // This function assumes its argument is a BUILD_VECTOR of constants or
8101 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8102 // true.
8103 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8104                                     unsigned &MaskValue) {
8105   MaskValue = 0;
8106   unsigned NumElems = BuildVector->getNumOperands();
8107   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8108   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8109   unsigned NumElemsInLane = NumElems / NumLanes;
8110
8111   // Blend for v16i16 should be symetric for the both lanes.
8112   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8113     SDValue EltCond = BuildVector->getOperand(i);
8114     SDValue SndLaneEltCond =
8115         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8116
8117     int Lane1Cond = -1, Lane2Cond = -1;
8118     if (isa<ConstantSDNode>(EltCond))
8119       Lane1Cond = !isZero(EltCond);
8120     if (isa<ConstantSDNode>(SndLaneEltCond))
8121       Lane2Cond = !isZero(SndLaneEltCond);
8122
8123     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8124       // Lane1Cond != 0, means we want the first argument.
8125       // Lane1Cond == 0, means we want the second argument.
8126       // The encoding of this argument is 0 for the first argument, 1
8127       // for the second. Therefore, invert the condition.
8128       MaskValue |= !Lane1Cond << i;
8129     else if (Lane1Cond < 0)
8130       MaskValue |= !Lane2Cond << i;
8131     else
8132       return false;
8133   }
8134   return true;
8135 }
8136
8137 // Try to lower a vselect node into a simple blend instruction.
8138 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8139                                    SelectionDAG &DAG) {
8140   SDValue Cond = Op.getOperand(0);
8141   SDValue LHS = Op.getOperand(1);
8142   SDValue RHS = Op.getOperand(2);
8143   SDLoc dl(Op);
8144   MVT VT = Op.getSimpleValueType();
8145   MVT EltVT = VT.getVectorElementType();
8146   unsigned NumElems = VT.getVectorNumElements();
8147
8148   // There is no blend with immediate in AVX-512.
8149   if (VT.is512BitVector())
8150     return SDValue();
8151
8152   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8153     return SDValue();
8154   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8155     return SDValue();
8156
8157   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8158     return SDValue();
8159
8160   // Check the mask for BLEND and build the value.
8161   unsigned MaskValue = 0;
8162   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8163     return SDValue();
8164
8165   // Convert i32 vectors to floating point if it is not AVX2.
8166   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8167   MVT BlendVT = VT;
8168   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8169     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8170                                NumElems);
8171     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8172     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8173   }
8174
8175   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8176                             DAG.getConstant(MaskValue, MVT::i32));
8177   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8178 }
8179
8180 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8181   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8182   if (BlendOp.getNode())
8183     return BlendOp;
8184
8185   // Some types for vselect were previously set to Expand, not Legal or
8186   // Custom. Return an empty SDValue so we fall-through to Expand, after
8187   // the Custom lowering phase.
8188   MVT VT = Op.getSimpleValueType();
8189   switch (VT.SimpleTy) {
8190   default:
8191     break;
8192   case MVT::v8i16:
8193   case MVT::v16i16:
8194     return SDValue();
8195   }
8196
8197   // We couldn't create a "Blend with immediate" node.
8198   // This node should still be legal, but we'll have to emit a blendv*
8199   // instruction.
8200   return Op;
8201 }
8202
8203 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8204   MVT VT = Op.getSimpleValueType();
8205   SDLoc dl(Op);
8206
8207   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8208     return SDValue();
8209
8210   if (VT.getSizeInBits() == 8) {
8211     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8212                                   Op.getOperand(0), Op.getOperand(1));
8213     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8214                                   DAG.getValueType(VT));
8215     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8216   }
8217
8218   if (VT.getSizeInBits() == 16) {
8219     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8220     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8221     if (Idx == 0)
8222       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8223                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8224                                      DAG.getNode(ISD::BITCAST, dl,
8225                                                  MVT::v4i32,
8226                                                  Op.getOperand(0)),
8227                                      Op.getOperand(1)));
8228     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8229                                   Op.getOperand(0), Op.getOperand(1));
8230     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8231                                   DAG.getValueType(VT));
8232     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8233   }
8234
8235   if (VT == MVT::f32) {
8236     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8237     // the result back to FR32 register. It's only worth matching if the
8238     // result has a single use which is a store or a bitcast to i32.  And in
8239     // the case of a store, it's not worth it if the index is a constant 0,
8240     // because a MOVSSmr can be used instead, which is smaller and faster.
8241     if (!Op.hasOneUse())
8242       return SDValue();
8243     SDNode *User = *Op.getNode()->use_begin();
8244     if ((User->getOpcode() != ISD::STORE ||
8245          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8246           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8247         (User->getOpcode() != ISD::BITCAST ||
8248          User->getValueType(0) != MVT::i32))
8249       return SDValue();
8250     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8251                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8252                                               Op.getOperand(0)),
8253                                               Op.getOperand(1));
8254     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8255   }
8256
8257   if (VT == MVT::i32 || VT == MVT::i64) {
8258     // ExtractPS/pextrq works with constant index.
8259     if (isa<ConstantSDNode>(Op.getOperand(1)))
8260       return Op;
8261   }
8262   return SDValue();
8263 }
8264
8265 /// Extract one bit from mask vector, like v16i1 or v8i1.
8266 /// AVX-512 feature.
8267 SDValue
8268 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8269   SDValue Vec = Op.getOperand(0);
8270   SDLoc dl(Vec);
8271   MVT VecVT = Vec.getSimpleValueType();
8272   SDValue Idx = Op.getOperand(1);
8273   MVT EltVT = Op.getSimpleValueType();
8274
8275   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8276
8277   // variable index can't be handled in mask registers,
8278   // extend vector to VR512
8279   if (!isa<ConstantSDNode>(Idx)) {
8280     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8281     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8282     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8283                               ExtVT.getVectorElementType(), Ext, Idx);
8284     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8285   }
8286
8287   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8288   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8289   unsigned MaxSift = rc->getSize()*8 - 1;
8290   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8291                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8292   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8293                     DAG.getConstant(MaxSift, MVT::i8));
8294   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8295                        DAG.getIntPtrConstant(0));
8296 }
8297
8298 SDValue
8299 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8300                                            SelectionDAG &DAG) const {
8301   SDLoc dl(Op);
8302   SDValue Vec = Op.getOperand(0);
8303   MVT VecVT = Vec.getSimpleValueType();
8304   SDValue Idx = Op.getOperand(1);
8305
8306   if (Op.getSimpleValueType() == MVT::i1)
8307     return ExtractBitFromMaskVector(Op, DAG);
8308
8309   if (!isa<ConstantSDNode>(Idx)) {
8310     if (VecVT.is512BitVector() ||
8311         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8312          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8313
8314       MVT MaskEltVT =
8315         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8316       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8317                                     MaskEltVT.getSizeInBits());
8318
8319       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8320       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8321                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8322                                 Idx, DAG.getConstant(0, getPointerTy()));
8323       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8324       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8325                         Perm, DAG.getConstant(0, getPointerTy()));
8326     }
8327     return SDValue();
8328   }
8329
8330   // If this is a 256-bit vector result, first extract the 128-bit vector and
8331   // then extract the element from the 128-bit vector.
8332   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8333
8334     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8335     // Get the 128-bit vector.
8336     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8337     MVT EltVT = VecVT.getVectorElementType();
8338
8339     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8340
8341     //if (IdxVal >= NumElems/2)
8342     //  IdxVal -= NumElems/2;
8343     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8344     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8345                        DAG.getConstant(IdxVal, MVT::i32));
8346   }
8347
8348   assert(VecVT.is128BitVector() && "Unexpected vector length");
8349
8350   if (Subtarget->hasSSE41()) {
8351     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8352     if (Res.getNode())
8353       return Res;
8354   }
8355
8356   MVT VT = Op.getSimpleValueType();
8357   // TODO: handle v16i8.
8358   if (VT.getSizeInBits() == 16) {
8359     SDValue Vec = Op.getOperand(0);
8360     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8361     if (Idx == 0)
8362       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8363                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8364                                      DAG.getNode(ISD::BITCAST, dl,
8365                                                  MVT::v4i32, Vec),
8366                                      Op.getOperand(1)));
8367     // Transform it so it match pextrw which produces a 32-bit result.
8368     MVT EltVT = MVT::i32;
8369     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8370                                   Op.getOperand(0), Op.getOperand(1));
8371     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8372                                   DAG.getValueType(VT));
8373     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8374   }
8375
8376   if (VT.getSizeInBits() == 32) {
8377     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8378     if (Idx == 0)
8379       return Op;
8380
8381     // SHUFPS the element to the lowest double word, then movss.
8382     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8383     MVT VVT = Op.getOperand(0).getSimpleValueType();
8384     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8385                                        DAG.getUNDEF(VVT), Mask);
8386     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8387                        DAG.getIntPtrConstant(0));
8388   }
8389
8390   if (VT.getSizeInBits() == 64) {
8391     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8392     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8393     //        to match extract_elt for f64.
8394     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8395     if (Idx == 0)
8396       return Op;
8397
8398     // UNPCKHPD the element to the lowest double word, then movsd.
8399     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8400     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8401     int Mask[2] = { 1, -1 };
8402     MVT VVT = Op.getOperand(0).getSimpleValueType();
8403     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8404                                        DAG.getUNDEF(VVT), Mask);
8405     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8406                        DAG.getIntPtrConstant(0));
8407   }
8408
8409   return SDValue();
8410 }
8411
8412 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8413   MVT VT = Op.getSimpleValueType();
8414   MVT EltVT = VT.getVectorElementType();
8415   SDLoc dl(Op);
8416
8417   SDValue N0 = Op.getOperand(0);
8418   SDValue N1 = Op.getOperand(1);
8419   SDValue N2 = Op.getOperand(2);
8420
8421   if (!VT.is128BitVector())
8422     return SDValue();
8423
8424   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8425       isa<ConstantSDNode>(N2)) {
8426     unsigned Opc;
8427     if (VT == MVT::v8i16)
8428       Opc = X86ISD::PINSRW;
8429     else if (VT == MVT::v16i8)
8430       Opc = X86ISD::PINSRB;
8431     else
8432       Opc = X86ISD::PINSRB;
8433
8434     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8435     // argument.
8436     if (N1.getValueType() != MVT::i32)
8437       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8438     if (N2.getValueType() != MVT::i32)
8439       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8440     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8441   }
8442
8443   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8444     // Bits [7:6] of the constant are the source select.  This will always be
8445     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8446     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8447     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8448     // Bits [5:4] of the constant are the destination select.  This is the
8449     //  value of the incoming immediate.
8450     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8451     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8452     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8453     // Create this as a scalar to vector..
8454     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8455     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8456   }
8457
8458   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8459     // PINSR* works with constant index.
8460     return Op;
8461   }
8462   return SDValue();
8463 }
8464
8465 /// Insert one bit to mask vector, like v16i1 or v8i1.
8466 /// AVX-512 feature.
8467 SDValue 
8468 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8469   SDLoc dl(Op);
8470   SDValue Vec = Op.getOperand(0);
8471   SDValue Elt = Op.getOperand(1);
8472   SDValue Idx = Op.getOperand(2);
8473   MVT VecVT = Vec.getSimpleValueType();
8474
8475   if (!isa<ConstantSDNode>(Idx)) {
8476     // Non constant index. Extend source and destination,
8477     // insert element and then truncate the result.
8478     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8479     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8480     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8481       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8482       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8483     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8484   }
8485
8486   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8487   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8488   if (Vec.getOpcode() == ISD::UNDEF)
8489     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8490                        DAG.getConstant(IdxVal, MVT::i8));
8491   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8492   unsigned MaxSift = rc->getSize()*8 - 1;
8493   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8494                     DAG.getConstant(MaxSift, MVT::i8));
8495   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8496                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8497   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8498 }
8499 SDValue
8500 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8501   MVT VT = Op.getSimpleValueType();
8502   MVT EltVT = VT.getVectorElementType();
8503   
8504   if (EltVT == MVT::i1)
8505     return InsertBitToMaskVector(Op, DAG);
8506
8507   SDLoc dl(Op);
8508   SDValue N0 = Op.getOperand(0);
8509   SDValue N1 = Op.getOperand(1);
8510   SDValue N2 = Op.getOperand(2);
8511
8512   // If this is a 256-bit vector result, first extract the 128-bit vector,
8513   // insert the element into the extracted half and then place it back.
8514   if (VT.is256BitVector() || VT.is512BitVector()) {
8515     if (!isa<ConstantSDNode>(N2))
8516       return SDValue();
8517
8518     // Get the desired 128-bit vector half.
8519     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8520     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8521
8522     // Insert the element into the desired half.
8523     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8524     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8525
8526     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8527                     DAG.getConstant(IdxIn128, MVT::i32));
8528
8529     // Insert the changed part back to the 256-bit vector
8530     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8531   }
8532
8533   if (Subtarget->hasSSE41())
8534     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8535
8536   if (EltVT == MVT::i8)
8537     return SDValue();
8538
8539   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8540     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8541     // as its second argument.
8542     if (N1.getValueType() != MVT::i32)
8543       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8544     if (N2.getValueType() != MVT::i32)
8545       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8546     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8547   }
8548   return SDValue();
8549 }
8550
8551 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8552   SDLoc dl(Op);
8553   MVT OpVT = Op.getSimpleValueType();
8554
8555   // If this is a 256-bit vector result, first insert into a 128-bit
8556   // vector and then insert into the 256-bit vector.
8557   if (!OpVT.is128BitVector()) {
8558     // Insert into a 128-bit vector.
8559     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8560     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8561                                  OpVT.getVectorNumElements() / SizeFactor);
8562
8563     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8564
8565     // Insert the 128-bit vector.
8566     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8567   }
8568
8569   if (OpVT == MVT::v1i64 &&
8570       Op.getOperand(0).getValueType() == MVT::i64)
8571     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8572
8573   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8574   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8575   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8576                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8577 }
8578
8579 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8580 // a simple subregister reference or explicit instructions to grab
8581 // upper bits of a vector.
8582 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8583                                       SelectionDAG &DAG) {
8584   SDLoc dl(Op);
8585   SDValue In =  Op.getOperand(0);
8586   SDValue Idx = Op.getOperand(1);
8587   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8588   MVT ResVT   = Op.getSimpleValueType();
8589   MVT InVT    = In.getSimpleValueType();
8590
8591   if (Subtarget->hasFp256()) {
8592     if (ResVT.is128BitVector() &&
8593         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8594         isa<ConstantSDNode>(Idx)) {
8595       return Extract128BitVector(In, IdxVal, DAG, dl);
8596     }
8597     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8598         isa<ConstantSDNode>(Idx)) {
8599       return Extract256BitVector(In, IdxVal, DAG, dl);
8600     }
8601   }
8602   return SDValue();
8603 }
8604
8605 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8606 // simple superregister reference or explicit instructions to insert
8607 // the upper bits of a vector.
8608 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8609                                      SelectionDAG &DAG) {
8610   if (Subtarget->hasFp256()) {
8611     SDLoc dl(Op.getNode());
8612     SDValue Vec = Op.getNode()->getOperand(0);
8613     SDValue SubVec = Op.getNode()->getOperand(1);
8614     SDValue Idx = Op.getNode()->getOperand(2);
8615
8616     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8617          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8618         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8619         isa<ConstantSDNode>(Idx)) {
8620       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8621       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8622     }
8623
8624     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8625         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8626         isa<ConstantSDNode>(Idx)) {
8627       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8628       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8629     }
8630   }
8631   return SDValue();
8632 }
8633
8634 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8635 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8636 // one of the above mentioned nodes. It has to be wrapped because otherwise
8637 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8638 // be used to form addressing mode. These wrapped nodes will be selected
8639 // into MOV32ri.
8640 SDValue
8641 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8642   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8643
8644   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8645   // global base reg.
8646   unsigned char OpFlag = 0;
8647   unsigned WrapperKind = X86ISD::Wrapper;
8648   CodeModel::Model M = getTargetMachine().getCodeModel();
8649
8650   if (Subtarget->isPICStyleRIPRel() &&
8651       (M == CodeModel::Small || M == CodeModel::Kernel))
8652     WrapperKind = X86ISD::WrapperRIP;
8653   else if (Subtarget->isPICStyleGOT())
8654     OpFlag = X86II::MO_GOTOFF;
8655   else if (Subtarget->isPICStyleStubPIC())
8656     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8657
8658   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8659                                              CP->getAlignment(),
8660                                              CP->getOffset(), OpFlag);
8661   SDLoc DL(CP);
8662   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8663   // With PIC, the address is actually $g + Offset.
8664   if (OpFlag) {
8665     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8666                          DAG.getNode(X86ISD::GlobalBaseReg,
8667                                      SDLoc(), getPointerTy()),
8668                          Result);
8669   }
8670
8671   return Result;
8672 }
8673
8674 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8675   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8676
8677   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8678   // global base reg.
8679   unsigned char OpFlag = 0;
8680   unsigned WrapperKind = X86ISD::Wrapper;
8681   CodeModel::Model M = getTargetMachine().getCodeModel();
8682
8683   if (Subtarget->isPICStyleRIPRel() &&
8684       (M == CodeModel::Small || M == CodeModel::Kernel))
8685     WrapperKind = X86ISD::WrapperRIP;
8686   else if (Subtarget->isPICStyleGOT())
8687     OpFlag = X86II::MO_GOTOFF;
8688   else if (Subtarget->isPICStyleStubPIC())
8689     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8690
8691   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8692                                           OpFlag);
8693   SDLoc DL(JT);
8694   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8695
8696   // With PIC, the address is actually $g + Offset.
8697   if (OpFlag)
8698     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8699                          DAG.getNode(X86ISD::GlobalBaseReg,
8700                                      SDLoc(), getPointerTy()),
8701                          Result);
8702
8703   return Result;
8704 }
8705
8706 SDValue
8707 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8708   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8709
8710   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8711   // global base reg.
8712   unsigned char OpFlag = 0;
8713   unsigned WrapperKind = X86ISD::Wrapper;
8714   CodeModel::Model M = getTargetMachine().getCodeModel();
8715
8716   if (Subtarget->isPICStyleRIPRel() &&
8717       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8718     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8719       OpFlag = X86II::MO_GOTPCREL;
8720     WrapperKind = X86ISD::WrapperRIP;
8721   } else if (Subtarget->isPICStyleGOT()) {
8722     OpFlag = X86II::MO_GOT;
8723   } else if (Subtarget->isPICStyleStubPIC()) {
8724     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8725   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8726     OpFlag = X86II::MO_DARWIN_NONLAZY;
8727   }
8728
8729   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8730
8731   SDLoc DL(Op);
8732   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8733
8734   // With PIC, the address is actually $g + Offset.
8735   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8736       !Subtarget->is64Bit()) {
8737     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8738                          DAG.getNode(X86ISD::GlobalBaseReg,
8739                                      SDLoc(), getPointerTy()),
8740                          Result);
8741   }
8742
8743   // For symbols that require a load from a stub to get the address, emit the
8744   // load.
8745   if (isGlobalStubReference(OpFlag))
8746     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8747                          MachinePointerInfo::getGOT(), false, false, false, 0);
8748
8749   return Result;
8750 }
8751
8752 SDValue
8753 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8754   // Create the TargetBlockAddressAddress node.
8755   unsigned char OpFlags =
8756     Subtarget->ClassifyBlockAddressReference();
8757   CodeModel::Model M = getTargetMachine().getCodeModel();
8758   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8759   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8760   SDLoc dl(Op);
8761   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8762                                              OpFlags);
8763
8764   if (Subtarget->isPICStyleRIPRel() &&
8765       (M == CodeModel::Small || M == CodeModel::Kernel))
8766     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8767   else
8768     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8769
8770   // With PIC, the address is actually $g + Offset.
8771   if (isGlobalRelativeToPICBase(OpFlags)) {
8772     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8773                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8774                          Result);
8775   }
8776
8777   return Result;
8778 }
8779
8780 SDValue
8781 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8782                                       int64_t Offset, SelectionDAG &DAG) const {
8783   // Create the TargetGlobalAddress node, folding in the constant
8784   // offset if it is legal.
8785   unsigned char OpFlags =
8786     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8787   CodeModel::Model M = getTargetMachine().getCodeModel();
8788   SDValue Result;
8789   if (OpFlags == X86II::MO_NO_FLAG &&
8790       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8791     // A direct static reference to a global.
8792     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8793     Offset = 0;
8794   } else {
8795     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8796   }
8797
8798   if (Subtarget->isPICStyleRIPRel() &&
8799       (M == CodeModel::Small || M == CodeModel::Kernel))
8800     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8801   else
8802     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8803
8804   // With PIC, the address is actually $g + Offset.
8805   if (isGlobalRelativeToPICBase(OpFlags)) {
8806     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8807                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8808                          Result);
8809   }
8810
8811   // For globals that require a load from a stub to get the address, emit the
8812   // load.
8813   if (isGlobalStubReference(OpFlags))
8814     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8815                          MachinePointerInfo::getGOT(), false, false, false, 0);
8816
8817   // If there was a non-zero offset that we didn't fold, create an explicit
8818   // addition for it.
8819   if (Offset != 0)
8820     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8821                          DAG.getConstant(Offset, getPointerTy()));
8822
8823   return Result;
8824 }
8825
8826 SDValue
8827 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8828   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8829   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8830   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8831 }
8832
8833 static SDValue
8834 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8835            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8836            unsigned char OperandFlags, bool LocalDynamic = false) {
8837   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8838   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8839   SDLoc dl(GA);
8840   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8841                                            GA->getValueType(0),
8842                                            GA->getOffset(),
8843                                            OperandFlags);
8844
8845   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8846                                            : X86ISD::TLSADDR;
8847
8848   if (InFlag) {
8849     SDValue Ops[] = { Chain,  TGA, *InFlag };
8850     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8851   } else {
8852     SDValue Ops[]  = { Chain, TGA };
8853     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8854   }
8855
8856   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8857   MFI->setAdjustsStack(true);
8858
8859   SDValue Flag = Chain.getValue(1);
8860   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8861 }
8862
8863 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8864 static SDValue
8865 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8866                                 const EVT PtrVT) {
8867   SDValue InFlag;
8868   SDLoc dl(GA);  // ? function entry point might be better
8869   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8870                                    DAG.getNode(X86ISD::GlobalBaseReg,
8871                                                SDLoc(), PtrVT), InFlag);
8872   InFlag = Chain.getValue(1);
8873
8874   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8875 }
8876
8877 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8878 static SDValue
8879 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8880                                 const EVT PtrVT) {
8881   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8882                     X86::RAX, X86II::MO_TLSGD);
8883 }
8884
8885 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8886                                            SelectionDAG &DAG,
8887                                            const EVT PtrVT,
8888                                            bool is64Bit) {
8889   SDLoc dl(GA);
8890
8891   // Get the start address of the TLS block for this module.
8892   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8893       .getInfo<X86MachineFunctionInfo>();
8894   MFI->incNumLocalDynamicTLSAccesses();
8895
8896   SDValue Base;
8897   if (is64Bit) {
8898     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8899                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8900   } else {
8901     SDValue InFlag;
8902     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8903         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8904     InFlag = Chain.getValue(1);
8905     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8906                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8907   }
8908
8909   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8910   // of Base.
8911
8912   // Build x@dtpoff.
8913   unsigned char OperandFlags = X86II::MO_DTPOFF;
8914   unsigned WrapperKind = X86ISD::Wrapper;
8915   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8916                                            GA->getValueType(0),
8917                                            GA->getOffset(), OperandFlags);
8918   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8919
8920   // Add x@dtpoff with the base.
8921   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8922 }
8923
8924 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8925 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8926                                    const EVT PtrVT, TLSModel::Model model,
8927                                    bool is64Bit, bool isPIC) {
8928   SDLoc dl(GA);
8929
8930   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8931   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8932                                                          is64Bit ? 257 : 256));
8933
8934   SDValue ThreadPointer =
8935       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8936                   MachinePointerInfo(Ptr), false, false, false, 0);
8937
8938   unsigned char OperandFlags = 0;
8939   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8940   // initialexec.
8941   unsigned WrapperKind = X86ISD::Wrapper;
8942   if (model == TLSModel::LocalExec) {
8943     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8944   } else if (model == TLSModel::InitialExec) {
8945     if (is64Bit) {
8946       OperandFlags = X86II::MO_GOTTPOFF;
8947       WrapperKind = X86ISD::WrapperRIP;
8948     } else {
8949       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8950     }
8951   } else {
8952     llvm_unreachable("Unexpected model");
8953   }
8954
8955   // emit "addl x@ntpoff,%eax" (local exec)
8956   // or "addl x@indntpoff,%eax" (initial exec)
8957   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8958   SDValue TGA =
8959       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8960                                  GA->getOffset(), OperandFlags);
8961   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8962
8963   if (model == TLSModel::InitialExec) {
8964     if (isPIC && !is64Bit) {
8965       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8966                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8967                            Offset);
8968     }
8969
8970     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8971                          MachinePointerInfo::getGOT(), false, false, false, 0);
8972   }
8973
8974   // The address of the thread local variable is the add of the thread
8975   // pointer with the offset of the variable.
8976   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8977 }
8978
8979 SDValue
8980 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8981
8982   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8983   const GlobalValue *GV = GA->getGlobal();
8984
8985   if (Subtarget->isTargetELF()) {
8986     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8987
8988     switch (model) {
8989       case TLSModel::GeneralDynamic:
8990         if (Subtarget->is64Bit())
8991           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8992         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8993       case TLSModel::LocalDynamic:
8994         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8995                                            Subtarget->is64Bit());
8996       case TLSModel::InitialExec:
8997       case TLSModel::LocalExec:
8998         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8999                                    Subtarget->is64Bit(),
9000                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
9001     }
9002     llvm_unreachable("Unknown TLS model.");
9003   }
9004
9005   if (Subtarget->isTargetDarwin()) {
9006     // Darwin only has one model of TLS.  Lower to that.
9007     unsigned char OpFlag = 0;
9008     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9009                            X86ISD::WrapperRIP : X86ISD::Wrapper;
9010
9011     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9012     // global base reg.
9013     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
9014                   !Subtarget->is64Bit();
9015     if (PIC32)
9016       OpFlag = X86II::MO_TLVP_PIC_BASE;
9017     else
9018       OpFlag = X86II::MO_TLVP;
9019     SDLoc DL(Op);
9020     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9021                                                 GA->getValueType(0),
9022                                                 GA->getOffset(), OpFlag);
9023     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9024
9025     // With PIC32, the address is actually $g + Offset.
9026     if (PIC32)
9027       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9028                            DAG.getNode(X86ISD::GlobalBaseReg,
9029                                        SDLoc(), getPointerTy()),
9030                            Offset);
9031
9032     // Lowering the machine isd will make sure everything is in the right
9033     // location.
9034     SDValue Chain = DAG.getEntryNode();
9035     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9036     SDValue Args[] = { Chain, Offset };
9037     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9038
9039     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9040     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9041     MFI->setAdjustsStack(true);
9042
9043     // And our return value (tls address) is in the standard call return value
9044     // location.
9045     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9046     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9047                               Chain.getValue(1));
9048   }
9049
9050   if (Subtarget->isTargetKnownWindowsMSVC() ||
9051       Subtarget->isTargetWindowsGNU()) {
9052     // Just use the implicit TLS architecture
9053     // Need to generate someting similar to:
9054     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9055     //                                  ; from TEB
9056     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
9057     //   mov     rcx, qword [rdx+rcx*8]
9058     //   mov     eax, .tls$:tlsvar
9059     //   [rax+rcx] contains the address
9060     // Windows 64bit: gs:0x58
9061     // Windows 32bit: fs:__tls_array
9062
9063     SDLoc dl(GA);
9064     SDValue Chain = DAG.getEntryNode();
9065
9066     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9067     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9068     // use its literal value of 0x2C.
9069     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9070                                         ? Type::getInt8PtrTy(*DAG.getContext(),
9071                                                              256)
9072                                         : Type::getInt32PtrTy(*DAG.getContext(),
9073                                                               257));
9074
9075     SDValue TlsArray =
9076         Subtarget->is64Bit()
9077             ? DAG.getIntPtrConstant(0x58)
9078             : (Subtarget->isTargetWindowsGNU()
9079                    ? DAG.getIntPtrConstant(0x2C)
9080                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9081
9082     SDValue ThreadPointer =
9083         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9084                     MachinePointerInfo(Ptr), false, false, false, 0);
9085
9086     // Load the _tls_index variable
9087     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9088     if (Subtarget->is64Bit())
9089       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9090                            IDX, MachinePointerInfo(), MVT::i32,
9091                            false, false, 0);
9092     else
9093       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9094                         false, false, false, 0);
9095
9096     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9097                                     getPointerTy());
9098     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9099
9100     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9101     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9102                       false, false, false, 0);
9103
9104     // Get the offset of start of .tls section
9105     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9106                                              GA->getValueType(0),
9107                                              GA->getOffset(), X86II::MO_SECREL);
9108     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9109
9110     // The address of the thread local variable is the add of the thread
9111     // pointer with the offset of the variable.
9112     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9113   }
9114
9115   llvm_unreachable("TLS not implemented for this target.");
9116 }
9117
9118 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9119 /// and take a 2 x i32 value to shift plus a shift amount.
9120 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9121   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9122   MVT VT = Op.getSimpleValueType();
9123   unsigned VTBits = VT.getSizeInBits();
9124   SDLoc dl(Op);
9125   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9126   SDValue ShOpLo = Op.getOperand(0);
9127   SDValue ShOpHi = Op.getOperand(1);
9128   SDValue ShAmt  = Op.getOperand(2);
9129   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9130   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9131   // during isel.
9132   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9133                                   DAG.getConstant(VTBits - 1, MVT::i8));
9134   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9135                                      DAG.getConstant(VTBits - 1, MVT::i8))
9136                        : DAG.getConstant(0, VT);
9137
9138   SDValue Tmp2, Tmp3;
9139   if (Op.getOpcode() == ISD::SHL_PARTS) {
9140     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9141     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9142   } else {
9143     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9144     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9145   }
9146
9147   // If the shift amount is larger or equal than the width of a part we can't
9148   // rely on the results of shld/shrd. Insert a test and select the appropriate
9149   // values for large shift amounts.
9150   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9151                                 DAG.getConstant(VTBits, MVT::i8));
9152   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9153                              AndNode, DAG.getConstant(0, MVT::i8));
9154
9155   SDValue Hi, Lo;
9156   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9157   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9158   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9159
9160   if (Op.getOpcode() == ISD::SHL_PARTS) {
9161     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9162     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9163   } else {
9164     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9165     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9166   }
9167
9168   SDValue Ops[2] = { Lo, Hi };
9169   return DAG.getMergeValues(Ops, dl);
9170 }
9171
9172 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9173                                            SelectionDAG &DAG) const {
9174   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9175
9176   if (SrcVT.isVector())
9177     return SDValue();
9178
9179   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9180          "Unknown SINT_TO_FP to lower!");
9181
9182   // These are really Legal; return the operand so the caller accepts it as
9183   // Legal.
9184   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9185     return Op;
9186   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9187       Subtarget->is64Bit()) {
9188     return Op;
9189   }
9190
9191   SDLoc dl(Op);
9192   unsigned Size = SrcVT.getSizeInBits()/8;
9193   MachineFunction &MF = DAG.getMachineFunction();
9194   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9195   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9196   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9197                                StackSlot,
9198                                MachinePointerInfo::getFixedStack(SSFI),
9199                                false, false, 0);
9200   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9201 }
9202
9203 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9204                                      SDValue StackSlot,
9205                                      SelectionDAG &DAG) const {
9206   // Build the FILD
9207   SDLoc DL(Op);
9208   SDVTList Tys;
9209   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9210   if (useSSE)
9211     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9212   else
9213     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9214
9215   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9216
9217   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9218   MachineMemOperand *MMO;
9219   if (FI) {
9220     int SSFI = FI->getIndex();
9221     MMO =
9222       DAG.getMachineFunction()
9223       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9224                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9225   } else {
9226     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9227     StackSlot = StackSlot.getOperand(1);
9228   }
9229   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9230   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9231                                            X86ISD::FILD, DL,
9232                                            Tys, Ops, SrcVT, MMO);
9233
9234   if (useSSE) {
9235     Chain = Result.getValue(1);
9236     SDValue InFlag = Result.getValue(2);
9237
9238     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9239     // shouldn't be necessary except that RFP cannot be live across
9240     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9241     MachineFunction &MF = DAG.getMachineFunction();
9242     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9243     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9244     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9245     Tys = DAG.getVTList(MVT::Other);
9246     SDValue Ops[] = {
9247       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9248     };
9249     MachineMemOperand *MMO =
9250       DAG.getMachineFunction()
9251       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9252                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9253
9254     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9255                                     Ops, Op.getValueType(), MMO);
9256     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9257                          MachinePointerInfo::getFixedStack(SSFI),
9258                          false, false, false, 0);
9259   }
9260
9261   return Result;
9262 }
9263
9264 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9265 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9266                                                SelectionDAG &DAG) const {
9267   // This algorithm is not obvious. Here it is what we're trying to output:
9268   /*
9269      movq       %rax,  %xmm0
9270      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9271      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9272      #ifdef __SSE3__
9273        haddpd   %xmm0, %xmm0
9274      #else
9275        pshufd   $0x4e, %xmm0, %xmm1
9276        addpd    %xmm1, %xmm0
9277      #endif
9278   */
9279
9280   SDLoc dl(Op);
9281   LLVMContext *Context = DAG.getContext();
9282
9283   // Build some magic constants.
9284   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9285   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9286   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9287
9288   SmallVector<Constant*,2> CV1;
9289   CV1.push_back(
9290     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9291                                       APInt(64, 0x4330000000000000ULL))));
9292   CV1.push_back(
9293     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9294                                       APInt(64, 0x4530000000000000ULL))));
9295   Constant *C1 = ConstantVector::get(CV1);
9296   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9297
9298   // Load the 64-bit value into an XMM register.
9299   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9300                             Op.getOperand(0));
9301   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9302                               MachinePointerInfo::getConstantPool(),
9303                               false, false, false, 16);
9304   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9305                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9306                               CLod0);
9307
9308   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9309                               MachinePointerInfo::getConstantPool(),
9310                               false, false, false, 16);
9311   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9312   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9313   SDValue Result;
9314
9315   if (Subtarget->hasSSE3()) {
9316     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9317     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9318   } else {
9319     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9320     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9321                                            S2F, 0x4E, DAG);
9322     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9323                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9324                          Sub);
9325   }
9326
9327   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9328                      DAG.getIntPtrConstant(0));
9329 }
9330
9331 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9332 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9333                                                SelectionDAG &DAG) const {
9334   SDLoc dl(Op);
9335   // FP constant to bias correct the final result.
9336   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9337                                    MVT::f64);
9338
9339   // Load the 32-bit value into an XMM register.
9340   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9341                              Op.getOperand(0));
9342
9343   // Zero out the upper parts of the register.
9344   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9345
9346   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9347                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9348                      DAG.getIntPtrConstant(0));
9349
9350   // Or the load with the bias.
9351   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9352                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9353                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9354                                                    MVT::v2f64, Load)),
9355                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9356                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9357                                                    MVT::v2f64, Bias)));
9358   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9359                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9360                    DAG.getIntPtrConstant(0));
9361
9362   // Subtract the bias.
9363   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9364
9365   // Handle final rounding.
9366   EVT DestVT = Op.getValueType();
9367
9368   if (DestVT.bitsLT(MVT::f64))
9369     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9370                        DAG.getIntPtrConstant(0));
9371   if (DestVT.bitsGT(MVT::f64))
9372     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9373
9374   // Handle final rounding.
9375   return Sub;
9376 }
9377
9378 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9379                                                SelectionDAG &DAG) const {
9380   SDValue N0 = Op.getOperand(0);
9381   MVT SVT = N0.getSimpleValueType();
9382   SDLoc dl(Op);
9383
9384   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9385           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9386          "Custom UINT_TO_FP is not supported!");
9387
9388   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9389   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9390                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9391 }
9392
9393 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9394                                            SelectionDAG &DAG) const {
9395   SDValue N0 = Op.getOperand(0);
9396   SDLoc dl(Op);
9397
9398   if (Op.getValueType().isVector())
9399     return lowerUINT_TO_FP_vec(Op, DAG);
9400
9401   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9402   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9403   // the optimization here.
9404   if (DAG.SignBitIsZero(N0))
9405     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9406
9407   MVT SrcVT = N0.getSimpleValueType();
9408   MVT DstVT = Op.getSimpleValueType();
9409   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9410     return LowerUINT_TO_FP_i64(Op, DAG);
9411   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9412     return LowerUINT_TO_FP_i32(Op, DAG);
9413   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9414     return SDValue();
9415
9416   // Make a 64-bit buffer, and use it to build an FILD.
9417   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9418   if (SrcVT == MVT::i32) {
9419     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9420     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9421                                      getPointerTy(), StackSlot, WordOff);
9422     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9423                                   StackSlot, MachinePointerInfo(),
9424                                   false, false, 0);
9425     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9426                                   OffsetSlot, MachinePointerInfo(),
9427                                   false, false, 0);
9428     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9429     return Fild;
9430   }
9431
9432   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9433   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9434                                StackSlot, MachinePointerInfo(),
9435                                false, false, 0);
9436   // For i64 source, we need to add the appropriate power of 2 if the input
9437   // was negative.  This is the same as the optimization in
9438   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9439   // we must be careful to do the computation in x87 extended precision, not
9440   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9441   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9442   MachineMemOperand *MMO =
9443     DAG.getMachineFunction()
9444     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9445                           MachineMemOperand::MOLoad, 8, 8);
9446
9447   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9448   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9449   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9450                                          MVT::i64, MMO);
9451
9452   APInt FF(32, 0x5F800000ULL);
9453
9454   // Check whether the sign bit is set.
9455   SDValue SignSet = DAG.getSetCC(dl,
9456                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9457                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9458                                  ISD::SETLT);
9459
9460   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9461   SDValue FudgePtr = DAG.getConstantPool(
9462                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9463                                          getPointerTy());
9464
9465   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9466   SDValue Zero = DAG.getIntPtrConstant(0);
9467   SDValue Four = DAG.getIntPtrConstant(4);
9468   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9469                                Zero, Four);
9470   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9471
9472   // Load the value out, extending it from f32 to f80.
9473   // FIXME: Avoid the extend by constructing the right constant pool?
9474   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9475                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9476                                  MVT::f32, false, false, 4);
9477   // Extend everything to 80 bits to force it to be done on x87.
9478   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9479   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9480 }
9481
9482 std::pair<SDValue,SDValue>
9483 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9484                                     bool IsSigned, bool IsReplace) const {
9485   SDLoc DL(Op);
9486
9487   EVT DstTy = Op.getValueType();
9488
9489   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9490     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9491     DstTy = MVT::i64;
9492   }
9493
9494   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9495          DstTy.getSimpleVT() >= MVT::i16 &&
9496          "Unknown FP_TO_INT to lower!");
9497
9498   // These are really Legal.
9499   if (DstTy == MVT::i32 &&
9500       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9501     return std::make_pair(SDValue(), SDValue());
9502   if (Subtarget->is64Bit() &&
9503       DstTy == MVT::i64 &&
9504       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9505     return std::make_pair(SDValue(), SDValue());
9506
9507   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9508   // stack slot, or into the FTOL runtime function.
9509   MachineFunction &MF = DAG.getMachineFunction();
9510   unsigned MemSize = DstTy.getSizeInBits()/8;
9511   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9512   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9513
9514   unsigned Opc;
9515   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9516     Opc = X86ISD::WIN_FTOL;
9517   else
9518     switch (DstTy.getSimpleVT().SimpleTy) {
9519     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9520     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9521     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9522     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9523     }
9524
9525   SDValue Chain = DAG.getEntryNode();
9526   SDValue Value = Op.getOperand(0);
9527   EVT TheVT = Op.getOperand(0).getValueType();
9528   // FIXME This causes a redundant load/store if the SSE-class value is already
9529   // in memory, such as if it is on the callstack.
9530   if (isScalarFPTypeInSSEReg(TheVT)) {
9531     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9532     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9533                          MachinePointerInfo::getFixedStack(SSFI),
9534                          false, false, 0);
9535     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9536     SDValue Ops[] = {
9537       Chain, StackSlot, DAG.getValueType(TheVT)
9538     };
9539
9540     MachineMemOperand *MMO =
9541       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9542                               MachineMemOperand::MOLoad, MemSize, MemSize);
9543     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9544     Chain = Value.getValue(1);
9545     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9546     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9547   }
9548
9549   MachineMemOperand *MMO =
9550     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9551                             MachineMemOperand::MOStore, MemSize, MemSize);
9552
9553   if (Opc != X86ISD::WIN_FTOL) {
9554     // Build the FP_TO_INT*_IN_MEM
9555     SDValue Ops[] = { Chain, Value, StackSlot };
9556     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9557                                            Ops, DstTy, MMO);
9558     return std::make_pair(FIST, StackSlot);
9559   } else {
9560     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9561       DAG.getVTList(MVT::Other, MVT::Glue),
9562       Chain, Value);
9563     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9564       MVT::i32, ftol.getValue(1));
9565     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9566       MVT::i32, eax.getValue(2));
9567     SDValue Ops[] = { eax, edx };
9568     SDValue pair = IsReplace
9569       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9570       : DAG.getMergeValues(Ops, DL);
9571     return std::make_pair(pair, SDValue());
9572   }
9573 }
9574
9575 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9576                               const X86Subtarget *Subtarget) {
9577   MVT VT = Op->getSimpleValueType(0);
9578   SDValue In = Op->getOperand(0);
9579   MVT InVT = In.getSimpleValueType();
9580   SDLoc dl(Op);
9581
9582   // Optimize vectors in AVX mode:
9583   //
9584   //   v8i16 -> v8i32
9585   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9586   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9587   //   Concat upper and lower parts.
9588   //
9589   //   v4i32 -> v4i64
9590   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9591   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9592   //   Concat upper and lower parts.
9593   //
9594
9595   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9596       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9597       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9598     return SDValue();
9599
9600   if (Subtarget->hasInt256())
9601     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9602
9603   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9604   SDValue Undef = DAG.getUNDEF(InVT);
9605   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9606   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9607   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9608
9609   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9610                              VT.getVectorNumElements()/2);
9611
9612   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9613   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9614
9615   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9616 }
9617
9618 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9619                                         SelectionDAG &DAG) {
9620   MVT VT = Op->getSimpleValueType(0);
9621   SDValue In = Op->getOperand(0);
9622   MVT InVT = In.getSimpleValueType();
9623   SDLoc DL(Op);
9624   unsigned int NumElts = VT.getVectorNumElements();
9625   if (NumElts != 8 && NumElts != 16)
9626     return SDValue();
9627
9628   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9629     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9630
9631   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9633   // Now we have only mask extension
9634   assert(InVT.getVectorElementType() == MVT::i1);
9635   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9636   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9637   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9638   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9639   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9640                            MachinePointerInfo::getConstantPool(),
9641                            false, false, false, Alignment);
9642
9643   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9644   if (VT.is512BitVector())
9645     return Brcst;
9646   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9647 }
9648
9649 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9650                                SelectionDAG &DAG) {
9651   if (Subtarget->hasFp256()) {
9652     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9653     if (Res.getNode())
9654       return Res;
9655   }
9656
9657   return SDValue();
9658 }
9659
9660 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9661                                 SelectionDAG &DAG) {
9662   SDLoc DL(Op);
9663   MVT VT = Op.getSimpleValueType();
9664   SDValue In = Op.getOperand(0);
9665   MVT SVT = In.getSimpleValueType();
9666
9667   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9668     return LowerZERO_EXTEND_AVX512(Op, DAG);
9669
9670   if (Subtarget->hasFp256()) {
9671     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9672     if (Res.getNode())
9673       return Res;
9674   }
9675
9676   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9677          VT.getVectorNumElements() != SVT.getVectorNumElements());
9678   return SDValue();
9679 }
9680
9681 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9682   SDLoc DL(Op);
9683   MVT VT = Op.getSimpleValueType();
9684   SDValue In = Op.getOperand(0);
9685   MVT InVT = In.getSimpleValueType();
9686
9687   if (VT == MVT::i1) {
9688     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9689            "Invalid scalar TRUNCATE operation");
9690     if (InVT == MVT::i32)
9691       return SDValue();
9692     if (InVT.getSizeInBits() == 64)
9693       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9694     else if (InVT.getSizeInBits() < 32)
9695       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9696     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9697   }
9698   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9699          "Invalid TRUNCATE operation");
9700
9701   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9702     if (VT.getVectorElementType().getSizeInBits() >=8)
9703       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9704
9705     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9706     unsigned NumElts = InVT.getVectorNumElements();
9707     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9708     if (InVT.getSizeInBits() < 512) {
9709       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9710       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9711       InVT = ExtVT;
9712     }
9713     
9714     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9715     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9716     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9717     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9718     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9719                            MachinePointerInfo::getConstantPool(),
9720                            false, false, false, Alignment);
9721     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9722     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9723     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9724   }
9725
9726   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9727     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9728     if (Subtarget->hasInt256()) {
9729       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9730       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9731       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9732                                 ShufMask);
9733       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9734                          DAG.getIntPtrConstant(0));
9735     }
9736
9737     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9738                                DAG.getIntPtrConstant(0));
9739     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9740                                DAG.getIntPtrConstant(2));
9741     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9742     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9743     static const int ShufMask[] = {0, 2, 4, 6};
9744     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9745   }
9746
9747   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9748     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9749     if (Subtarget->hasInt256()) {
9750       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9751
9752       SmallVector<SDValue,32> pshufbMask;
9753       for (unsigned i = 0; i < 2; ++i) {
9754         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9755         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9756         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9757         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9758         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9759         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9760         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9761         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9762         for (unsigned j = 0; j < 8; ++j)
9763           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9764       }
9765       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9766       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9767       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9768
9769       static const int ShufMask[] = {0,  2,  -1,  -1};
9770       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9771                                 &ShufMask[0]);
9772       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9773                        DAG.getIntPtrConstant(0));
9774       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9775     }
9776
9777     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9778                                DAG.getIntPtrConstant(0));
9779
9780     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9781                                DAG.getIntPtrConstant(4));
9782
9783     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9784     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9785
9786     // The PSHUFB mask:
9787     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9788                                    -1, -1, -1, -1, -1, -1, -1, -1};
9789
9790     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9791     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9792     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9793
9794     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9795     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9796
9797     // The MOVLHPS Mask:
9798     static const int ShufMask2[] = {0, 1, 4, 5};
9799     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9800     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9801   }
9802
9803   // Handle truncation of V256 to V128 using shuffles.
9804   if (!VT.is128BitVector() || !InVT.is256BitVector())
9805     return SDValue();
9806
9807   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9808
9809   unsigned NumElems = VT.getVectorNumElements();
9810   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9811
9812   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9813   // Prepare truncation shuffle mask
9814   for (unsigned i = 0; i != NumElems; ++i)
9815     MaskVec[i] = i * 2;
9816   SDValue V = DAG.getVectorShuffle(NVT, DL,
9817                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9818                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9819   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9820                      DAG.getIntPtrConstant(0));
9821 }
9822
9823 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9824                                            SelectionDAG &DAG) const {
9825   assert(!Op.getSimpleValueType().isVector());
9826
9827   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9828     /*IsSigned=*/ true, /*IsReplace=*/ false);
9829   SDValue FIST = Vals.first, StackSlot = Vals.second;
9830   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9831   if (!FIST.getNode()) return Op;
9832
9833   if (StackSlot.getNode())
9834     // Load the result.
9835     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9836                        FIST, StackSlot, MachinePointerInfo(),
9837                        false, false, false, 0);
9838
9839   // The node is the result.
9840   return FIST;
9841 }
9842
9843 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9844                                            SelectionDAG &DAG) const {
9845   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9846     /*IsSigned=*/ false, /*IsReplace=*/ false);
9847   SDValue FIST = Vals.first, StackSlot = Vals.second;
9848   assert(FIST.getNode() && "Unexpected failure");
9849
9850   if (StackSlot.getNode())
9851     // Load the result.
9852     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9853                        FIST, StackSlot, MachinePointerInfo(),
9854                        false, false, false, 0);
9855
9856   // The node is the result.
9857   return FIST;
9858 }
9859
9860 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9861   SDLoc DL(Op);
9862   MVT VT = Op.getSimpleValueType();
9863   SDValue In = Op.getOperand(0);
9864   MVT SVT = In.getSimpleValueType();
9865
9866   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9867
9868   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9869                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9870                                  In, DAG.getUNDEF(SVT)));
9871 }
9872
9873 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9874   LLVMContext *Context = DAG.getContext();
9875   SDLoc dl(Op);
9876   MVT VT = Op.getSimpleValueType();
9877   MVT EltVT = VT;
9878   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9879   if (VT.isVector()) {
9880     EltVT = VT.getVectorElementType();
9881     NumElts = VT.getVectorNumElements();
9882   }
9883   Constant *C;
9884   if (EltVT == MVT::f64)
9885     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9886                                           APInt(64, ~(1ULL << 63))));
9887   else
9888     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9889                                           APInt(32, ~(1U << 31))));
9890   C = ConstantVector::getSplat(NumElts, C);
9891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9892   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9893   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9894   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9895                              MachinePointerInfo::getConstantPool(),
9896                              false, false, false, Alignment);
9897   if (VT.isVector()) {
9898     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9899     return DAG.getNode(ISD::BITCAST, dl, VT,
9900                        DAG.getNode(ISD::AND, dl, ANDVT,
9901                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9902                                                Op.getOperand(0)),
9903                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9904   }
9905   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9906 }
9907
9908 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9909   LLVMContext *Context = DAG.getContext();
9910   SDLoc dl(Op);
9911   MVT VT = Op.getSimpleValueType();
9912   MVT EltVT = VT;
9913   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9914   if (VT.isVector()) {
9915     EltVT = VT.getVectorElementType();
9916     NumElts = VT.getVectorNumElements();
9917   }
9918   Constant *C;
9919   if (EltVT == MVT::f64)
9920     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9921                                           APInt(64, 1ULL << 63)));
9922   else
9923     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9924                                           APInt(32, 1U << 31)));
9925   C = ConstantVector::getSplat(NumElts, C);
9926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9927   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9928   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9929   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9930                              MachinePointerInfo::getConstantPool(),
9931                              false, false, false, Alignment);
9932   if (VT.isVector()) {
9933     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9934     return DAG.getNode(ISD::BITCAST, dl, VT,
9935                        DAG.getNode(ISD::XOR, dl, XORVT,
9936                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9937                                                Op.getOperand(0)),
9938                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9939   }
9940
9941   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9942 }
9943
9944 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9946   LLVMContext *Context = DAG.getContext();
9947   SDValue Op0 = Op.getOperand(0);
9948   SDValue Op1 = Op.getOperand(1);
9949   SDLoc dl(Op);
9950   MVT VT = Op.getSimpleValueType();
9951   MVT SrcVT = Op1.getSimpleValueType();
9952
9953   // If second operand is smaller, extend it first.
9954   if (SrcVT.bitsLT(VT)) {
9955     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9956     SrcVT = VT;
9957   }
9958   // And if it is bigger, shrink it first.
9959   if (SrcVT.bitsGT(VT)) {
9960     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9961     SrcVT = VT;
9962   }
9963
9964   // At this point the operands and the result should have the same
9965   // type, and that won't be f80 since that is not custom lowered.
9966
9967   // First get the sign bit of second operand.
9968   SmallVector<Constant*,4> CV;
9969   if (SrcVT == MVT::f64) {
9970     const fltSemantics &Sem = APFloat::IEEEdouble;
9971     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9972     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9973   } else {
9974     const fltSemantics &Sem = APFloat::IEEEsingle;
9975     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9976     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9977     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9978     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9979   }
9980   Constant *C = ConstantVector::get(CV);
9981   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9982   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9983                               MachinePointerInfo::getConstantPool(),
9984                               false, false, false, 16);
9985   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9986
9987   // Shift sign bit right or left if the two operands have different types.
9988   if (SrcVT.bitsGT(VT)) {
9989     // Op0 is MVT::f32, Op1 is MVT::f64.
9990     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9991     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9992                           DAG.getConstant(32, MVT::i32));
9993     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9994     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9995                           DAG.getIntPtrConstant(0));
9996   }
9997
9998   // Clear first operand sign bit.
9999   CV.clear();
10000   if (VT == MVT::f64) {
10001     const fltSemantics &Sem = APFloat::IEEEdouble;
10002     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10003                                                    APInt(64, ~(1ULL << 63)))));
10004     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10005   } else {
10006     const fltSemantics &Sem = APFloat::IEEEsingle;
10007     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10008                                                    APInt(32, ~(1U << 31)))));
10009     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10010     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10011     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10012   }
10013   C = ConstantVector::get(CV);
10014   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10015   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10016                               MachinePointerInfo::getConstantPool(),
10017                               false, false, false, 16);
10018   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10019
10020   // Or the value with the sign bit.
10021   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10022 }
10023
10024 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10025   SDValue N0 = Op.getOperand(0);
10026   SDLoc dl(Op);
10027   MVT VT = Op.getSimpleValueType();
10028
10029   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10030   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10031                                   DAG.getConstant(1, VT));
10032   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10033 }
10034
10035 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10036 //
10037 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10038                                       SelectionDAG &DAG) {
10039   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10040
10041   if (!Subtarget->hasSSE41())
10042     return SDValue();
10043
10044   if (!Op->hasOneUse())
10045     return SDValue();
10046
10047   SDNode *N = Op.getNode();
10048   SDLoc DL(N);
10049
10050   SmallVector<SDValue, 8> Opnds;
10051   DenseMap<SDValue, unsigned> VecInMap;
10052   SmallVector<SDValue, 8> VecIns;
10053   EVT VT = MVT::Other;
10054
10055   // Recognize a special case where a vector is casted into wide integer to
10056   // test all 0s.
10057   Opnds.push_back(N->getOperand(0));
10058   Opnds.push_back(N->getOperand(1));
10059
10060   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10061     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10062     // BFS traverse all OR'd operands.
10063     if (I->getOpcode() == ISD::OR) {
10064       Opnds.push_back(I->getOperand(0));
10065       Opnds.push_back(I->getOperand(1));
10066       // Re-evaluate the number of nodes to be traversed.
10067       e += 2; // 2 more nodes (LHS and RHS) are pushed.
10068       continue;
10069     }
10070
10071     // Quit if a non-EXTRACT_VECTOR_ELT
10072     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10073       return SDValue();
10074
10075     // Quit if without a constant index.
10076     SDValue Idx = I->getOperand(1);
10077     if (!isa<ConstantSDNode>(Idx))
10078       return SDValue();
10079
10080     SDValue ExtractedFromVec = I->getOperand(0);
10081     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10082     if (M == VecInMap.end()) {
10083       VT = ExtractedFromVec.getValueType();
10084       // Quit if not 128/256-bit vector.
10085       if (!VT.is128BitVector() && !VT.is256BitVector())
10086         return SDValue();
10087       // Quit if not the same type.
10088       if (VecInMap.begin() != VecInMap.end() &&
10089           VT != VecInMap.begin()->first.getValueType())
10090         return SDValue();
10091       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10092       VecIns.push_back(ExtractedFromVec);
10093     }
10094     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10095   }
10096
10097   assert((VT.is128BitVector() || VT.is256BitVector()) &&
10098          "Not extracted from 128-/256-bit vector.");
10099
10100   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10101
10102   for (DenseMap<SDValue, unsigned>::const_iterator
10103         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10104     // Quit if not all elements are used.
10105     if (I->second != FullMask)
10106       return SDValue();
10107   }
10108
10109   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10110
10111   // Cast all vectors into TestVT for PTEST.
10112   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10113     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10114
10115   // If more than one full vectors are evaluated, OR them first before PTEST.
10116   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10117     // Each iteration will OR 2 nodes and append the result until there is only
10118     // 1 node left, i.e. the final OR'd value of all vectors.
10119     SDValue LHS = VecIns[Slot];
10120     SDValue RHS = VecIns[Slot + 1];
10121     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10122   }
10123
10124   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10125                      VecIns.back(), VecIns.back());
10126 }
10127
10128 /// \brief return true if \c Op has a use that doesn't just read flags.
10129 static bool hasNonFlagsUse(SDValue Op) {
10130   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10131        ++UI) {
10132     SDNode *User = *UI;
10133     unsigned UOpNo = UI.getOperandNo();
10134     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10135       // Look pass truncate.
10136       UOpNo = User->use_begin().getOperandNo();
10137       User = *User->use_begin();
10138     }
10139
10140     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10141         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10142       return true;
10143   }
10144   return false;
10145 }
10146
10147 /// Emit nodes that will be selected as "test Op0,Op0", or something
10148 /// equivalent.
10149 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10150                                     SelectionDAG &DAG) const {
10151   if (Op.getValueType() == MVT::i1)
10152     // KORTEST instruction should be selected
10153     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10154                        DAG.getConstant(0, Op.getValueType()));
10155
10156   // CF and OF aren't always set the way we want. Determine which
10157   // of these we need.
10158   bool NeedCF = false;
10159   bool NeedOF = false;
10160   switch (X86CC) {
10161   default: break;
10162   case X86::COND_A: case X86::COND_AE:
10163   case X86::COND_B: case X86::COND_BE:
10164     NeedCF = true;
10165     break;
10166   case X86::COND_G: case X86::COND_GE:
10167   case X86::COND_L: case X86::COND_LE:
10168   case X86::COND_O: case X86::COND_NO: {
10169     // Check if we really need to set the
10170     // Overflow flag. If NoSignedWrap is present
10171     // that is not actually needed.
10172     switch (Op->getOpcode()) {
10173     case ISD::ADD:
10174     case ISD::SUB:
10175     case ISD::MUL:
10176     case ISD::SHL: {
10177       const BinaryWithFlagsSDNode *BinNode =
10178           cast<BinaryWithFlagsSDNode>(Op.getNode());
10179       if (BinNode->hasNoSignedWrap())
10180         break;
10181     }
10182     default:
10183       NeedOF = true;
10184       break;
10185     }
10186     break;
10187   }
10188   }
10189   // See if we can use the EFLAGS value from the operand instead of
10190   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10191   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10192   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10193     // Emit a CMP with 0, which is the TEST pattern.
10194     //if (Op.getValueType() == MVT::i1)
10195     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10196     //                     DAG.getConstant(0, MVT::i1));
10197     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10198                        DAG.getConstant(0, Op.getValueType()));
10199   }
10200   unsigned Opcode = 0;
10201   unsigned NumOperands = 0;
10202
10203   // Truncate operations may prevent the merge of the SETCC instruction
10204   // and the arithmetic instruction before it. Attempt to truncate the operands
10205   // of the arithmetic instruction and use a reduced bit-width instruction.
10206   bool NeedTruncation = false;
10207   SDValue ArithOp = Op;
10208   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10209     SDValue Arith = Op->getOperand(0);
10210     // Both the trunc and the arithmetic op need to have one user each.
10211     if (Arith->hasOneUse())
10212       switch (Arith.getOpcode()) {
10213         default: break;
10214         case ISD::ADD:
10215         case ISD::SUB:
10216         case ISD::AND:
10217         case ISD::OR:
10218         case ISD::XOR: {
10219           NeedTruncation = true;
10220           ArithOp = Arith;
10221         }
10222       }
10223   }
10224
10225   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10226   // which may be the result of a CAST.  We use the variable 'Op', which is the
10227   // non-casted variable when we check for possible users.
10228   switch (ArithOp.getOpcode()) {
10229   case ISD::ADD:
10230     // Due to an isel shortcoming, be conservative if this add is likely to be
10231     // selected as part of a load-modify-store instruction. When the root node
10232     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10233     // uses of other nodes in the match, such as the ADD in this case. This
10234     // leads to the ADD being left around and reselected, with the result being
10235     // two adds in the output.  Alas, even if none our users are stores, that
10236     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10237     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10238     // climbing the DAG back to the root, and it doesn't seem to be worth the
10239     // effort.
10240     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10241          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10242       if (UI->getOpcode() != ISD::CopyToReg &&
10243           UI->getOpcode() != ISD::SETCC &&
10244           UI->getOpcode() != ISD::STORE)
10245         goto default_case;
10246
10247     if (ConstantSDNode *C =
10248         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10249       // An add of one will be selected as an INC.
10250       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10251         Opcode = X86ISD::INC;
10252         NumOperands = 1;
10253         break;
10254       }
10255
10256       // An add of negative one (subtract of one) will be selected as a DEC.
10257       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10258         Opcode = X86ISD::DEC;
10259         NumOperands = 1;
10260         break;
10261       }
10262     }
10263
10264     // Otherwise use a regular EFLAGS-setting add.
10265     Opcode = X86ISD::ADD;
10266     NumOperands = 2;
10267     break;
10268   case ISD::SHL:
10269   case ISD::SRL:
10270     // If we have a constant logical shift that's only used in a comparison
10271     // against zero turn it into an equivalent AND. This allows turning it into
10272     // a TEST instruction later.
10273     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10274         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10275       EVT VT = Op.getValueType();
10276       unsigned BitWidth = VT.getSizeInBits();
10277       unsigned ShAmt = Op->getConstantOperandVal(1);
10278       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10279         break;
10280       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10281                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10282                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10283       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10284         break;
10285       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10286                                 DAG.getConstant(Mask, VT));
10287       DAG.ReplaceAllUsesWith(Op, New);
10288       Op = New;
10289     }
10290     break;
10291
10292   case ISD::AND:
10293     // If the primary and result isn't used, don't bother using X86ISD::AND,
10294     // because a TEST instruction will be better.
10295     if (!hasNonFlagsUse(Op))
10296       break;
10297     // FALL THROUGH
10298   case ISD::SUB:
10299   case ISD::OR:
10300   case ISD::XOR:
10301     // Due to the ISEL shortcoming noted above, be conservative if this op is
10302     // likely to be selected as part of a load-modify-store instruction.
10303     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10304            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10305       if (UI->getOpcode() == ISD::STORE)
10306         goto default_case;
10307
10308     // Otherwise use a regular EFLAGS-setting instruction.
10309     switch (ArithOp.getOpcode()) {
10310     default: llvm_unreachable("unexpected operator!");
10311     case ISD::SUB: Opcode = X86ISD::SUB; break;
10312     case ISD::XOR: Opcode = X86ISD::XOR; break;
10313     case ISD::AND: Opcode = X86ISD::AND; break;
10314     case ISD::OR: {
10315       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10316         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10317         if (EFLAGS.getNode())
10318           return EFLAGS;
10319       }
10320       Opcode = X86ISD::OR;
10321       break;
10322     }
10323     }
10324
10325     NumOperands = 2;
10326     break;
10327   case X86ISD::ADD:
10328   case X86ISD::SUB:
10329   case X86ISD::INC:
10330   case X86ISD::DEC:
10331   case X86ISD::OR:
10332   case X86ISD::XOR:
10333   case X86ISD::AND:
10334     return SDValue(Op.getNode(), 1);
10335   default:
10336   default_case:
10337     break;
10338   }
10339
10340   // If we found that truncation is beneficial, perform the truncation and
10341   // update 'Op'.
10342   if (NeedTruncation) {
10343     EVT VT = Op.getValueType();
10344     SDValue WideVal = Op->getOperand(0);
10345     EVT WideVT = WideVal.getValueType();
10346     unsigned ConvertedOp = 0;
10347     // Use a target machine opcode to prevent further DAGCombine
10348     // optimizations that may separate the arithmetic operations
10349     // from the setcc node.
10350     switch (WideVal.getOpcode()) {
10351       default: break;
10352       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10353       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10354       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10355       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10356       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10357     }
10358
10359     if (ConvertedOp) {
10360       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10361       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10362         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10363         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10364         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10365       }
10366     }
10367   }
10368
10369   if (Opcode == 0)
10370     // Emit a CMP with 0, which is the TEST pattern.
10371     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10372                        DAG.getConstant(0, Op.getValueType()));
10373
10374   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10375   SmallVector<SDValue, 4> Ops;
10376   for (unsigned i = 0; i != NumOperands; ++i)
10377     Ops.push_back(Op.getOperand(i));
10378
10379   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10380   DAG.ReplaceAllUsesWith(Op, New);
10381   return SDValue(New.getNode(), 1);
10382 }
10383
10384 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10385 /// equivalent.
10386 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10387                                    SDLoc dl, SelectionDAG &DAG) const {
10388   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10389     if (C->getAPIntValue() == 0)
10390       return EmitTest(Op0, X86CC, dl, DAG);
10391
10392      if (Op0.getValueType() == MVT::i1)
10393        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10394   }
10395  
10396   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10397        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10398     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10399     // This avoids subregister aliasing issues. Keep the smaller reference 
10400     // if we're optimizing for size, however, as that'll allow better folding 
10401     // of memory operations.
10402     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10403         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10404              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10405         !Subtarget->isAtom()) {
10406       unsigned ExtendOp =
10407           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10408       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10409       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10410     }
10411     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10412     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10413     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10414                               Op0, Op1);
10415     return SDValue(Sub.getNode(), 1);
10416   }
10417   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10418 }
10419
10420 /// Convert a comparison if required by the subtarget.
10421 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10422                                                  SelectionDAG &DAG) const {
10423   // If the subtarget does not support the FUCOMI instruction, floating-point
10424   // comparisons have to be converted.
10425   if (Subtarget->hasCMov() ||
10426       Cmp.getOpcode() != X86ISD::CMP ||
10427       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10428       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10429     return Cmp;
10430
10431   // The instruction selector will select an FUCOM instruction instead of
10432   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10433   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10434   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10435   SDLoc dl(Cmp);
10436   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10437   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10438   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10439                             DAG.getConstant(8, MVT::i8));
10440   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10441   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10442 }
10443
10444 static bool isAllOnes(SDValue V) {
10445   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10446   return C && C->isAllOnesValue();
10447 }
10448
10449 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10450 /// if it's possible.
10451 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10452                                      SDLoc dl, SelectionDAG &DAG) const {
10453   SDValue Op0 = And.getOperand(0);
10454   SDValue Op1 = And.getOperand(1);
10455   if (Op0.getOpcode() == ISD::TRUNCATE)
10456     Op0 = Op0.getOperand(0);
10457   if (Op1.getOpcode() == ISD::TRUNCATE)
10458     Op1 = Op1.getOperand(0);
10459
10460   SDValue LHS, RHS;
10461   if (Op1.getOpcode() == ISD::SHL)
10462     std::swap(Op0, Op1);
10463   if (Op0.getOpcode() == ISD::SHL) {
10464     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10465       if (And00C->getZExtValue() == 1) {
10466         // If we looked past a truncate, check that it's only truncating away
10467         // known zeros.
10468         unsigned BitWidth = Op0.getValueSizeInBits();
10469         unsigned AndBitWidth = And.getValueSizeInBits();
10470         if (BitWidth > AndBitWidth) {
10471           APInt Zeros, Ones;
10472           DAG.computeKnownBits(Op0, Zeros, Ones);
10473           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10474             return SDValue();
10475         }
10476         LHS = Op1;
10477         RHS = Op0.getOperand(1);
10478       }
10479   } else if (Op1.getOpcode() == ISD::Constant) {
10480     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10481     uint64_t AndRHSVal = AndRHS->getZExtValue();
10482     SDValue AndLHS = Op0;
10483
10484     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10485       LHS = AndLHS.getOperand(0);
10486       RHS = AndLHS.getOperand(1);
10487     }
10488
10489     // Use BT if the immediate can't be encoded in a TEST instruction.
10490     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10491       LHS = AndLHS;
10492       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10493     }
10494   }
10495
10496   if (LHS.getNode()) {
10497     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10498     // instruction.  Since the shift amount is in-range-or-undefined, we know
10499     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10500     // the encoding for the i16 version is larger than the i32 version.
10501     // Also promote i16 to i32 for performance / code size reason.
10502     if (LHS.getValueType() == MVT::i8 ||
10503         LHS.getValueType() == MVT::i16)
10504       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10505
10506     // If the operand types disagree, extend the shift amount to match.  Since
10507     // BT ignores high bits (like shifts) we can use anyextend.
10508     if (LHS.getValueType() != RHS.getValueType())
10509       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10510
10511     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10512     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10513     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10514                        DAG.getConstant(Cond, MVT::i8), BT);
10515   }
10516
10517   return SDValue();
10518 }
10519
10520 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10521 /// mask CMPs.
10522 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10523                               SDValue &Op1) {
10524   unsigned SSECC;
10525   bool Swap = false;
10526
10527   // SSE Condition code mapping:
10528   //  0 - EQ
10529   //  1 - LT
10530   //  2 - LE
10531   //  3 - UNORD
10532   //  4 - NEQ
10533   //  5 - NLT
10534   //  6 - NLE
10535   //  7 - ORD
10536   switch (SetCCOpcode) {
10537   default: llvm_unreachable("Unexpected SETCC condition");
10538   case ISD::SETOEQ:
10539   case ISD::SETEQ:  SSECC = 0; break;
10540   case ISD::SETOGT:
10541   case ISD::SETGT:  Swap = true; // Fallthrough
10542   case ISD::SETLT:
10543   case ISD::SETOLT: SSECC = 1; break;
10544   case ISD::SETOGE:
10545   case ISD::SETGE:  Swap = true; // Fallthrough
10546   case ISD::SETLE:
10547   case ISD::SETOLE: SSECC = 2; break;
10548   case ISD::SETUO:  SSECC = 3; break;
10549   case ISD::SETUNE:
10550   case ISD::SETNE:  SSECC = 4; break;
10551   case ISD::SETULE: Swap = true; // Fallthrough
10552   case ISD::SETUGE: SSECC = 5; break;
10553   case ISD::SETULT: Swap = true; // Fallthrough
10554   case ISD::SETUGT: SSECC = 6; break;
10555   case ISD::SETO:   SSECC = 7; break;
10556   case ISD::SETUEQ:
10557   case ISD::SETONE: SSECC = 8; break;
10558   }
10559   if (Swap)
10560     std::swap(Op0, Op1);
10561
10562   return SSECC;
10563 }
10564
10565 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10566 // ones, and then concatenate the result back.
10567 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10568   MVT VT = Op.getSimpleValueType();
10569
10570   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10571          "Unsupported value type for operation");
10572
10573   unsigned NumElems = VT.getVectorNumElements();
10574   SDLoc dl(Op);
10575   SDValue CC = Op.getOperand(2);
10576
10577   // Extract the LHS vectors
10578   SDValue LHS = Op.getOperand(0);
10579   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10580   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10581
10582   // Extract the RHS vectors
10583   SDValue RHS = Op.getOperand(1);
10584   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10585   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10586
10587   // Issue the operation on the smaller types and concatenate the result back
10588   MVT EltVT = VT.getVectorElementType();
10589   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10590   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10591                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10592                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10593 }
10594
10595 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10596                                      const X86Subtarget *Subtarget) {
10597   SDValue Op0 = Op.getOperand(0);
10598   SDValue Op1 = Op.getOperand(1);
10599   SDValue CC = Op.getOperand(2);
10600   MVT VT = Op.getSimpleValueType();
10601   SDLoc dl(Op);
10602
10603   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10604          Op.getValueType().getScalarType() == MVT::i1 &&
10605          "Cannot set masked compare for this operation");
10606
10607   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10608   unsigned  Opc = 0;
10609   bool Unsigned = false;
10610   bool Swap = false;
10611   unsigned SSECC;
10612   switch (SetCCOpcode) {
10613   default: llvm_unreachable("Unexpected SETCC condition");
10614   case ISD::SETNE:  SSECC = 4; break;
10615   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10616   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10617   case ISD::SETLT:  Swap = true; //fall-through
10618   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10619   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10620   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10621   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10622   case ISD::SETULE: Unsigned = true; //fall-through
10623   case ISD::SETLE:  SSECC = 2; break;
10624   }
10625
10626   if (Swap)
10627     std::swap(Op0, Op1);
10628   if (Opc)
10629     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10630   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10631   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10632                      DAG.getConstant(SSECC, MVT::i8));
10633 }
10634
10635 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10636 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10637 /// return an empty value.
10638 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10639 {
10640   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10641   if (!BV)
10642     return SDValue();
10643
10644   MVT VT = Op1.getSimpleValueType();
10645   MVT EVT = VT.getVectorElementType();
10646   unsigned n = VT.getVectorNumElements();
10647   SmallVector<SDValue, 8> ULTOp1;
10648
10649   for (unsigned i = 0; i < n; ++i) {
10650     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10651     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10652       return SDValue();
10653
10654     // Avoid underflow.
10655     APInt Val = Elt->getAPIntValue();
10656     if (Val == 0)
10657       return SDValue();
10658
10659     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10660   }
10661
10662   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10663 }
10664
10665 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10666                            SelectionDAG &DAG) {
10667   SDValue Op0 = Op.getOperand(0);
10668   SDValue Op1 = Op.getOperand(1);
10669   SDValue CC = Op.getOperand(2);
10670   MVT VT = Op.getSimpleValueType();
10671   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10672   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10673   SDLoc dl(Op);
10674
10675   if (isFP) {
10676 #ifndef NDEBUG
10677     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10678     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10679 #endif
10680
10681     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10682     unsigned Opc = X86ISD::CMPP;
10683     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10684       assert(VT.getVectorNumElements() <= 16);
10685       Opc = X86ISD::CMPM;
10686     }
10687     // In the two special cases we can't handle, emit two comparisons.
10688     if (SSECC == 8) {
10689       unsigned CC0, CC1;
10690       unsigned CombineOpc;
10691       if (SetCCOpcode == ISD::SETUEQ) {
10692         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10693       } else {
10694         assert(SetCCOpcode == ISD::SETONE);
10695         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10696       }
10697
10698       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10699                                  DAG.getConstant(CC0, MVT::i8));
10700       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10701                                  DAG.getConstant(CC1, MVT::i8));
10702       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10703     }
10704     // Handle all other FP comparisons here.
10705     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10706                        DAG.getConstant(SSECC, MVT::i8));
10707   }
10708
10709   // Break 256-bit integer vector compare into smaller ones.
10710   if (VT.is256BitVector() && !Subtarget->hasInt256())
10711     return Lower256IntVSETCC(Op, DAG);
10712
10713   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10714   EVT OpVT = Op1.getValueType();
10715   if (Subtarget->hasAVX512()) {
10716     if (Op1.getValueType().is512BitVector() ||
10717         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10718       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10719
10720     // In AVX-512 architecture setcc returns mask with i1 elements,
10721     // But there is no compare instruction for i8 and i16 elements.
10722     // We are not talking about 512-bit operands in this case, these
10723     // types are illegal.
10724     if (MaskResult &&
10725         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10726          OpVT.getVectorElementType().getSizeInBits() >= 8))
10727       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10728                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10729   }
10730
10731   // We are handling one of the integer comparisons here.  Since SSE only has
10732   // GT and EQ comparisons for integer, swapping operands and multiple
10733   // operations may be required for some comparisons.
10734   unsigned Opc;
10735   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10736   bool Subus = false;
10737
10738   switch (SetCCOpcode) {
10739   default: llvm_unreachable("Unexpected SETCC condition");
10740   case ISD::SETNE:  Invert = true;
10741   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10742   case ISD::SETLT:  Swap = true;
10743   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10744   case ISD::SETGE:  Swap = true;
10745   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10746                     Invert = true; break;
10747   case ISD::SETULT: Swap = true;
10748   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10749                     FlipSigns = true; break;
10750   case ISD::SETUGE: Swap = true;
10751   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10752                     FlipSigns = true; Invert = true; break;
10753   }
10754
10755   // Special case: Use min/max operations for SETULE/SETUGE
10756   MVT VET = VT.getVectorElementType();
10757   bool hasMinMax =
10758        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10759     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10760
10761   if (hasMinMax) {
10762     switch (SetCCOpcode) {
10763     default: break;
10764     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10765     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10766     }
10767
10768     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10769   }
10770
10771   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10772   if (!MinMax && hasSubus) {
10773     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10774     // Op0 u<= Op1:
10775     //   t = psubus Op0, Op1
10776     //   pcmpeq t, <0..0>
10777     switch (SetCCOpcode) {
10778     default: break;
10779     case ISD::SETULT: {
10780       // If the comparison is against a constant we can turn this into a
10781       // setule.  With psubus, setule does not require a swap.  This is
10782       // beneficial because the constant in the register is no longer
10783       // destructed as the destination so it can be hoisted out of a loop.
10784       // Only do this pre-AVX since vpcmp* is no longer destructive.
10785       if (Subtarget->hasAVX())
10786         break;
10787       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10788       if (ULEOp1.getNode()) {
10789         Op1 = ULEOp1;
10790         Subus = true; Invert = false; Swap = false;
10791       }
10792       break;
10793     }
10794     // Psubus is better than flip-sign because it requires no inversion.
10795     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10796     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10797     }
10798
10799     if (Subus) {
10800       Opc = X86ISD::SUBUS;
10801       FlipSigns = false;
10802     }
10803   }
10804
10805   if (Swap)
10806     std::swap(Op0, Op1);
10807
10808   // Check that the operation in question is available (most are plain SSE2,
10809   // but PCMPGTQ and PCMPEQQ have different requirements).
10810   if (VT == MVT::v2i64) {
10811     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10812       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10813
10814       // First cast everything to the right type.
10815       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10816       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10817
10818       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10819       // bits of the inputs before performing those operations. The lower
10820       // compare is always unsigned.
10821       SDValue SB;
10822       if (FlipSigns) {
10823         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10824       } else {
10825         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10826         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10827         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10828                          Sign, Zero, Sign, Zero);
10829       }
10830       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10831       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10832
10833       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10834       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10835       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10836
10837       // Create masks for only the low parts/high parts of the 64 bit integers.
10838       static const int MaskHi[] = { 1, 1, 3, 3 };
10839       static const int MaskLo[] = { 0, 0, 2, 2 };
10840       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10841       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10842       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10843
10844       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10845       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10846
10847       if (Invert)
10848         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10849
10850       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10851     }
10852
10853     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10854       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10855       // pcmpeqd + pshufd + pand.
10856       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10857
10858       // First cast everything to the right type.
10859       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10860       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10861
10862       // Do the compare.
10863       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10864
10865       // Make sure the lower and upper halves are both all-ones.
10866       static const int Mask[] = { 1, 0, 3, 2 };
10867       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10868       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10869
10870       if (Invert)
10871         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10872
10873       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10874     }
10875   }
10876
10877   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10878   // bits of the inputs before performing those operations.
10879   if (FlipSigns) {
10880     EVT EltVT = VT.getVectorElementType();
10881     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10882     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10883     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10884   }
10885
10886   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10887
10888   // If the logical-not of the result is required, perform that now.
10889   if (Invert)
10890     Result = DAG.getNOT(dl, Result, VT);
10891
10892   if (MinMax)
10893     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10894
10895   if (Subus)
10896     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10897                          getZeroVector(VT, Subtarget, DAG, dl));
10898
10899   return Result;
10900 }
10901
10902 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10903
10904   MVT VT = Op.getSimpleValueType();
10905
10906   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10907
10908   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10909          && "SetCC type must be 8-bit or 1-bit integer");
10910   SDValue Op0 = Op.getOperand(0);
10911   SDValue Op1 = Op.getOperand(1);
10912   SDLoc dl(Op);
10913   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10914
10915   // Optimize to BT if possible.
10916   // Lower (X & (1 << N)) == 0 to BT(X, N).
10917   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10918   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10919   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10920       Op1.getOpcode() == ISD::Constant &&
10921       cast<ConstantSDNode>(Op1)->isNullValue() &&
10922       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10923     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10924     if (NewSetCC.getNode())
10925       return NewSetCC;
10926   }
10927
10928   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10929   // these.
10930   if (Op1.getOpcode() == ISD::Constant &&
10931       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10932        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10933       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10934
10935     // If the input is a setcc, then reuse the input setcc or use a new one with
10936     // the inverted condition.
10937     if (Op0.getOpcode() == X86ISD::SETCC) {
10938       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10939       bool Invert = (CC == ISD::SETNE) ^
10940         cast<ConstantSDNode>(Op1)->isNullValue();
10941       if (!Invert)
10942         return Op0;
10943
10944       CCode = X86::GetOppositeBranchCondition(CCode);
10945       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10946                                   DAG.getConstant(CCode, MVT::i8),
10947                                   Op0.getOperand(1));
10948       if (VT == MVT::i1)
10949         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10950       return SetCC;
10951     }
10952   }
10953   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10954       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10955       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10956
10957     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10958     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10959   }
10960
10961   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10962   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10963   if (X86CC == X86::COND_INVALID)
10964     return SDValue();
10965
10966   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10967   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10968   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10969                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10970   if (VT == MVT::i1)
10971     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10972   return SetCC;
10973 }
10974
10975 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10976 static bool isX86LogicalCmp(SDValue Op) {
10977   unsigned Opc = Op.getNode()->getOpcode();
10978   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10979       Opc == X86ISD::SAHF)
10980     return true;
10981   if (Op.getResNo() == 1 &&
10982       (Opc == X86ISD::ADD ||
10983        Opc == X86ISD::SUB ||
10984        Opc == X86ISD::ADC ||
10985        Opc == X86ISD::SBB ||
10986        Opc == X86ISD::SMUL ||
10987        Opc == X86ISD::UMUL ||
10988        Opc == X86ISD::INC ||
10989        Opc == X86ISD::DEC ||
10990        Opc == X86ISD::OR ||
10991        Opc == X86ISD::XOR ||
10992        Opc == X86ISD::AND))
10993     return true;
10994
10995   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10996     return true;
10997
10998   return false;
10999 }
11000
11001 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11002   if (V.getOpcode() != ISD::TRUNCATE)
11003     return false;
11004
11005   SDValue VOp0 = V.getOperand(0);
11006   unsigned InBits = VOp0.getValueSizeInBits();
11007   unsigned Bits = V.getValueSizeInBits();
11008   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11009 }
11010
11011 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11012   bool addTest = true;
11013   SDValue Cond  = Op.getOperand(0);
11014   SDValue Op1 = Op.getOperand(1);
11015   SDValue Op2 = Op.getOperand(2);
11016   SDLoc DL(Op);
11017   EVT VT = Op1.getValueType();
11018   SDValue CC;
11019
11020   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11021   // are available. Otherwise fp cmovs get lowered into a less efficient branch
11022   // sequence later on.
11023   if (Cond.getOpcode() == ISD::SETCC &&
11024       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11025        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11026       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11027     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11028     int SSECC = translateX86FSETCC(
11029         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11030
11031     if (SSECC != 8) {
11032       if (Subtarget->hasAVX512()) {
11033         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11034                                   DAG.getConstant(SSECC, MVT::i8));
11035         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11036       }
11037       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11038                                 DAG.getConstant(SSECC, MVT::i8));
11039       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11040       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11041       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11042     }
11043   }
11044
11045   if (Cond.getOpcode() == ISD::SETCC) {
11046     SDValue NewCond = LowerSETCC(Cond, DAG);
11047     if (NewCond.getNode())
11048       Cond = NewCond;
11049   }
11050
11051   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11052   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11053   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11054   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11055   if (Cond.getOpcode() == X86ISD::SETCC &&
11056       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11057       isZero(Cond.getOperand(1).getOperand(1))) {
11058     SDValue Cmp = Cond.getOperand(1);
11059
11060     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11061
11062     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11063         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11064       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11065
11066       SDValue CmpOp0 = Cmp.getOperand(0);
11067       // Apply further optimizations for special cases
11068       // (select (x != 0), -1, 0) -> neg & sbb
11069       // (select (x == 0), 0, -1) -> neg & sbb
11070       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11071         if (YC->isNullValue() &&
11072             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11073           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11074           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11075                                     DAG.getConstant(0, CmpOp0.getValueType()),
11076                                     CmpOp0);
11077           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11078                                     DAG.getConstant(X86::COND_B, MVT::i8),
11079                                     SDValue(Neg.getNode(), 1));
11080           return Res;
11081         }
11082
11083       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11084                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11085       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11086
11087       SDValue Res =   // Res = 0 or -1.
11088         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11089                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11090
11091       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11092         Res = DAG.getNOT(DL, Res, Res.getValueType());
11093
11094       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11095       if (!N2C || !N2C->isNullValue())
11096         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11097       return Res;
11098     }
11099   }
11100
11101   // Look past (and (setcc_carry (cmp ...)), 1).
11102   if (Cond.getOpcode() == ISD::AND &&
11103       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11104     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11105     if (C && C->getAPIntValue() == 1)
11106       Cond = Cond.getOperand(0);
11107   }
11108
11109   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11110   // setting operand in place of the X86ISD::SETCC.
11111   unsigned CondOpcode = Cond.getOpcode();
11112   if (CondOpcode == X86ISD::SETCC ||
11113       CondOpcode == X86ISD::SETCC_CARRY) {
11114     CC = Cond.getOperand(0);
11115
11116     SDValue Cmp = Cond.getOperand(1);
11117     unsigned Opc = Cmp.getOpcode();
11118     MVT VT = Op.getSimpleValueType();
11119
11120     bool IllegalFPCMov = false;
11121     if (VT.isFloatingPoint() && !VT.isVector() &&
11122         !isScalarFPTypeInSSEReg(VT))  // FPStack?
11123       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11124
11125     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11126         Opc == X86ISD::BT) { // FIXME
11127       Cond = Cmp;
11128       addTest = false;
11129     }
11130   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11131              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11132              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11133               Cond.getOperand(0).getValueType() != MVT::i8)) {
11134     SDValue LHS = Cond.getOperand(0);
11135     SDValue RHS = Cond.getOperand(1);
11136     unsigned X86Opcode;
11137     unsigned X86Cond;
11138     SDVTList VTs;
11139     switch (CondOpcode) {
11140     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11141     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11142     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11143     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11144     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11145     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11146     default: llvm_unreachable("unexpected overflowing operator");
11147     }
11148     if (CondOpcode == ISD::UMULO)
11149       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11150                           MVT::i32);
11151     else
11152       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11153
11154     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11155
11156     if (CondOpcode == ISD::UMULO)
11157       Cond = X86Op.getValue(2);
11158     else
11159       Cond = X86Op.getValue(1);
11160
11161     CC = DAG.getConstant(X86Cond, MVT::i8);
11162     addTest = false;
11163   }
11164
11165   if (addTest) {
11166     // Look pass the truncate if the high bits are known zero.
11167     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11168         Cond = Cond.getOperand(0);
11169
11170     // We know the result of AND is compared against zero. Try to match
11171     // it to BT.
11172     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11173       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11174       if (NewSetCC.getNode()) {
11175         CC = NewSetCC.getOperand(0);
11176         Cond = NewSetCC.getOperand(1);
11177         addTest = false;
11178       }
11179     }
11180   }
11181
11182   if (addTest) {
11183     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11184     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11185   }
11186
11187   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11188   // a <  b ?  0 : -1 -> RES = setcc_carry
11189   // a >= b ? -1 :  0 -> RES = setcc_carry
11190   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11191   if (Cond.getOpcode() == X86ISD::SUB) {
11192     Cond = ConvertCmpIfNecessary(Cond, DAG);
11193     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11194
11195     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11196         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11197       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11198                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11199       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11200         return DAG.getNOT(DL, Res, Res.getValueType());
11201       return Res;
11202     }
11203   }
11204
11205   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11206   // widen the cmov and push the truncate through. This avoids introducing a new
11207   // branch during isel and doesn't add any extensions.
11208   if (Op.getValueType() == MVT::i8 &&
11209       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11210     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11211     if (T1.getValueType() == T2.getValueType() &&
11212         // Blacklist CopyFromReg to avoid partial register stalls.
11213         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11214       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11215       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11216       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11217     }
11218   }
11219
11220   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11221   // condition is true.
11222   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11223   SDValue Ops[] = { Op2, Op1, CC, Cond };
11224   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11225 }
11226
11227 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11228   MVT VT = Op->getSimpleValueType(0);
11229   SDValue In = Op->getOperand(0);
11230   MVT InVT = In.getSimpleValueType();
11231   SDLoc dl(Op);
11232
11233   unsigned int NumElts = VT.getVectorNumElements();
11234   if (NumElts != 8 && NumElts != 16)
11235     return SDValue();
11236
11237   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11238     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11239
11240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11241   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11242
11243   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11244   Constant *C = ConstantInt::get(*DAG.getContext(),
11245     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11246
11247   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11248   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11249   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11250                           MachinePointerInfo::getConstantPool(),
11251                           false, false, false, Alignment);
11252   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11253   if (VT.is512BitVector())
11254     return Brcst;
11255   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11256 }
11257
11258 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11259                                 SelectionDAG &DAG) {
11260   MVT VT = Op->getSimpleValueType(0);
11261   SDValue In = Op->getOperand(0);
11262   MVT InVT = In.getSimpleValueType();
11263   SDLoc dl(Op);
11264
11265   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11266     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11267
11268   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11269       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11270       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11271     return SDValue();
11272
11273   if (Subtarget->hasInt256())
11274     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11275
11276   // Optimize vectors in AVX mode
11277   // Sign extend  v8i16 to v8i32 and
11278   //              v4i32 to v4i64
11279   //
11280   // Divide input vector into two parts
11281   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11282   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11283   // concat the vectors to original VT
11284
11285   unsigned NumElems = InVT.getVectorNumElements();
11286   SDValue Undef = DAG.getUNDEF(InVT);
11287
11288   SmallVector<int,8> ShufMask1(NumElems, -1);
11289   for (unsigned i = 0; i != NumElems/2; ++i)
11290     ShufMask1[i] = i;
11291
11292   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11293
11294   SmallVector<int,8> ShufMask2(NumElems, -1);
11295   for (unsigned i = 0; i != NumElems/2; ++i)
11296     ShufMask2[i] = i + NumElems/2;
11297
11298   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11299
11300   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11301                                 VT.getVectorNumElements()/2);
11302
11303   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11304   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11305
11306   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11307 }
11308
11309 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11310 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11311 // from the AND / OR.
11312 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11313   Opc = Op.getOpcode();
11314   if (Opc != ISD::OR && Opc != ISD::AND)
11315     return false;
11316   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11317           Op.getOperand(0).hasOneUse() &&
11318           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11319           Op.getOperand(1).hasOneUse());
11320 }
11321
11322 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11323 // 1 and that the SETCC node has a single use.
11324 static bool isXor1OfSetCC(SDValue Op) {
11325   if (Op.getOpcode() != ISD::XOR)
11326     return false;
11327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11328   if (N1C && N1C->getAPIntValue() == 1) {
11329     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11330       Op.getOperand(0).hasOneUse();
11331   }
11332   return false;
11333 }
11334
11335 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11336   bool addTest = true;
11337   SDValue Chain = Op.getOperand(0);
11338   SDValue Cond  = Op.getOperand(1);
11339   SDValue Dest  = Op.getOperand(2);
11340   SDLoc dl(Op);
11341   SDValue CC;
11342   bool Inverted = false;
11343
11344   if (Cond.getOpcode() == ISD::SETCC) {
11345     // Check for setcc([su]{add,sub,mul}o == 0).
11346     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11347         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11348         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11349         Cond.getOperand(0).getResNo() == 1 &&
11350         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11351          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11352          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11353          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11354          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11355          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11356       Inverted = true;
11357       Cond = Cond.getOperand(0);
11358     } else {
11359       SDValue NewCond = LowerSETCC(Cond, DAG);
11360       if (NewCond.getNode())
11361         Cond = NewCond;
11362     }
11363   }
11364 #if 0
11365   // FIXME: LowerXALUO doesn't handle these!!
11366   else if (Cond.getOpcode() == X86ISD::ADD  ||
11367            Cond.getOpcode() == X86ISD::SUB  ||
11368            Cond.getOpcode() == X86ISD::SMUL ||
11369            Cond.getOpcode() == X86ISD::UMUL)
11370     Cond = LowerXALUO(Cond, DAG);
11371 #endif
11372
11373   // Look pass (and (setcc_carry (cmp ...)), 1).
11374   if (Cond.getOpcode() == ISD::AND &&
11375       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11376     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11377     if (C && C->getAPIntValue() == 1)
11378       Cond = Cond.getOperand(0);
11379   }
11380
11381   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11382   // setting operand in place of the X86ISD::SETCC.
11383   unsigned CondOpcode = Cond.getOpcode();
11384   if (CondOpcode == X86ISD::SETCC ||
11385       CondOpcode == X86ISD::SETCC_CARRY) {
11386     CC = Cond.getOperand(0);
11387
11388     SDValue Cmp = Cond.getOperand(1);
11389     unsigned Opc = Cmp.getOpcode();
11390     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11391     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11392       Cond = Cmp;
11393       addTest = false;
11394     } else {
11395       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11396       default: break;
11397       case X86::COND_O:
11398       case X86::COND_B:
11399         // These can only come from an arithmetic instruction with overflow,
11400         // e.g. SADDO, UADDO.
11401         Cond = Cond.getNode()->getOperand(1);
11402         addTest = false;
11403         break;
11404       }
11405     }
11406   }
11407   CondOpcode = Cond.getOpcode();
11408   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11409       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11410       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11411        Cond.getOperand(0).getValueType() != MVT::i8)) {
11412     SDValue LHS = Cond.getOperand(0);
11413     SDValue RHS = Cond.getOperand(1);
11414     unsigned X86Opcode;
11415     unsigned X86Cond;
11416     SDVTList VTs;
11417     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11418     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11419     // X86ISD::INC).
11420     switch (CondOpcode) {
11421     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11422     case ISD::SADDO:
11423       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11424         if (C->isOne()) {
11425           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11426           break;
11427         }
11428       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11429     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11430     case ISD::SSUBO:
11431       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11432         if (C->isOne()) {
11433           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11434           break;
11435         }
11436       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11437     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11438     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11439     default: llvm_unreachable("unexpected overflowing operator");
11440     }
11441     if (Inverted)
11442       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11443     if (CondOpcode == ISD::UMULO)
11444       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11445                           MVT::i32);
11446     else
11447       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11448
11449     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11450
11451     if (CondOpcode == ISD::UMULO)
11452       Cond = X86Op.getValue(2);
11453     else
11454       Cond = X86Op.getValue(1);
11455
11456     CC = DAG.getConstant(X86Cond, MVT::i8);
11457     addTest = false;
11458   } else {
11459     unsigned CondOpc;
11460     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11461       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11462       if (CondOpc == ISD::OR) {
11463         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11464         // two branches instead of an explicit OR instruction with a
11465         // separate test.
11466         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11467             isX86LogicalCmp(Cmp)) {
11468           CC = Cond.getOperand(0).getOperand(0);
11469           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11470                               Chain, Dest, CC, Cmp);
11471           CC = Cond.getOperand(1).getOperand(0);
11472           Cond = Cmp;
11473           addTest = false;
11474         }
11475       } else { // ISD::AND
11476         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11477         // two branches instead of an explicit AND instruction with a
11478         // separate test. However, we only do this if this block doesn't
11479         // have a fall-through edge, because this requires an explicit
11480         // jmp when the condition is false.
11481         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11482             isX86LogicalCmp(Cmp) &&
11483             Op.getNode()->hasOneUse()) {
11484           X86::CondCode CCode =
11485             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11486           CCode = X86::GetOppositeBranchCondition(CCode);
11487           CC = DAG.getConstant(CCode, MVT::i8);
11488           SDNode *User = *Op.getNode()->use_begin();
11489           // Look for an unconditional branch following this conditional branch.
11490           // We need this because we need to reverse the successors in order
11491           // to implement FCMP_OEQ.
11492           if (User->getOpcode() == ISD::BR) {
11493             SDValue FalseBB = User->getOperand(1);
11494             SDNode *NewBR =
11495               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11496             assert(NewBR == User);
11497             (void)NewBR;
11498             Dest = FalseBB;
11499
11500             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11501                                 Chain, Dest, CC, Cmp);
11502             X86::CondCode CCode =
11503               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11504             CCode = X86::GetOppositeBranchCondition(CCode);
11505             CC = DAG.getConstant(CCode, MVT::i8);
11506             Cond = Cmp;
11507             addTest = false;
11508           }
11509         }
11510       }
11511     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11512       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11513       // It should be transformed during dag combiner except when the condition
11514       // is set by a arithmetics with overflow node.
11515       X86::CondCode CCode =
11516         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11517       CCode = X86::GetOppositeBranchCondition(CCode);
11518       CC = DAG.getConstant(CCode, MVT::i8);
11519       Cond = Cond.getOperand(0).getOperand(1);
11520       addTest = false;
11521     } else if (Cond.getOpcode() == ISD::SETCC &&
11522                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11523       // For FCMP_OEQ, we can emit
11524       // two branches instead of an explicit AND instruction with a
11525       // separate test. However, we only do this if this block doesn't
11526       // have a fall-through edge, because this requires an explicit
11527       // jmp when the condition is false.
11528       if (Op.getNode()->hasOneUse()) {
11529         SDNode *User = *Op.getNode()->use_begin();
11530         // Look for an unconditional branch following this conditional branch.
11531         // We need this because we need to reverse the successors in order
11532         // to implement FCMP_OEQ.
11533         if (User->getOpcode() == ISD::BR) {
11534           SDValue FalseBB = User->getOperand(1);
11535           SDNode *NewBR =
11536             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11537           assert(NewBR == User);
11538           (void)NewBR;
11539           Dest = FalseBB;
11540
11541           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11542                                     Cond.getOperand(0), Cond.getOperand(1));
11543           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11544           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11545           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11546                               Chain, Dest, CC, Cmp);
11547           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11548           Cond = Cmp;
11549           addTest = false;
11550         }
11551       }
11552     } else if (Cond.getOpcode() == ISD::SETCC &&
11553                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11554       // For FCMP_UNE, we can emit
11555       // two branches instead of an explicit AND instruction with a
11556       // separate test. However, we only do this if this block doesn't
11557       // have a fall-through edge, because this requires an explicit
11558       // jmp when the condition is false.
11559       if (Op.getNode()->hasOneUse()) {
11560         SDNode *User = *Op.getNode()->use_begin();
11561         // Look for an unconditional branch following this conditional branch.
11562         // We need this because we need to reverse the successors in order
11563         // to implement FCMP_UNE.
11564         if (User->getOpcode() == ISD::BR) {
11565           SDValue FalseBB = User->getOperand(1);
11566           SDNode *NewBR =
11567             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11568           assert(NewBR == User);
11569           (void)NewBR;
11570
11571           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11572                                     Cond.getOperand(0), Cond.getOperand(1));
11573           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11574           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11575           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11576                               Chain, Dest, CC, Cmp);
11577           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11578           Cond = Cmp;
11579           addTest = false;
11580           Dest = FalseBB;
11581         }
11582       }
11583     }
11584   }
11585
11586   if (addTest) {
11587     // Look pass the truncate if the high bits are known zero.
11588     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11589         Cond = Cond.getOperand(0);
11590
11591     // We know the result of AND is compared against zero. Try to match
11592     // it to BT.
11593     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11594       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11595       if (NewSetCC.getNode()) {
11596         CC = NewSetCC.getOperand(0);
11597         Cond = NewSetCC.getOperand(1);
11598         addTest = false;
11599       }
11600     }
11601   }
11602
11603   if (addTest) {
11604     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11605     CC = DAG.getConstant(X86Cond, MVT::i8);
11606     Cond = EmitTest(Cond, X86Cond, dl, DAG);
11607   }
11608   Cond = ConvertCmpIfNecessary(Cond, DAG);
11609   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11610                      Chain, Dest, CC, Cond);
11611 }
11612
11613 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11614 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11615 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11616 // that the guard pages used by the OS virtual memory manager are allocated in
11617 // correct sequence.
11618 SDValue
11619 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11620                                            SelectionDAG &DAG) const {
11621   MachineFunction &MF = DAG.getMachineFunction();
11622   bool SplitStack = MF.shouldSplitStack();
11623   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11624                SplitStack;
11625   SDLoc dl(Op);
11626
11627   if (!Lower) {
11628     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11629     SDNode* Node = Op.getNode();
11630
11631     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11632     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11633         " not tell us which reg is the stack pointer!");
11634     EVT VT = Node->getValueType(0);
11635     SDValue Tmp1 = SDValue(Node, 0);
11636     SDValue Tmp2 = SDValue(Node, 1);
11637     SDValue Tmp3 = Node->getOperand(2);
11638     SDValue Chain = Tmp1.getOperand(0);
11639
11640     // Chain the dynamic stack allocation so that it doesn't modify the stack
11641     // pointer when other instructions are using the stack.
11642     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11643         SDLoc(Node));
11644
11645     SDValue Size = Tmp2.getOperand(1);
11646     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11647     Chain = SP.getValue(1);
11648     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11649     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11650     unsigned StackAlign = TFI.getStackAlignment();
11651     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11652     if (Align > StackAlign)
11653       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11654           DAG.getConstant(-(uint64_t)Align, VT));
11655     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11656
11657     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11658         DAG.getIntPtrConstant(0, true), SDValue(),
11659         SDLoc(Node));
11660
11661     SDValue Ops[2] = { Tmp1, Tmp2 };
11662     return DAG.getMergeValues(Ops, dl);
11663   }
11664
11665   // Get the inputs.
11666   SDValue Chain = Op.getOperand(0);
11667   SDValue Size  = Op.getOperand(1);
11668   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11669   EVT VT = Op.getNode()->getValueType(0);
11670
11671   bool Is64Bit = Subtarget->is64Bit();
11672   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11673
11674   if (SplitStack) {
11675     MachineRegisterInfo &MRI = MF.getRegInfo();
11676
11677     if (Is64Bit) {
11678       // The 64 bit implementation of segmented stacks needs to clobber both r10
11679       // r11. This makes it impossible to use it along with nested parameters.
11680       const Function *F = MF.getFunction();
11681
11682       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11683            I != E; ++I)
11684         if (I->hasNestAttr())
11685           report_fatal_error("Cannot use segmented stacks with functions that "
11686                              "have nested arguments.");
11687     }
11688
11689     const TargetRegisterClass *AddrRegClass =
11690       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11691     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11692     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11693     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11694                                 DAG.getRegister(Vreg, SPTy));
11695     SDValue Ops1[2] = { Value, Chain };
11696     return DAG.getMergeValues(Ops1, dl);
11697   } else {
11698     SDValue Flag;
11699     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11700
11701     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11702     Flag = Chain.getValue(1);
11703     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11704
11705     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11706
11707     const X86RegisterInfo *RegInfo =
11708       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11709     unsigned SPReg = RegInfo->getStackRegister();
11710     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11711     Chain = SP.getValue(1);
11712
11713     if (Align) {
11714       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11715                        DAG.getConstant(-(uint64_t)Align, VT));
11716       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11717     }
11718
11719     SDValue Ops1[2] = { SP, Chain };
11720     return DAG.getMergeValues(Ops1, dl);
11721   }
11722 }
11723
11724 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11725   MachineFunction &MF = DAG.getMachineFunction();
11726   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11727
11728   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11729   SDLoc DL(Op);
11730
11731   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11732     // vastart just stores the address of the VarArgsFrameIndex slot into the
11733     // memory location argument.
11734     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11735                                    getPointerTy());
11736     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11737                         MachinePointerInfo(SV), false, false, 0);
11738   }
11739
11740   // __va_list_tag:
11741   //   gp_offset         (0 - 6 * 8)
11742   //   fp_offset         (48 - 48 + 8 * 16)
11743   //   overflow_arg_area (point to parameters coming in memory).
11744   //   reg_save_area
11745   SmallVector<SDValue, 8> MemOps;
11746   SDValue FIN = Op.getOperand(1);
11747   // Store gp_offset
11748   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11749                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11750                                                MVT::i32),
11751                                FIN, MachinePointerInfo(SV), false, false, 0);
11752   MemOps.push_back(Store);
11753
11754   // Store fp_offset
11755   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11756                     FIN, DAG.getIntPtrConstant(4));
11757   Store = DAG.getStore(Op.getOperand(0), DL,
11758                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11759                                        MVT::i32),
11760                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11761   MemOps.push_back(Store);
11762
11763   // Store ptr to overflow_arg_area
11764   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11765                     FIN, DAG.getIntPtrConstant(4));
11766   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11767                                     getPointerTy());
11768   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11769                        MachinePointerInfo(SV, 8),
11770                        false, false, 0);
11771   MemOps.push_back(Store);
11772
11773   // Store ptr to reg_save_area.
11774   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11775                     FIN, DAG.getIntPtrConstant(8));
11776   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11777                                     getPointerTy());
11778   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11779                        MachinePointerInfo(SV, 16), false, false, 0);
11780   MemOps.push_back(Store);
11781   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11782 }
11783
11784 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11785   assert(Subtarget->is64Bit() &&
11786          "LowerVAARG only handles 64-bit va_arg!");
11787   assert((Subtarget->isTargetLinux() ||
11788           Subtarget->isTargetDarwin()) &&
11789           "Unhandled target in LowerVAARG");
11790   assert(Op.getNode()->getNumOperands() == 4);
11791   SDValue Chain = Op.getOperand(0);
11792   SDValue SrcPtr = Op.getOperand(1);
11793   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11794   unsigned Align = Op.getConstantOperandVal(3);
11795   SDLoc dl(Op);
11796
11797   EVT ArgVT = Op.getNode()->getValueType(0);
11798   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11799   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11800   uint8_t ArgMode;
11801
11802   // Decide which area this value should be read from.
11803   // TODO: Implement the AMD64 ABI in its entirety. This simple
11804   // selection mechanism works only for the basic types.
11805   if (ArgVT == MVT::f80) {
11806     llvm_unreachable("va_arg for f80 not yet implemented");
11807   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11808     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11809   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11810     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11811   } else {
11812     llvm_unreachable("Unhandled argument type in LowerVAARG");
11813   }
11814
11815   if (ArgMode == 2) {
11816     // Sanity Check: Make sure using fp_offset makes sense.
11817     assert(!getTargetMachine().Options.UseSoftFloat &&
11818            !(DAG.getMachineFunction()
11819                 .getFunction()->getAttributes()
11820                 .hasAttribute(AttributeSet::FunctionIndex,
11821                               Attribute::NoImplicitFloat)) &&
11822            Subtarget->hasSSE1());
11823   }
11824
11825   // Insert VAARG_64 node into the DAG
11826   // VAARG_64 returns two values: Variable Argument Address, Chain
11827   SmallVector<SDValue, 11> InstOps;
11828   InstOps.push_back(Chain);
11829   InstOps.push_back(SrcPtr);
11830   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11831   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11832   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11833   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11834   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11835                                           VTs, InstOps, MVT::i64,
11836                                           MachinePointerInfo(SV),
11837                                           /*Align=*/0,
11838                                           /*Volatile=*/false,
11839                                           /*ReadMem=*/true,
11840                                           /*WriteMem=*/true);
11841   Chain = VAARG.getValue(1);
11842
11843   // Load the next argument and return it
11844   return DAG.getLoad(ArgVT, dl,
11845                      Chain,
11846                      VAARG,
11847                      MachinePointerInfo(),
11848                      false, false, false, 0);
11849 }
11850
11851 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11852                            SelectionDAG &DAG) {
11853   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11854   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11855   SDValue Chain = Op.getOperand(0);
11856   SDValue DstPtr = Op.getOperand(1);
11857   SDValue SrcPtr = Op.getOperand(2);
11858   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11859   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11860   SDLoc DL(Op);
11861
11862   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11863                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11864                        false,
11865                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11866 }
11867
11868 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11869 // amount is a constant. Takes immediate version of shift as input.
11870 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11871                                           SDValue SrcOp, uint64_t ShiftAmt,
11872                                           SelectionDAG &DAG) {
11873   MVT ElementType = VT.getVectorElementType();
11874
11875   // Fold this packed shift into its first operand if ShiftAmt is 0.
11876   if (ShiftAmt == 0)
11877     return SrcOp;
11878
11879   // Check for ShiftAmt >= element width
11880   if (ShiftAmt >= ElementType.getSizeInBits()) {
11881     if (Opc == X86ISD::VSRAI)
11882       ShiftAmt = ElementType.getSizeInBits() - 1;
11883     else
11884       return DAG.getConstant(0, VT);
11885   }
11886
11887   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11888          && "Unknown target vector shift-by-constant node");
11889
11890   // Fold this packed vector shift into a build vector if SrcOp is a
11891   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11892   if (VT == SrcOp.getSimpleValueType() &&
11893       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11894     SmallVector<SDValue, 8> Elts;
11895     unsigned NumElts = SrcOp->getNumOperands();
11896     ConstantSDNode *ND;
11897
11898     switch(Opc) {
11899     default: llvm_unreachable(nullptr);
11900     case X86ISD::VSHLI:
11901       for (unsigned i=0; i!=NumElts; ++i) {
11902         SDValue CurrentOp = SrcOp->getOperand(i);
11903         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11904           Elts.push_back(CurrentOp);
11905           continue;
11906         }
11907         ND = cast<ConstantSDNode>(CurrentOp);
11908         const APInt &C = ND->getAPIntValue();
11909         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11910       }
11911       break;
11912     case X86ISD::VSRLI:
11913       for (unsigned i=0; i!=NumElts; ++i) {
11914         SDValue CurrentOp = SrcOp->getOperand(i);
11915         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11916           Elts.push_back(CurrentOp);
11917           continue;
11918         }
11919         ND = cast<ConstantSDNode>(CurrentOp);
11920         const APInt &C = ND->getAPIntValue();
11921         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11922       }
11923       break;
11924     case X86ISD::VSRAI:
11925       for (unsigned i=0; i!=NumElts; ++i) {
11926         SDValue CurrentOp = SrcOp->getOperand(i);
11927         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11928           Elts.push_back(CurrentOp);
11929           continue;
11930         }
11931         ND = cast<ConstantSDNode>(CurrentOp);
11932         const APInt &C = ND->getAPIntValue();
11933         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11934       }
11935       break;
11936     }
11937
11938     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11939   }
11940
11941   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11942 }
11943
11944 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11945 // may or may not be a constant. Takes immediate version of shift as input.
11946 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11947                                    SDValue SrcOp, SDValue ShAmt,
11948                                    SelectionDAG &DAG) {
11949   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11950
11951   // Catch shift-by-constant.
11952   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11953     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11954                                       CShAmt->getZExtValue(), DAG);
11955
11956   // Change opcode to non-immediate version
11957   switch (Opc) {
11958     default: llvm_unreachable("Unknown target vector shift node");
11959     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11960     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11961     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11962   }
11963
11964   // Need to build a vector containing shift amount
11965   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11966   SDValue ShOps[4];
11967   ShOps[0] = ShAmt;
11968   ShOps[1] = DAG.getConstant(0, MVT::i32);
11969   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11970   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11971
11972   // The return type has to be a 128-bit type with the same element
11973   // type as the input type.
11974   MVT EltVT = VT.getVectorElementType();
11975   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11976
11977   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11978   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11979 }
11980
11981 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11982   SDLoc dl(Op);
11983   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11984   switch (IntNo) {
11985   default: return SDValue();    // Don't custom lower most intrinsics.
11986   // Comparison intrinsics.
11987   case Intrinsic::x86_sse_comieq_ss:
11988   case Intrinsic::x86_sse_comilt_ss:
11989   case Intrinsic::x86_sse_comile_ss:
11990   case Intrinsic::x86_sse_comigt_ss:
11991   case Intrinsic::x86_sse_comige_ss:
11992   case Intrinsic::x86_sse_comineq_ss:
11993   case Intrinsic::x86_sse_ucomieq_ss:
11994   case Intrinsic::x86_sse_ucomilt_ss:
11995   case Intrinsic::x86_sse_ucomile_ss:
11996   case Intrinsic::x86_sse_ucomigt_ss:
11997   case Intrinsic::x86_sse_ucomige_ss:
11998   case Intrinsic::x86_sse_ucomineq_ss:
11999   case Intrinsic::x86_sse2_comieq_sd:
12000   case Intrinsic::x86_sse2_comilt_sd:
12001   case Intrinsic::x86_sse2_comile_sd:
12002   case Intrinsic::x86_sse2_comigt_sd:
12003   case Intrinsic::x86_sse2_comige_sd:
12004   case Intrinsic::x86_sse2_comineq_sd:
12005   case Intrinsic::x86_sse2_ucomieq_sd:
12006   case Intrinsic::x86_sse2_ucomilt_sd:
12007   case Intrinsic::x86_sse2_ucomile_sd:
12008   case Intrinsic::x86_sse2_ucomigt_sd:
12009   case Intrinsic::x86_sse2_ucomige_sd:
12010   case Intrinsic::x86_sse2_ucomineq_sd: {
12011     unsigned Opc;
12012     ISD::CondCode CC;
12013     switch (IntNo) {
12014     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12015     case Intrinsic::x86_sse_comieq_ss:
12016     case Intrinsic::x86_sse2_comieq_sd:
12017       Opc = X86ISD::COMI;
12018       CC = ISD::SETEQ;
12019       break;
12020     case Intrinsic::x86_sse_comilt_ss:
12021     case Intrinsic::x86_sse2_comilt_sd:
12022       Opc = X86ISD::COMI;
12023       CC = ISD::SETLT;
12024       break;
12025     case Intrinsic::x86_sse_comile_ss:
12026     case Intrinsic::x86_sse2_comile_sd:
12027       Opc = X86ISD::COMI;
12028       CC = ISD::SETLE;
12029       break;
12030     case Intrinsic::x86_sse_comigt_ss:
12031     case Intrinsic::x86_sse2_comigt_sd:
12032       Opc = X86ISD::COMI;
12033       CC = ISD::SETGT;
12034       break;
12035     case Intrinsic::x86_sse_comige_ss:
12036     case Intrinsic::x86_sse2_comige_sd:
12037       Opc = X86ISD::COMI;
12038       CC = ISD::SETGE;
12039       break;
12040     case Intrinsic::x86_sse_comineq_ss:
12041     case Intrinsic::x86_sse2_comineq_sd:
12042       Opc = X86ISD::COMI;
12043       CC = ISD::SETNE;
12044       break;
12045     case Intrinsic::x86_sse_ucomieq_ss:
12046     case Intrinsic::x86_sse2_ucomieq_sd:
12047       Opc = X86ISD::UCOMI;
12048       CC = ISD::SETEQ;
12049       break;
12050     case Intrinsic::x86_sse_ucomilt_ss:
12051     case Intrinsic::x86_sse2_ucomilt_sd:
12052       Opc = X86ISD::UCOMI;
12053       CC = ISD::SETLT;
12054       break;
12055     case Intrinsic::x86_sse_ucomile_ss:
12056     case Intrinsic::x86_sse2_ucomile_sd:
12057       Opc = X86ISD::UCOMI;
12058       CC = ISD::SETLE;
12059       break;
12060     case Intrinsic::x86_sse_ucomigt_ss:
12061     case Intrinsic::x86_sse2_ucomigt_sd:
12062       Opc = X86ISD::UCOMI;
12063       CC = ISD::SETGT;
12064       break;
12065     case Intrinsic::x86_sse_ucomige_ss:
12066     case Intrinsic::x86_sse2_ucomige_sd:
12067       Opc = X86ISD::UCOMI;
12068       CC = ISD::SETGE;
12069       break;
12070     case Intrinsic::x86_sse_ucomineq_ss:
12071     case Intrinsic::x86_sse2_ucomineq_sd:
12072       Opc = X86ISD::UCOMI;
12073       CC = ISD::SETNE;
12074       break;
12075     }
12076
12077     SDValue LHS = Op.getOperand(1);
12078     SDValue RHS = Op.getOperand(2);
12079     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12080     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12081     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12082     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12083                                 DAG.getConstant(X86CC, MVT::i8), Cond);
12084     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12085   }
12086
12087   // Arithmetic intrinsics.
12088   case Intrinsic::x86_sse2_pmulu_dq:
12089   case Intrinsic::x86_avx2_pmulu_dq:
12090     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12091                        Op.getOperand(1), Op.getOperand(2));
12092
12093   case Intrinsic::x86_sse41_pmuldq:
12094   case Intrinsic::x86_avx2_pmul_dq:
12095     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12096                        Op.getOperand(1), Op.getOperand(2));
12097
12098   case Intrinsic::x86_sse2_pmulhu_w:
12099   case Intrinsic::x86_avx2_pmulhu_w:
12100     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12101                        Op.getOperand(1), Op.getOperand(2));
12102
12103   case Intrinsic::x86_sse2_pmulh_w:
12104   case Intrinsic::x86_avx2_pmulh_w:
12105     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12106                        Op.getOperand(1), Op.getOperand(2));
12107
12108   // SSE2/AVX2 sub with unsigned saturation intrinsics
12109   case Intrinsic::x86_sse2_psubus_b:
12110   case Intrinsic::x86_sse2_psubus_w:
12111   case Intrinsic::x86_avx2_psubus_b:
12112   case Intrinsic::x86_avx2_psubus_w:
12113     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12114                        Op.getOperand(1), Op.getOperand(2));
12115
12116   // SSE3/AVX horizontal add/sub intrinsics
12117   case Intrinsic::x86_sse3_hadd_ps:
12118   case Intrinsic::x86_sse3_hadd_pd:
12119   case Intrinsic::x86_avx_hadd_ps_256:
12120   case Intrinsic::x86_avx_hadd_pd_256:
12121   case Intrinsic::x86_sse3_hsub_ps:
12122   case Intrinsic::x86_sse3_hsub_pd:
12123   case Intrinsic::x86_avx_hsub_ps_256:
12124   case Intrinsic::x86_avx_hsub_pd_256:
12125   case Intrinsic::x86_ssse3_phadd_w_128:
12126   case Intrinsic::x86_ssse3_phadd_d_128:
12127   case Intrinsic::x86_avx2_phadd_w:
12128   case Intrinsic::x86_avx2_phadd_d:
12129   case Intrinsic::x86_ssse3_phsub_w_128:
12130   case Intrinsic::x86_ssse3_phsub_d_128:
12131   case Intrinsic::x86_avx2_phsub_w:
12132   case Intrinsic::x86_avx2_phsub_d: {
12133     unsigned Opcode;
12134     switch (IntNo) {
12135     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12136     case Intrinsic::x86_sse3_hadd_ps:
12137     case Intrinsic::x86_sse3_hadd_pd:
12138     case Intrinsic::x86_avx_hadd_ps_256:
12139     case Intrinsic::x86_avx_hadd_pd_256:
12140       Opcode = X86ISD::FHADD;
12141       break;
12142     case Intrinsic::x86_sse3_hsub_ps:
12143     case Intrinsic::x86_sse3_hsub_pd:
12144     case Intrinsic::x86_avx_hsub_ps_256:
12145     case Intrinsic::x86_avx_hsub_pd_256:
12146       Opcode = X86ISD::FHSUB;
12147       break;
12148     case Intrinsic::x86_ssse3_phadd_w_128:
12149     case Intrinsic::x86_ssse3_phadd_d_128:
12150     case Intrinsic::x86_avx2_phadd_w:
12151     case Intrinsic::x86_avx2_phadd_d:
12152       Opcode = X86ISD::HADD;
12153       break;
12154     case Intrinsic::x86_ssse3_phsub_w_128:
12155     case Intrinsic::x86_ssse3_phsub_d_128:
12156     case Intrinsic::x86_avx2_phsub_w:
12157     case Intrinsic::x86_avx2_phsub_d:
12158       Opcode = X86ISD::HSUB;
12159       break;
12160     }
12161     return DAG.getNode(Opcode, dl, Op.getValueType(),
12162                        Op.getOperand(1), Op.getOperand(2));
12163   }
12164
12165   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12166   case Intrinsic::x86_sse2_pmaxu_b:
12167   case Intrinsic::x86_sse41_pmaxuw:
12168   case Intrinsic::x86_sse41_pmaxud:
12169   case Intrinsic::x86_avx2_pmaxu_b:
12170   case Intrinsic::x86_avx2_pmaxu_w:
12171   case Intrinsic::x86_avx2_pmaxu_d:
12172   case Intrinsic::x86_sse2_pminu_b:
12173   case Intrinsic::x86_sse41_pminuw:
12174   case Intrinsic::x86_sse41_pminud:
12175   case Intrinsic::x86_avx2_pminu_b:
12176   case Intrinsic::x86_avx2_pminu_w:
12177   case Intrinsic::x86_avx2_pminu_d:
12178   case Intrinsic::x86_sse41_pmaxsb:
12179   case Intrinsic::x86_sse2_pmaxs_w:
12180   case Intrinsic::x86_sse41_pmaxsd:
12181   case Intrinsic::x86_avx2_pmaxs_b:
12182   case Intrinsic::x86_avx2_pmaxs_w:
12183   case Intrinsic::x86_avx2_pmaxs_d:
12184   case Intrinsic::x86_sse41_pminsb:
12185   case Intrinsic::x86_sse2_pmins_w:
12186   case Intrinsic::x86_sse41_pminsd:
12187   case Intrinsic::x86_avx2_pmins_b:
12188   case Intrinsic::x86_avx2_pmins_w:
12189   case Intrinsic::x86_avx2_pmins_d: {
12190     unsigned Opcode;
12191     switch (IntNo) {
12192     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12193     case Intrinsic::x86_sse2_pmaxu_b:
12194     case Intrinsic::x86_sse41_pmaxuw:
12195     case Intrinsic::x86_sse41_pmaxud:
12196     case Intrinsic::x86_avx2_pmaxu_b:
12197     case Intrinsic::x86_avx2_pmaxu_w:
12198     case Intrinsic::x86_avx2_pmaxu_d:
12199       Opcode = X86ISD::UMAX;
12200       break;
12201     case Intrinsic::x86_sse2_pminu_b:
12202     case Intrinsic::x86_sse41_pminuw:
12203     case Intrinsic::x86_sse41_pminud:
12204     case Intrinsic::x86_avx2_pminu_b:
12205     case Intrinsic::x86_avx2_pminu_w:
12206     case Intrinsic::x86_avx2_pminu_d:
12207       Opcode = X86ISD::UMIN;
12208       break;
12209     case Intrinsic::x86_sse41_pmaxsb:
12210     case Intrinsic::x86_sse2_pmaxs_w:
12211     case Intrinsic::x86_sse41_pmaxsd:
12212     case Intrinsic::x86_avx2_pmaxs_b:
12213     case Intrinsic::x86_avx2_pmaxs_w:
12214     case Intrinsic::x86_avx2_pmaxs_d:
12215       Opcode = X86ISD::SMAX;
12216       break;
12217     case Intrinsic::x86_sse41_pminsb:
12218     case Intrinsic::x86_sse2_pmins_w:
12219     case Intrinsic::x86_sse41_pminsd:
12220     case Intrinsic::x86_avx2_pmins_b:
12221     case Intrinsic::x86_avx2_pmins_w:
12222     case Intrinsic::x86_avx2_pmins_d:
12223       Opcode = X86ISD::SMIN;
12224       break;
12225     }
12226     return DAG.getNode(Opcode, dl, Op.getValueType(),
12227                        Op.getOperand(1), Op.getOperand(2));
12228   }
12229
12230   // SSE/SSE2/AVX floating point max/min intrinsics.
12231   case Intrinsic::x86_sse_max_ps:
12232   case Intrinsic::x86_sse2_max_pd:
12233   case Intrinsic::x86_avx_max_ps_256:
12234   case Intrinsic::x86_avx_max_pd_256:
12235   case Intrinsic::x86_sse_min_ps:
12236   case Intrinsic::x86_sse2_min_pd:
12237   case Intrinsic::x86_avx_min_ps_256:
12238   case Intrinsic::x86_avx_min_pd_256: {
12239     unsigned Opcode;
12240     switch (IntNo) {
12241     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12242     case Intrinsic::x86_sse_max_ps:
12243     case Intrinsic::x86_sse2_max_pd:
12244     case Intrinsic::x86_avx_max_ps_256:
12245     case Intrinsic::x86_avx_max_pd_256:
12246       Opcode = X86ISD::FMAX;
12247       break;
12248     case Intrinsic::x86_sse_min_ps:
12249     case Intrinsic::x86_sse2_min_pd:
12250     case Intrinsic::x86_avx_min_ps_256:
12251     case Intrinsic::x86_avx_min_pd_256:
12252       Opcode = X86ISD::FMIN;
12253       break;
12254     }
12255     return DAG.getNode(Opcode, dl, Op.getValueType(),
12256                        Op.getOperand(1), Op.getOperand(2));
12257   }
12258
12259   // AVX2 variable shift intrinsics
12260   case Intrinsic::x86_avx2_psllv_d:
12261   case Intrinsic::x86_avx2_psllv_q:
12262   case Intrinsic::x86_avx2_psllv_d_256:
12263   case Intrinsic::x86_avx2_psllv_q_256:
12264   case Intrinsic::x86_avx2_psrlv_d:
12265   case Intrinsic::x86_avx2_psrlv_q:
12266   case Intrinsic::x86_avx2_psrlv_d_256:
12267   case Intrinsic::x86_avx2_psrlv_q_256:
12268   case Intrinsic::x86_avx2_psrav_d:
12269   case Intrinsic::x86_avx2_psrav_d_256: {
12270     unsigned Opcode;
12271     switch (IntNo) {
12272     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12273     case Intrinsic::x86_avx2_psllv_d:
12274     case Intrinsic::x86_avx2_psllv_q:
12275     case Intrinsic::x86_avx2_psllv_d_256:
12276     case Intrinsic::x86_avx2_psllv_q_256:
12277       Opcode = ISD::SHL;
12278       break;
12279     case Intrinsic::x86_avx2_psrlv_d:
12280     case Intrinsic::x86_avx2_psrlv_q:
12281     case Intrinsic::x86_avx2_psrlv_d_256:
12282     case Intrinsic::x86_avx2_psrlv_q_256:
12283       Opcode = ISD::SRL;
12284       break;
12285     case Intrinsic::x86_avx2_psrav_d:
12286     case Intrinsic::x86_avx2_psrav_d_256:
12287       Opcode = ISD::SRA;
12288       break;
12289     }
12290     return DAG.getNode(Opcode, dl, Op.getValueType(),
12291                        Op.getOperand(1), Op.getOperand(2));
12292   }
12293
12294   case Intrinsic::x86_ssse3_pshuf_b_128:
12295   case Intrinsic::x86_avx2_pshuf_b:
12296     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12297                        Op.getOperand(1), Op.getOperand(2));
12298
12299   case Intrinsic::x86_ssse3_psign_b_128:
12300   case Intrinsic::x86_ssse3_psign_w_128:
12301   case Intrinsic::x86_ssse3_psign_d_128:
12302   case Intrinsic::x86_avx2_psign_b:
12303   case Intrinsic::x86_avx2_psign_w:
12304   case Intrinsic::x86_avx2_psign_d:
12305     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12306                        Op.getOperand(1), Op.getOperand(2));
12307
12308   case Intrinsic::x86_sse41_insertps:
12309     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12310                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12311
12312   case Intrinsic::x86_avx_vperm2f128_ps_256:
12313   case Intrinsic::x86_avx_vperm2f128_pd_256:
12314   case Intrinsic::x86_avx_vperm2f128_si_256:
12315   case Intrinsic::x86_avx2_vperm2i128:
12316     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12317                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12318
12319   case Intrinsic::x86_avx2_permd:
12320   case Intrinsic::x86_avx2_permps:
12321     // Operands intentionally swapped. Mask is last operand to intrinsic,
12322     // but second operand for node/instruction.
12323     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12324                        Op.getOperand(2), Op.getOperand(1));
12325
12326   case Intrinsic::x86_sse_sqrt_ps:
12327   case Intrinsic::x86_sse2_sqrt_pd:
12328   case Intrinsic::x86_avx_sqrt_ps_256:
12329   case Intrinsic::x86_avx_sqrt_pd_256:
12330     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12331
12332   // ptest and testp intrinsics. The intrinsic these come from are designed to
12333   // return an integer value, not just an instruction so lower it to the ptest
12334   // or testp pattern and a setcc for the result.
12335   case Intrinsic::x86_sse41_ptestz:
12336   case Intrinsic::x86_sse41_ptestc:
12337   case Intrinsic::x86_sse41_ptestnzc:
12338   case Intrinsic::x86_avx_ptestz_256:
12339   case Intrinsic::x86_avx_ptestc_256:
12340   case Intrinsic::x86_avx_ptestnzc_256:
12341   case Intrinsic::x86_avx_vtestz_ps:
12342   case Intrinsic::x86_avx_vtestc_ps:
12343   case Intrinsic::x86_avx_vtestnzc_ps:
12344   case Intrinsic::x86_avx_vtestz_pd:
12345   case Intrinsic::x86_avx_vtestc_pd:
12346   case Intrinsic::x86_avx_vtestnzc_pd:
12347   case Intrinsic::x86_avx_vtestz_ps_256:
12348   case Intrinsic::x86_avx_vtestc_ps_256:
12349   case Intrinsic::x86_avx_vtestnzc_ps_256:
12350   case Intrinsic::x86_avx_vtestz_pd_256:
12351   case Intrinsic::x86_avx_vtestc_pd_256:
12352   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12353     bool IsTestPacked = false;
12354     unsigned X86CC;
12355     switch (IntNo) {
12356     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12357     case Intrinsic::x86_avx_vtestz_ps:
12358     case Intrinsic::x86_avx_vtestz_pd:
12359     case Intrinsic::x86_avx_vtestz_ps_256:
12360     case Intrinsic::x86_avx_vtestz_pd_256:
12361       IsTestPacked = true; // Fallthrough
12362     case Intrinsic::x86_sse41_ptestz:
12363     case Intrinsic::x86_avx_ptestz_256:
12364       // ZF = 1
12365       X86CC = X86::COND_E;
12366       break;
12367     case Intrinsic::x86_avx_vtestc_ps:
12368     case Intrinsic::x86_avx_vtestc_pd:
12369     case Intrinsic::x86_avx_vtestc_ps_256:
12370     case Intrinsic::x86_avx_vtestc_pd_256:
12371       IsTestPacked = true; // Fallthrough
12372     case Intrinsic::x86_sse41_ptestc:
12373     case Intrinsic::x86_avx_ptestc_256:
12374       // CF = 1
12375       X86CC = X86::COND_B;
12376       break;
12377     case Intrinsic::x86_avx_vtestnzc_ps:
12378     case Intrinsic::x86_avx_vtestnzc_pd:
12379     case Intrinsic::x86_avx_vtestnzc_ps_256:
12380     case Intrinsic::x86_avx_vtestnzc_pd_256:
12381       IsTestPacked = true; // Fallthrough
12382     case Intrinsic::x86_sse41_ptestnzc:
12383     case Intrinsic::x86_avx_ptestnzc_256:
12384       // ZF and CF = 0
12385       X86CC = X86::COND_A;
12386       break;
12387     }
12388
12389     SDValue LHS = Op.getOperand(1);
12390     SDValue RHS = Op.getOperand(2);
12391     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12392     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12393     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12394     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12395     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12396   }
12397   case Intrinsic::x86_avx512_kortestz_w:
12398   case Intrinsic::x86_avx512_kortestc_w: {
12399     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12400     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12401     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12402     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12403     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12404     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12405     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12406   }
12407
12408   // SSE/AVX shift intrinsics
12409   case Intrinsic::x86_sse2_psll_w:
12410   case Intrinsic::x86_sse2_psll_d:
12411   case Intrinsic::x86_sse2_psll_q:
12412   case Intrinsic::x86_avx2_psll_w:
12413   case Intrinsic::x86_avx2_psll_d:
12414   case Intrinsic::x86_avx2_psll_q:
12415   case Intrinsic::x86_sse2_psrl_w:
12416   case Intrinsic::x86_sse2_psrl_d:
12417   case Intrinsic::x86_sse2_psrl_q:
12418   case Intrinsic::x86_avx2_psrl_w:
12419   case Intrinsic::x86_avx2_psrl_d:
12420   case Intrinsic::x86_avx2_psrl_q:
12421   case Intrinsic::x86_sse2_psra_w:
12422   case Intrinsic::x86_sse2_psra_d:
12423   case Intrinsic::x86_avx2_psra_w:
12424   case Intrinsic::x86_avx2_psra_d: {
12425     unsigned Opcode;
12426     switch (IntNo) {
12427     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12428     case Intrinsic::x86_sse2_psll_w:
12429     case Intrinsic::x86_sse2_psll_d:
12430     case Intrinsic::x86_sse2_psll_q:
12431     case Intrinsic::x86_avx2_psll_w:
12432     case Intrinsic::x86_avx2_psll_d:
12433     case Intrinsic::x86_avx2_psll_q:
12434       Opcode = X86ISD::VSHL;
12435       break;
12436     case Intrinsic::x86_sse2_psrl_w:
12437     case Intrinsic::x86_sse2_psrl_d:
12438     case Intrinsic::x86_sse2_psrl_q:
12439     case Intrinsic::x86_avx2_psrl_w:
12440     case Intrinsic::x86_avx2_psrl_d:
12441     case Intrinsic::x86_avx2_psrl_q:
12442       Opcode = X86ISD::VSRL;
12443       break;
12444     case Intrinsic::x86_sse2_psra_w:
12445     case Intrinsic::x86_sse2_psra_d:
12446     case Intrinsic::x86_avx2_psra_w:
12447     case Intrinsic::x86_avx2_psra_d:
12448       Opcode = X86ISD::VSRA;
12449       break;
12450     }
12451     return DAG.getNode(Opcode, dl, Op.getValueType(),
12452                        Op.getOperand(1), Op.getOperand(2));
12453   }
12454
12455   // SSE/AVX immediate shift intrinsics
12456   case Intrinsic::x86_sse2_pslli_w:
12457   case Intrinsic::x86_sse2_pslli_d:
12458   case Intrinsic::x86_sse2_pslli_q:
12459   case Intrinsic::x86_avx2_pslli_w:
12460   case Intrinsic::x86_avx2_pslli_d:
12461   case Intrinsic::x86_avx2_pslli_q:
12462   case Intrinsic::x86_sse2_psrli_w:
12463   case Intrinsic::x86_sse2_psrli_d:
12464   case Intrinsic::x86_sse2_psrli_q:
12465   case Intrinsic::x86_avx2_psrli_w:
12466   case Intrinsic::x86_avx2_psrli_d:
12467   case Intrinsic::x86_avx2_psrli_q:
12468   case Intrinsic::x86_sse2_psrai_w:
12469   case Intrinsic::x86_sse2_psrai_d:
12470   case Intrinsic::x86_avx2_psrai_w:
12471   case Intrinsic::x86_avx2_psrai_d: {
12472     unsigned Opcode;
12473     switch (IntNo) {
12474     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12475     case Intrinsic::x86_sse2_pslli_w:
12476     case Intrinsic::x86_sse2_pslli_d:
12477     case Intrinsic::x86_sse2_pslli_q:
12478     case Intrinsic::x86_avx2_pslli_w:
12479     case Intrinsic::x86_avx2_pslli_d:
12480     case Intrinsic::x86_avx2_pslli_q:
12481       Opcode = X86ISD::VSHLI;
12482       break;
12483     case Intrinsic::x86_sse2_psrli_w:
12484     case Intrinsic::x86_sse2_psrli_d:
12485     case Intrinsic::x86_sse2_psrli_q:
12486     case Intrinsic::x86_avx2_psrli_w:
12487     case Intrinsic::x86_avx2_psrli_d:
12488     case Intrinsic::x86_avx2_psrli_q:
12489       Opcode = X86ISD::VSRLI;
12490       break;
12491     case Intrinsic::x86_sse2_psrai_w:
12492     case Intrinsic::x86_sse2_psrai_d:
12493     case Intrinsic::x86_avx2_psrai_w:
12494     case Intrinsic::x86_avx2_psrai_d:
12495       Opcode = X86ISD::VSRAI;
12496       break;
12497     }
12498     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12499                                Op.getOperand(1), Op.getOperand(2), DAG);
12500   }
12501
12502   case Intrinsic::x86_sse42_pcmpistria128:
12503   case Intrinsic::x86_sse42_pcmpestria128:
12504   case Intrinsic::x86_sse42_pcmpistric128:
12505   case Intrinsic::x86_sse42_pcmpestric128:
12506   case Intrinsic::x86_sse42_pcmpistrio128:
12507   case Intrinsic::x86_sse42_pcmpestrio128:
12508   case Intrinsic::x86_sse42_pcmpistris128:
12509   case Intrinsic::x86_sse42_pcmpestris128:
12510   case Intrinsic::x86_sse42_pcmpistriz128:
12511   case Intrinsic::x86_sse42_pcmpestriz128: {
12512     unsigned Opcode;
12513     unsigned X86CC;
12514     switch (IntNo) {
12515     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12516     case Intrinsic::x86_sse42_pcmpistria128:
12517       Opcode = X86ISD::PCMPISTRI;
12518       X86CC = X86::COND_A;
12519       break;
12520     case Intrinsic::x86_sse42_pcmpestria128:
12521       Opcode = X86ISD::PCMPESTRI;
12522       X86CC = X86::COND_A;
12523       break;
12524     case Intrinsic::x86_sse42_pcmpistric128:
12525       Opcode = X86ISD::PCMPISTRI;
12526       X86CC = X86::COND_B;
12527       break;
12528     case Intrinsic::x86_sse42_pcmpestric128:
12529       Opcode = X86ISD::PCMPESTRI;
12530       X86CC = X86::COND_B;
12531       break;
12532     case Intrinsic::x86_sse42_pcmpistrio128:
12533       Opcode = X86ISD::PCMPISTRI;
12534       X86CC = X86::COND_O;
12535       break;
12536     case Intrinsic::x86_sse42_pcmpestrio128:
12537       Opcode = X86ISD::PCMPESTRI;
12538       X86CC = X86::COND_O;
12539       break;
12540     case Intrinsic::x86_sse42_pcmpistris128:
12541       Opcode = X86ISD::PCMPISTRI;
12542       X86CC = X86::COND_S;
12543       break;
12544     case Intrinsic::x86_sse42_pcmpestris128:
12545       Opcode = X86ISD::PCMPESTRI;
12546       X86CC = X86::COND_S;
12547       break;
12548     case Intrinsic::x86_sse42_pcmpistriz128:
12549       Opcode = X86ISD::PCMPISTRI;
12550       X86CC = X86::COND_E;
12551       break;
12552     case Intrinsic::x86_sse42_pcmpestriz128:
12553       Opcode = X86ISD::PCMPESTRI;
12554       X86CC = X86::COND_E;
12555       break;
12556     }
12557     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12558     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12559     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12560     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12561                                 DAG.getConstant(X86CC, MVT::i8),
12562                                 SDValue(PCMP.getNode(), 1));
12563     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12564   }
12565
12566   case Intrinsic::x86_sse42_pcmpistri128:
12567   case Intrinsic::x86_sse42_pcmpestri128: {
12568     unsigned Opcode;
12569     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12570       Opcode = X86ISD::PCMPISTRI;
12571     else
12572       Opcode = X86ISD::PCMPESTRI;
12573
12574     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12575     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12576     return DAG.getNode(Opcode, dl, VTs, NewOps);
12577   }
12578   case Intrinsic::x86_fma_vfmadd_ps:
12579   case Intrinsic::x86_fma_vfmadd_pd:
12580   case Intrinsic::x86_fma_vfmsub_ps:
12581   case Intrinsic::x86_fma_vfmsub_pd:
12582   case Intrinsic::x86_fma_vfnmadd_ps:
12583   case Intrinsic::x86_fma_vfnmadd_pd:
12584   case Intrinsic::x86_fma_vfnmsub_ps:
12585   case Intrinsic::x86_fma_vfnmsub_pd:
12586   case Intrinsic::x86_fma_vfmaddsub_ps:
12587   case Intrinsic::x86_fma_vfmaddsub_pd:
12588   case Intrinsic::x86_fma_vfmsubadd_ps:
12589   case Intrinsic::x86_fma_vfmsubadd_pd:
12590   case Intrinsic::x86_fma_vfmadd_ps_256:
12591   case Intrinsic::x86_fma_vfmadd_pd_256:
12592   case Intrinsic::x86_fma_vfmsub_ps_256:
12593   case Intrinsic::x86_fma_vfmsub_pd_256:
12594   case Intrinsic::x86_fma_vfnmadd_ps_256:
12595   case Intrinsic::x86_fma_vfnmadd_pd_256:
12596   case Intrinsic::x86_fma_vfnmsub_ps_256:
12597   case Intrinsic::x86_fma_vfnmsub_pd_256:
12598   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12599   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12600   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12601   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12602   case Intrinsic::x86_fma_vfmadd_ps_512:
12603   case Intrinsic::x86_fma_vfmadd_pd_512:
12604   case Intrinsic::x86_fma_vfmsub_ps_512:
12605   case Intrinsic::x86_fma_vfmsub_pd_512:
12606   case Intrinsic::x86_fma_vfnmadd_ps_512:
12607   case Intrinsic::x86_fma_vfnmadd_pd_512:
12608   case Intrinsic::x86_fma_vfnmsub_ps_512:
12609   case Intrinsic::x86_fma_vfnmsub_pd_512:
12610   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12611   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12612   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12613   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12614     unsigned Opc;
12615     switch (IntNo) {
12616     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12617     case Intrinsic::x86_fma_vfmadd_ps:
12618     case Intrinsic::x86_fma_vfmadd_pd:
12619     case Intrinsic::x86_fma_vfmadd_ps_256:
12620     case Intrinsic::x86_fma_vfmadd_pd_256:
12621     case Intrinsic::x86_fma_vfmadd_ps_512:
12622     case Intrinsic::x86_fma_vfmadd_pd_512:
12623       Opc = X86ISD::FMADD;
12624       break;
12625     case Intrinsic::x86_fma_vfmsub_ps:
12626     case Intrinsic::x86_fma_vfmsub_pd:
12627     case Intrinsic::x86_fma_vfmsub_ps_256:
12628     case Intrinsic::x86_fma_vfmsub_pd_256:
12629     case Intrinsic::x86_fma_vfmsub_ps_512:
12630     case Intrinsic::x86_fma_vfmsub_pd_512:
12631       Opc = X86ISD::FMSUB;
12632       break;
12633     case Intrinsic::x86_fma_vfnmadd_ps:
12634     case Intrinsic::x86_fma_vfnmadd_pd:
12635     case Intrinsic::x86_fma_vfnmadd_ps_256:
12636     case Intrinsic::x86_fma_vfnmadd_pd_256:
12637     case Intrinsic::x86_fma_vfnmadd_ps_512:
12638     case Intrinsic::x86_fma_vfnmadd_pd_512:
12639       Opc = X86ISD::FNMADD;
12640       break;
12641     case Intrinsic::x86_fma_vfnmsub_ps:
12642     case Intrinsic::x86_fma_vfnmsub_pd:
12643     case Intrinsic::x86_fma_vfnmsub_ps_256:
12644     case Intrinsic::x86_fma_vfnmsub_pd_256:
12645     case Intrinsic::x86_fma_vfnmsub_ps_512:
12646     case Intrinsic::x86_fma_vfnmsub_pd_512:
12647       Opc = X86ISD::FNMSUB;
12648       break;
12649     case Intrinsic::x86_fma_vfmaddsub_ps:
12650     case Intrinsic::x86_fma_vfmaddsub_pd:
12651     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12652     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12653     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12654     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12655       Opc = X86ISD::FMADDSUB;
12656       break;
12657     case Intrinsic::x86_fma_vfmsubadd_ps:
12658     case Intrinsic::x86_fma_vfmsubadd_pd:
12659     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12660     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12661     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12662     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12663       Opc = X86ISD::FMSUBADD;
12664       break;
12665     }
12666
12667     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12668                        Op.getOperand(2), Op.getOperand(3));
12669   }
12670   }
12671 }
12672
12673 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12674                               SDValue Src, SDValue Mask, SDValue Base,
12675                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12676                               const X86Subtarget * Subtarget) {
12677   SDLoc dl(Op);
12678   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12679   assert(C && "Invalid scale type");
12680   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12681   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12682                              Index.getSimpleValueType().getVectorNumElements());
12683   SDValue MaskInReg;
12684   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12685   if (MaskC)
12686     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12687   else
12688     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12689   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12690   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12691   SDValue Segment = DAG.getRegister(0, MVT::i32);
12692   if (Src.getOpcode() == ISD::UNDEF)
12693     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12694   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12695   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12696   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12697   return DAG.getMergeValues(RetOps, dl);
12698 }
12699
12700 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12701                                SDValue Src, SDValue Mask, SDValue Base,
12702                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12703   SDLoc dl(Op);
12704   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12705   assert(C && "Invalid scale type");
12706   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12707   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12708   SDValue Segment = DAG.getRegister(0, MVT::i32);
12709   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12710                              Index.getSimpleValueType().getVectorNumElements());
12711   SDValue MaskInReg;
12712   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12713   if (MaskC)
12714     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12715   else
12716     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12717   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12718   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12719   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12720   return SDValue(Res, 1);
12721 }
12722
12723 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12724                                SDValue Mask, SDValue Base, SDValue Index,
12725                                SDValue ScaleOp, SDValue Chain) {
12726   SDLoc dl(Op);
12727   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12728   assert(C && "Invalid scale type");
12729   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12730   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12731   SDValue Segment = DAG.getRegister(0, MVT::i32);
12732   EVT MaskVT =
12733     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12734   SDValue MaskInReg;
12735   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12736   if (MaskC)
12737     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12738   else
12739     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12740   //SDVTList VTs = DAG.getVTList(MVT::Other);
12741   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12742   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12743   return SDValue(Res, 0);
12744 }
12745
12746 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12747 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12748 // also used to custom lower READCYCLECOUNTER nodes.
12749 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12750                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12751                               SmallVectorImpl<SDValue> &Results) {
12752   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12753   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12754   SDValue LO, HI;
12755
12756   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12757   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12758   // and the EAX register is loaded with the low-order 32 bits.
12759   if (Subtarget->is64Bit()) {
12760     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12761     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12762                             LO.getValue(2));
12763   } else {
12764     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12765     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12766                             LO.getValue(2));
12767   }
12768   SDValue Chain = HI.getValue(1);
12769
12770   if (Opcode == X86ISD::RDTSCP_DAG) {
12771     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12772
12773     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12774     // the ECX register. Add 'ecx' explicitly to the chain.
12775     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12776                                      HI.getValue(2));
12777     // Explicitly store the content of ECX at the location passed in input
12778     // to the 'rdtscp' intrinsic.
12779     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12780                          MachinePointerInfo(), false, false, 0);
12781   }
12782
12783   if (Subtarget->is64Bit()) {
12784     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12785     // the EAX register is loaded with the low-order 32 bits.
12786     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12787                               DAG.getConstant(32, MVT::i8));
12788     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12789     Results.push_back(Chain);
12790     return;
12791   }
12792
12793   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12794   SDValue Ops[] = { LO, HI };
12795   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12796   Results.push_back(Pair);
12797   Results.push_back(Chain);
12798 }
12799
12800 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12801                                      SelectionDAG &DAG) {
12802   SmallVector<SDValue, 2> Results;
12803   SDLoc DL(Op);
12804   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12805                           Results);
12806   return DAG.getMergeValues(Results, DL);
12807 }
12808
12809 enum IntrinsicType {
12810   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12811 };
12812
12813 struct IntrinsicData {
12814   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12815     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12816   IntrinsicType Type;
12817   unsigned      Opc0;
12818   unsigned      Opc1;
12819 };
12820
12821 std::map < unsigned, IntrinsicData> IntrMap;
12822 static void InitIntinsicsMap() {
12823   static bool Initialized = false;
12824   if (Initialized) 
12825     return;
12826   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12827                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12828   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12829                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12830   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12831                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12832   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12833                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12834   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12835                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12836   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12837                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12838   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12839                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12840   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12841                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12842   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12843                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12844
12845   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12846                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12847   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12848                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12849   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12850                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12851   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12852                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12853   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12854                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12855   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12856                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12857   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
12858                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12859   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
12860                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12861    
12862   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
12863                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12864                                                         X86::VGATHERPF1QPSm)));
12865   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
12866                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12867                                                         X86::VGATHERPF1QPDm)));
12868   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
12869                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12870                                                         X86::VGATHERPF1DPDm)));
12871   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
12872                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12873                                                         X86::VGATHERPF1DPSm)));
12874   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
12875                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12876                                                         X86::VSCATTERPF1QPSm)));
12877   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
12878                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12879                                                         X86::VSCATTERPF1QPDm)));
12880   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
12881                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12882                                                         X86::VSCATTERPF1DPDm)));
12883   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
12884                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12885                                                         X86::VSCATTERPF1DPSm)));
12886   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12887                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12888   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12889                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12890   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12891                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12892   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12893                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12894   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12895                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12896   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12897                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12898   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12899                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
12900   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12901                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
12902   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12903                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
12904   Initialized = true;
12905 }
12906
12907 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12908                                       SelectionDAG &DAG) {
12909   InitIntinsicsMap();
12910   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12911   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12912   if (itr == IntrMap.end())
12913     return SDValue();
12914
12915   SDLoc dl(Op);
12916   IntrinsicData Intr = itr->second;
12917   switch(Intr.Type) {
12918   case RDSEED:
12919   case RDRAND: {
12920     // Emit the node with the right value type.
12921     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12922     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12923
12924     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12925     // Otherwise return the value from Rand, which is always 0, casted to i32.
12926     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12927                       DAG.getConstant(1, Op->getValueType(1)),
12928                       DAG.getConstant(X86::COND_B, MVT::i32),
12929                       SDValue(Result.getNode(), 1) };
12930     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12931                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12932                                   Ops);
12933
12934     // Return { result, isValid, chain }.
12935     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12936                        SDValue(Result.getNode(), 2));
12937   }
12938   case GATHER: {
12939   //gather(v1, mask, index, base, scale);
12940     SDValue Chain = Op.getOperand(0);
12941     SDValue Src   = Op.getOperand(2);
12942     SDValue Base  = Op.getOperand(3);
12943     SDValue Index = Op.getOperand(4);
12944     SDValue Mask  = Op.getOperand(5);
12945     SDValue Scale = Op.getOperand(6);
12946     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12947                           Subtarget);
12948   }
12949   case SCATTER: {
12950   //scatter(base, mask, index, v1, scale);
12951     SDValue Chain = Op.getOperand(0);
12952     SDValue Base  = Op.getOperand(2);
12953     SDValue Mask  = Op.getOperand(3);
12954     SDValue Index = Op.getOperand(4);
12955     SDValue Src   = Op.getOperand(5);
12956     SDValue Scale = Op.getOperand(6);
12957     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12958   }
12959   case PREFETCH: {
12960     SDValue Hint = Op.getOperand(6);
12961     unsigned HintVal;
12962     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
12963         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12964       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12965     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12966     SDValue Chain = Op.getOperand(0);
12967     SDValue Mask  = Op.getOperand(2);
12968     SDValue Index = Op.getOperand(3);
12969     SDValue Base  = Op.getOperand(4);
12970     SDValue Scale = Op.getOperand(5);
12971     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12972   }
12973   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12974   case RDTSC: {
12975     SmallVector<SDValue, 2> Results;
12976     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12977     return DAG.getMergeValues(Results, dl);
12978   }
12979   // XTEST intrinsics.
12980   case XTEST: {
12981     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12982     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12983     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12984                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12985                                 InTrans);
12986     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12987     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12988                        Ret, SDValue(InTrans.getNode(), 1));
12989   }
12990   }
12991   llvm_unreachable("Unknown Intrinsic Type");
12992 }
12993
12994 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12995                                            SelectionDAG &DAG) const {
12996   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12997   MFI->setReturnAddressIsTaken(true);
12998
12999   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13000     return SDValue();
13001
13002   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13003   SDLoc dl(Op);
13004   EVT PtrVT = getPointerTy();
13005
13006   if (Depth > 0) {
13007     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13008     const X86RegisterInfo *RegInfo =
13009       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13010     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13011     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13012                        DAG.getNode(ISD::ADD, dl, PtrVT,
13013                                    FrameAddr, Offset),
13014                        MachinePointerInfo(), false, false, false, 0);
13015   }
13016
13017   // Just load the return address.
13018   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13019   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13020                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13021 }
13022
13023 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13024   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13025   MFI->setFrameAddressIsTaken(true);
13026
13027   EVT VT = Op.getValueType();
13028   SDLoc dl(Op);  // FIXME probably not meaningful
13029   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13030   const X86RegisterInfo *RegInfo =
13031     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13032   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13033   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13034           (FrameReg == X86::EBP && VT == MVT::i32)) &&
13035          "Invalid Frame Register!");
13036   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13037   while (Depth--)
13038     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13039                             MachinePointerInfo(),
13040                             false, false, false, 0);
13041   return FrameAddr;
13042 }
13043
13044 // FIXME? Maybe this could be a TableGen attribute on some registers and
13045 // this table could be generated automatically from RegInfo.
13046 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13047                                               EVT VT) const {
13048   unsigned Reg = StringSwitch<unsigned>(RegName)
13049                        .Case("esp", X86::ESP)
13050                        .Case("rsp", X86::RSP)
13051                        .Default(0);
13052   if (Reg)
13053     return Reg;
13054   report_fatal_error("Invalid register name global variable");
13055 }
13056
13057 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13058                                                      SelectionDAG &DAG) const {
13059   const X86RegisterInfo *RegInfo =
13060     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13061   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13062 }
13063
13064 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13065   SDValue Chain     = Op.getOperand(0);
13066   SDValue Offset    = Op.getOperand(1);
13067   SDValue Handler   = Op.getOperand(2);
13068   SDLoc dl      (Op);
13069
13070   EVT PtrVT = getPointerTy();
13071   const X86RegisterInfo *RegInfo =
13072     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
13073   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13074   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13075           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13076          "Invalid Frame Register!");
13077   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13078   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13079
13080   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13081                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13082   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13083   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13084                        false, false, 0);
13085   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13086
13087   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13088                      DAG.getRegister(StoreAddrReg, PtrVT));
13089 }
13090
13091 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13092                                                SelectionDAG &DAG) const {
13093   SDLoc DL(Op);
13094   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13095                      DAG.getVTList(MVT::i32, MVT::Other),
13096                      Op.getOperand(0), Op.getOperand(1));
13097 }
13098
13099 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13100                                                 SelectionDAG &DAG) const {
13101   SDLoc DL(Op);
13102   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13103                      Op.getOperand(0), Op.getOperand(1));
13104 }
13105
13106 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13107   return Op.getOperand(0);
13108 }
13109
13110 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13111                                                 SelectionDAG &DAG) const {
13112   SDValue Root = Op.getOperand(0);
13113   SDValue Trmp = Op.getOperand(1); // trampoline
13114   SDValue FPtr = Op.getOperand(2); // nested function
13115   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13116   SDLoc dl (Op);
13117
13118   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13119   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13120
13121   if (Subtarget->is64Bit()) {
13122     SDValue OutChains[6];
13123
13124     // Large code-model.
13125     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
13126     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13127
13128     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13129     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13130
13131     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13132
13133     // Load the pointer to the nested function into R11.
13134     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13135     SDValue Addr = Trmp;
13136     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13137                                 Addr, MachinePointerInfo(TrmpAddr),
13138                                 false, false, 0);
13139
13140     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13141                        DAG.getConstant(2, MVT::i64));
13142     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13143                                 MachinePointerInfo(TrmpAddr, 2),
13144                                 false, false, 2);
13145
13146     // Load the 'nest' parameter value into R10.
13147     // R10 is specified in X86CallingConv.td
13148     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13149     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13150                        DAG.getConstant(10, MVT::i64));
13151     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13152                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13153                                 false, false, 0);
13154
13155     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13156                        DAG.getConstant(12, MVT::i64));
13157     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13158                                 MachinePointerInfo(TrmpAddr, 12),
13159                                 false, false, 2);
13160
13161     // Jump to the nested function.
13162     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13163     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13164                        DAG.getConstant(20, MVT::i64));
13165     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13166                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13167                                 false, false, 0);
13168
13169     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13170     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13171                        DAG.getConstant(22, MVT::i64));
13172     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13173                                 MachinePointerInfo(TrmpAddr, 22),
13174                                 false, false, 0);
13175
13176     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13177   } else {
13178     const Function *Func =
13179       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13180     CallingConv::ID CC = Func->getCallingConv();
13181     unsigned NestReg;
13182
13183     switch (CC) {
13184     default:
13185       llvm_unreachable("Unsupported calling convention");
13186     case CallingConv::C:
13187     case CallingConv::X86_StdCall: {
13188       // Pass 'nest' parameter in ECX.
13189       // Must be kept in sync with X86CallingConv.td
13190       NestReg = X86::ECX;
13191
13192       // Check that ECX wasn't needed by an 'inreg' parameter.
13193       FunctionType *FTy = Func->getFunctionType();
13194       const AttributeSet &Attrs = Func->getAttributes();
13195
13196       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13197         unsigned InRegCount = 0;
13198         unsigned Idx = 1;
13199
13200         for (FunctionType::param_iterator I = FTy->param_begin(),
13201              E = FTy->param_end(); I != E; ++I, ++Idx)
13202           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13203             // FIXME: should only count parameters that are lowered to integers.
13204             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13205
13206         if (InRegCount > 2) {
13207           report_fatal_error("Nest register in use - reduce number of inreg"
13208                              " parameters!");
13209         }
13210       }
13211       break;
13212     }
13213     case CallingConv::X86_FastCall:
13214     case CallingConv::X86_ThisCall:
13215     case CallingConv::Fast:
13216       // Pass 'nest' parameter in EAX.
13217       // Must be kept in sync with X86CallingConv.td
13218       NestReg = X86::EAX;
13219       break;
13220     }
13221
13222     SDValue OutChains[4];
13223     SDValue Addr, Disp;
13224
13225     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13226                        DAG.getConstant(10, MVT::i32));
13227     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13228
13229     // This is storing the opcode for MOV32ri.
13230     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13231     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13232     OutChains[0] = DAG.getStore(Root, dl,
13233                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13234                                 Trmp, MachinePointerInfo(TrmpAddr),
13235                                 false, false, 0);
13236
13237     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13238                        DAG.getConstant(1, MVT::i32));
13239     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13240                                 MachinePointerInfo(TrmpAddr, 1),
13241                                 false, false, 1);
13242
13243     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13244     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13245                        DAG.getConstant(5, MVT::i32));
13246     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13247                                 MachinePointerInfo(TrmpAddr, 5),
13248                                 false, false, 1);
13249
13250     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13251                        DAG.getConstant(6, MVT::i32));
13252     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13253                                 MachinePointerInfo(TrmpAddr, 6),
13254                                 false, false, 1);
13255
13256     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13257   }
13258 }
13259
13260 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13261                                             SelectionDAG &DAG) const {
13262   /*
13263    The rounding mode is in bits 11:10 of FPSR, and has the following
13264    settings:
13265      00 Round to nearest
13266      01 Round to -inf
13267      10 Round to +inf
13268      11 Round to 0
13269
13270   FLT_ROUNDS, on the other hand, expects the following:
13271     -1 Undefined
13272      0 Round to 0
13273      1 Round to nearest
13274      2 Round to +inf
13275      3 Round to -inf
13276
13277   To perform the conversion, we do:
13278     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13279   */
13280
13281   MachineFunction &MF = DAG.getMachineFunction();
13282   const TargetMachine &TM = MF.getTarget();
13283   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13284   unsigned StackAlignment = TFI.getStackAlignment();
13285   MVT VT = Op.getSimpleValueType();
13286   SDLoc DL(Op);
13287
13288   // Save FP Control Word to stack slot
13289   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13290   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13291
13292   MachineMemOperand *MMO =
13293    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13294                            MachineMemOperand::MOStore, 2, 2);
13295
13296   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13297   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13298                                           DAG.getVTList(MVT::Other),
13299                                           Ops, MVT::i16, MMO);
13300
13301   // Load FP Control Word from stack slot
13302   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13303                             MachinePointerInfo(), false, false, false, 0);
13304
13305   // Transform as necessary
13306   SDValue CWD1 =
13307     DAG.getNode(ISD::SRL, DL, MVT::i16,
13308                 DAG.getNode(ISD::AND, DL, MVT::i16,
13309                             CWD, DAG.getConstant(0x800, MVT::i16)),
13310                 DAG.getConstant(11, MVT::i8));
13311   SDValue CWD2 =
13312     DAG.getNode(ISD::SRL, DL, MVT::i16,
13313                 DAG.getNode(ISD::AND, DL, MVT::i16,
13314                             CWD, DAG.getConstant(0x400, MVT::i16)),
13315                 DAG.getConstant(9, MVT::i8));
13316
13317   SDValue RetVal =
13318     DAG.getNode(ISD::AND, DL, MVT::i16,
13319                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13320                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13321                             DAG.getConstant(1, MVT::i16)),
13322                 DAG.getConstant(3, MVT::i16));
13323
13324   return DAG.getNode((VT.getSizeInBits() < 16 ?
13325                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13326 }
13327
13328 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13329   MVT VT = Op.getSimpleValueType();
13330   EVT OpVT = VT;
13331   unsigned NumBits = VT.getSizeInBits();
13332   SDLoc dl(Op);
13333
13334   Op = Op.getOperand(0);
13335   if (VT == MVT::i8) {
13336     // Zero extend to i32 since there is not an i8 bsr.
13337     OpVT = MVT::i32;
13338     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13339   }
13340
13341   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13342   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13343   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13344
13345   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13346   SDValue Ops[] = {
13347     Op,
13348     DAG.getConstant(NumBits+NumBits-1, OpVT),
13349     DAG.getConstant(X86::COND_E, MVT::i8),
13350     Op.getValue(1)
13351   };
13352   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13353
13354   // Finally xor with NumBits-1.
13355   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13356
13357   if (VT == MVT::i8)
13358     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13359   return Op;
13360 }
13361
13362 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13363   MVT VT = Op.getSimpleValueType();
13364   EVT OpVT = VT;
13365   unsigned NumBits = VT.getSizeInBits();
13366   SDLoc dl(Op);
13367
13368   Op = Op.getOperand(0);
13369   if (VT == MVT::i8) {
13370     // Zero extend to i32 since there is not an i8 bsr.
13371     OpVT = MVT::i32;
13372     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13373   }
13374
13375   // Issue a bsr (scan bits in reverse).
13376   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13377   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13378
13379   // And xor with NumBits-1.
13380   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13381
13382   if (VT == MVT::i8)
13383     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13384   return Op;
13385 }
13386
13387 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13388   MVT VT = Op.getSimpleValueType();
13389   unsigned NumBits = VT.getSizeInBits();
13390   SDLoc dl(Op);
13391   Op = Op.getOperand(0);
13392
13393   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13394   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13395   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13396
13397   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13398   SDValue Ops[] = {
13399     Op,
13400     DAG.getConstant(NumBits, VT),
13401     DAG.getConstant(X86::COND_E, MVT::i8),
13402     Op.getValue(1)
13403   };
13404   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13405 }
13406
13407 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13408 // ones, and then concatenate the result back.
13409 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13410   MVT VT = Op.getSimpleValueType();
13411
13412   assert(VT.is256BitVector() && VT.isInteger() &&
13413          "Unsupported value type for operation");
13414
13415   unsigned NumElems = VT.getVectorNumElements();
13416   SDLoc dl(Op);
13417
13418   // Extract the LHS vectors
13419   SDValue LHS = Op.getOperand(0);
13420   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13421   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13422
13423   // Extract the RHS vectors
13424   SDValue RHS = Op.getOperand(1);
13425   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13426   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13427
13428   MVT EltVT = VT.getVectorElementType();
13429   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13430
13431   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13432                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13433                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13434 }
13435
13436 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13437   assert(Op.getSimpleValueType().is256BitVector() &&
13438          Op.getSimpleValueType().isInteger() &&
13439          "Only handle AVX 256-bit vector integer operation");
13440   return Lower256IntArith(Op, DAG);
13441 }
13442
13443 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13444   assert(Op.getSimpleValueType().is256BitVector() &&
13445          Op.getSimpleValueType().isInteger() &&
13446          "Only handle AVX 256-bit vector integer operation");
13447   return Lower256IntArith(Op, DAG);
13448 }
13449
13450 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13451                         SelectionDAG &DAG) {
13452   SDLoc dl(Op);
13453   MVT VT = Op.getSimpleValueType();
13454
13455   // Decompose 256-bit ops into smaller 128-bit ops.
13456   if (VT.is256BitVector() && !Subtarget->hasInt256())
13457     return Lower256IntArith(Op, DAG);
13458
13459   SDValue A = Op.getOperand(0);
13460   SDValue B = Op.getOperand(1);
13461
13462   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13463   if (VT == MVT::v4i32) {
13464     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13465            "Should not custom lower when pmuldq is available!");
13466
13467     // Extract the odd parts.
13468     static const int UnpackMask[] = { 1, -1, 3, -1 };
13469     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13470     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13471
13472     // Multiply the even parts.
13473     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13474     // Now multiply odd parts.
13475     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13476
13477     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13478     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13479
13480     // Merge the two vectors back together with a shuffle. This expands into 2
13481     // shuffles.
13482     static const int ShufMask[] = { 0, 4, 2, 6 };
13483     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13484   }
13485
13486   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13487          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13488
13489   //  Ahi = psrlqi(a, 32);
13490   //  Bhi = psrlqi(b, 32);
13491   //
13492   //  AloBlo = pmuludq(a, b);
13493   //  AloBhi = pmuludq(a, Bhi);
13494   //  AhiBlo = pmuludq(Ahi, b);
13495
13496   //  AloBhi = psllqi(AloBhi, 32);
13497   //  AhiBlo = psllqi(AhiBlo, 32);
13498   //  return AloBlo + AloBhi + AhiBlo;
13499
13500   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13501   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13502
13503   // Bit cast to 32-bit vectors for MULUDQ
13504   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13505                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13506   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13507   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13508   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13509   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13510
13511   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13512   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13513   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13514
13515   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13516   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13517
13518   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13519   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13520 }
13521
13522 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13523   assert(Subtarget->isTargetWin64() && "Unexpected target");
13524   EVT VT = Op.getValueType();
13525   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13526          "Unexpected return type for lowering");
13527
13528   RTLIB::Libcall LC;
13529   bool isSigned;
13530   switch (Op->getOpcode()) {
13531   default: llvm_unreachable("Unexpected request for libcall!");
13532   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13533   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13534   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13535   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13536   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13537   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13538   }
13539
13540   SDLoc dl(Op);
13541   SDValue InChain = DAG.getEntryNode();
13542
13543   TargetLowering::ArgListTy Args;
13544   TargetLowering::ArgListEntry Entry;
13545   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13546     EVT ArgVT = Op->getOperand(i).getValueType();
13547     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13548            "Unexpected argument type for lowering");
13549     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13550     Entry.Node = StackPtr;
13551     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13552                            false, false, 16);
13553     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13554     Entry.Ty = PointerType::get(ArgTy,0);
13555     Entry.isSExt = false;
13556     Entry.isZExt = false;
13557     Args.push_back(Entry);
13558   }
13559
13560   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13561                                          getPointerTy());
13562
13563   TargetLowering::CallLoweringInfo CLI(DAG);
13564   CLI.setDebugLoc(dl).setChain(InChain)
13565     .setCallee(getLibcallCallingConv(LC),
13566                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13567                Callee, &Args, 0)
13568     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13569
13570   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13571   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13572 }
13573
13574 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13575                              SelectionDAG &DAG) {
13576   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13577   EVT VT = Op0.getValueType();
13578   SDLoc dl(Op);
13579
13580   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13581          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13582
13583   // Get the high parts.
13584   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13585   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13586   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13587
13588   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13589   // ints.
13590   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13591   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13592   unsigned Opcode =
13593       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13594   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13595                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13596   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13597                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13598
13599   // Shuffle it back into the right order.
13600   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13601   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13602   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13603   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13604
13605   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13606   // unsigned multiply.
13607   if (IsSigned && !Subtarget->hasSSE41()) {
13608     SDValue ShAmt =
13609         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13610     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13611                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13612     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13613                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13614
13615     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13616     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13617   }
13618
13619   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13620 }
13621
13622 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13623                                          const X86Subtarget *Subtarget) {
13624   MVT VT = Op.getSimpleValueType();
13625   SDLoc dl(Op);
13626   SDValue R = Op.getOperand(0);
13627   SDValue Amt = Op.getOperand(1);
13628
13629   // Optimize shl/srl/sra with constant shift amount.
13630   if (isSplatVector(Amt.getNode())) {
13631     SDValue SclrAmt = Amt->getOperand(0);
13632     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13633       uint64_t ShiftAmt = C->getZExtValue();
13634
13635       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13636           (Subtarget->hasInt256() &&
13637            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13638           (Subtarget->hasAVX512() &&
13639            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13640         if (Op.getOpcode() == ISD::SHL)
13641           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13642                                             DAG);
13643         if (Op.getOpcode() == ISD::SRL)
13644           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13645                                             DAG);
13646         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13647           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13648                                             DAG);
13649       }
13650
13651       if (VT == MVT::v16i8) {
13652         if (Op.getOpcode() == ISD::SHL) {
13653           // Make a large shift.
13654           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13655                                                    MVT::v8i16, R, ShiftAmt,
13656                                                    DAG);
13657           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13658           // Zero out the rightmost bits.
13659           SmallVector<SDValue, 16> V(16,
13660                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13661                                                      MVT::i8));
13662           return DAG.getNode(ISD::AND, dl, VT, SHL,
13663                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13664         }
13665         if (Op.getOpcode() == ISD::SRL) {
13666           // Make a large shift.
13667           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13668                                                    MVT::v8i16, R, ShiftAmt,
13669                                                    DAG);
13670           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13671           // Zero out the leftmost bits.
13672           SmallVector<SDValue, 16> V(16,
13673                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13674                                                      MVT::i8));
13675           return DAG.getNode(ISD::AND, dl, VT, SRL,
13676                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13677         }
13678         if (Op.getOpcode() == ISD::SRA) {
13679           if (ShiftAmt == 7) {
13680             // R s>> 7  ===  R s< 0
13681             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13682             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13683           }
13684
13685           // R s>> a === ((R u>> a) ^ m) - m
13686           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13687           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13688                                                          MVT::i8));
13689           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13690           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13691           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13692           return Res;
13693         }
13694         llvm_unreachable("Unknown shift opcode.");
13695       }
13696
13697       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13698         if (Op.getOpcode() == ISD::SHL) {
13699           // Make a large shift.
13700           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13701                                                    MVT::v16i16, R, ShiftAmt,
13702                                                    DAG);
13703           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13704           // Zero out the rightmost bits.
13705           SmallVector<SDValue, 32> V(32,
13706                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13707                                                      MVT::i8));
13708           return DAG.getNode(ISD::AND, dl, VT, SHL,
13709                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13710         }
13711         if (Op.getOpcode() == ISD::SRL) {
13712           // Make a large shift.
13713           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13714                                                    MVT::v16i16, R, ShiftAmt,
13715                                                    DAG);
13716           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13717           // Zero out the leftmost bits.
13718           SmallVector<SDValue, 32> V(32,
13719                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13720                                                      MVT::i8));
13721           return DAG.getNode(ISD::AND, dl, VT, SRL,
13722                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13723         }
13724         if (Op.getOpcode() == ISD::SRA) {
13725           if (ShiftAmt == 7) {
13726             // R s>> 7  ===  R s< 0
13727             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13728             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13729           }
13730
13731           // R s>> a === ((R u>> a) ^ m) - m
13732           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13733           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13734                                                          MVT::i8));
13735           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13736           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13737           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13738           return Res;
13739         }
13740         llvm_unreachable("Unknown shift opcode.");
13741       }
13742     }
13743   }
13744
13745   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13746   if (!Subtarget->is64Bit() &&
13747       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13748       Amt.getOpcode() == ISD::BITCAST &&
13749       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13750     Amt = Amt.getOperand(0);
13751     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13752                      VT.getVectorNumElements();
13753     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13754     uint64_t ShiftAmt = 0;
13755     for (unsigned i = 0; i != Ratio; ++i) {
13756       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13757       if (!C)
13758         return SDValue();
13759       // 6 == Log2(64)
13760       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13761     }
13762     // Check remaining shift amounts.
13763     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13764       uint64_t ShAmt = 0;
13765       for (unsigned j = 0; j != Ratio; ++j) {
13766         ConstantSDNode *C =
13767           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13768         if (!C)
13769           return SDValue();
13770         // 6 == Log2(64)
13771         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13772       }
13773       if (ShAmt != ShiftAmt)
13774         return SDValue();
13775     }
13776     switch (Op.getOpcode()) {
13777     default:
13778       llvm_unreachable("Unknown shift opcode!");
13779     case ISD::SHL:
13780       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13781                                         DAG);
13782     case ISD::SRL:
13783       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13784                                         DAG);
13785     case ISD::SRA:
13786       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13787                                         DAG);
13788     }
13789   }
13790
13791   return SDValue();
13792 }
13793
13794 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13795                                         const X86Subtarget* Subtarget) {
13796   MVT VT = Op.getSimpleValueType();
13797   SDLoc dl(Op);
13798   SDValue R = Op.getOperand(0);
13799   SDValue Amt = Op.getOperand(1);
13800
13801   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13802       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13803       (Subtarget->hasInt256() &&
13804        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13805         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13806        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13807     SDValue BaseShAmt;
13808     EVT EltVT = VT.getVectorElementType();
13809
13810     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13811       unsigned NumElts = VT.getVectorNumElements();
13812       unsigned i, j;
13813       for (i = 0; i != NumElts; ++i) {
13814         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13815           continue;
13816         break;
13817       }
13818       for (j = i; j != NumElts; ++j) {
13819         SDValue Arg = Amt.getOperand(j);
13820         if (Arg.getOpcode() == ISD::UNDEF) continue;
13821         if (Arg != Amt.getOperand(i))
13822           break;
13823       }
13824       if (i != NumElts && j == NumElts)
13825         BaseShAmt = Amt.getOperand(i);
13826     } else {
13827       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13828         Amt = Amt.getOperand(0);
13829       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13830                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13831         SDValue InVec = Amt.getOperand(0);
13832         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13833           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13834           unsigned i = 0;
13835           for (; i != NumElts; ++i) {
13836             SDValue Arg = InVec.getOperand(i);
13837             if (Arg.getOpcode() == ISD::UNDEF) continue;
13838             BaseShAmt = Arg;
13839             break;
13840           }
13841         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13842            if (ConstantSDNode *C =
13843                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13844              unsigned SplatIdx =
13845                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13846              if (C->getZExtValue() == SplatIdx)
13847                BaseShAmt = InVec.getOperand(1);
13848            }
13849         }
13850         if (!BaseShAmt.getNode())
13851           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13852                                   DAG.getIntPtrConstant(0));
13853       }
13854     }
13855
13856     if (BaseShAmt.getNode()) {
13857       if (EltVT.bitsGT(MVT::i32))
13858         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13859       else if (EltVT.bitsLT(MVT::i32))
13860         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13861
13862       switch (Op.getOpcode()) {
13863       default:
13864         llvm_unreachable("Unknown shift opcode!");
13865       case ISD::SHL:
13866         switch (VT.SimpleTy) {
13867         default: return SDValue();
13868         case MVT::v2i64:
13869         case MVT::v4i32:
13870         case MVT::v8i16:
13871         case MVT::v4i64:
13872         case MVT::v8i32:
13873         case MVT::v16i16:
13874         case MVT::v16i32:
13875         case MVT::v8i64:
13876           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13877         }
13878       case ISD::SRA:
13879         switch (VT.SimpleTy) {
13880         default: return SDValue();
13881         case MVT::v4i32:
13882         case MVT::v8i16:
13883         case MVT::v8i32:
13884         case MVT::v16i16:
13885         case MVT::v16i32:
13886         case MVT::v8i64:
13887           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13888         }
13889       case ISD::SRL:
13890         switch (VT.SimpleTy) {
13891         default: return SDValue();
13892         case MVT::v2i64:
13893         case MVT::v4i32:
13894         case MVT::v8i16:
13895         case MVT::v4i64:
13896         case MVT::v8i32:
13897         case MVT::v16i16:
13898         case MVT::v16i32:
13899         case MVT::v8i64:
13900           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13901         }
13902       }
13903     }
13904   }
13905
13906   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13907   if (!Subtarget->is64Bit() &&
13908       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13909       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13910       Amt.getOpcode() == ISD::BITCAST &&
13911       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13912     Amt = Amt.getOperand(0);
13913     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13914                      VT.getVectorNumElements();
13915     std::vector<SDValue> Vals(Ratio);
13916     for (unsigned i = 0; i != Ratio; ++i)
13917       Vals[i] = Amt.getOperand(i);
13918     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13919       for (unsigned j = 0; j != Ratio; ++j)
13920         if (Vals[j] != Amt.getOperand(i + j))
13921           return SDValue();
13922     }
13923     switch (Op.getOpcode()) {
13924     default:
13925       llvm_unreachable("Unknown shift opcode!");
13926     case ISD::SHL:
13927       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13928     case ISD::SRL:
13929       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13930     case ISD::SRA:
13931       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13932     }
13933   }
13934
13935   return SDValue();
13936 }
13937
13938 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13939                           SelectionDAG &DAG) {
13940
13941   MVT VT = Op.getSimpleValueType();
13942   SDLoc dl(Op);
13943   SDValue R = Op.getOperand(0);
13944   SDValue Amt = Op.getOperand(1);
13945   SDValue V;
13946
13947   if (!Subtarget->hasSSE2())
13948     return SDValue();
13949
13950   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13951   if (V.getNode())
13952     return V;
13953
13954   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13955   if (V.getNode())
13956       return V;
13957
13958   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13959     return Op;
13960   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13961   if (Subtarget->hasInt256()) {
13962     if (Op.getOpcode() == ISD::SRL &&
13963         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13964          VT == MVT::v4i64 || VT == MVT::v8i32))
13965       return Op;
13966     if (Op.getOpcode() == ISD::SHL &&
13967         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13968          VT == MVT::v4i64 || VT == MVT::v8i32))
13969       return Op;
13970     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13971       return Op;
13972   }
13973
13974   // If possible, lower this packed shift into a vector multiply instead of
13975   // expanding it into a sequence of scalar shifts.
13976   // Do this only if the vector shift count is a constant build_vector.
13977   if (Op.getOpcode() == ISD::SHL && 
13978       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13979        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13980       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13981     SmallVector<SDValue, 8> Elts;
13982     EVT SVT = VT.getScalarType();
13983     unsigned SVTBits = SVT.getSizeInBits();
13984     const APInt &One = APInt(SVTBits, 1);
13985     unsigned NumElems = VT.getVectorNumElements();
13986
13987     for (unsigned i=0; i !=NumElems; ++i) {
13988       SDValue Op = Amt->getOperand(i);
13989       if (Op->getOpcode() == ISD::UNDEF) {
13990         Elts.push_back(Op);
13991         continue;
13992       }
13993
13994       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13995       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13996       uint64_t ShAmt = C.getZExtValue();
13997       if (ShAmt >= SVTBits) {
13998         Elts.push_back(DAG.getUNDEF(SVT));
13999         continue;
14000       }
14001       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14002     }
14003     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14004     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14005   }
14006
14007   // Lower SHL with variable shift amount.
14008   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14009     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14010
14011     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14012     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14013     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14014     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14015   }
14016
14017   // If possible, lower this shift as a sequence of two shifts by
14018   // constant plus a MOVSS/MOVSD instead of scalarizing it.
14019   // Example:
14020   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14021   //
14022   // Could be rewritten as:
14023   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14024   //
14025   // The advantage is that the two shifts from the example would be
14026   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14027   // the vector shift into four scalar shifts plus four pairs of vector
14028   // insert/extract.
14029   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14030       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14031     unsigned TargetOpcode = X86ISD::MOVSS;
14032     bool CanBeSimplified;
14033     // The splat value for the first packed shift (the 'X' from the example).
14034     SDValue Amt1 = Amt->getOperand(0);
14035     // The splat value for the second packed shift (the 'Y' from the example).
14036     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14037                                         Amt->getOperand(2);
14038
14039     // See if it is possible to replace this node with a sequence of
14040     // two shifts followed by a MOVSS/MOVSD
14041     if (VT == MVT::v4i32) {
14042       // Check if it is legal to use a MOVSS.
14043       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14044                         Amt2 == Amt->getOperand(3);
14045       if (!CanBeSimplified) {
14046         // Otherwise, check if we can still simplify this node using a MOVSD.
14047         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14048                           Amt->getOperand(2) == Amt->getOperand(3);
14049         TargetOpcode = X86ISD::MOVSD;
14050         Amt2 = Amt->getOperand(2);
14051       }
14052     } else {
14053       // Do similar checks for the case where the machine value type
14054       // is MVT::v8i16.
14055       CanBeSimplified = Amt1 == Amt->getOperand(1);
14056       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14057         CanBeSimplified = Amt2 == Amt->getOperand(i);
14058
14059       if (!CanBeSimplified) {
14060         TargetOpcode = X86ISD::MOVSD;
14061         CanBeSimplified = true;
14062         Amt2 = Amt->getOperand(4);
14063         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14064           CanBeSimplified = Amt1 == Amt->getOperand(i);
14065         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14066           CanBeSimplified = Amt2 == Amt->getOperand(j);
14067       }
14068     }
14069     
14070     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14071         isa<ConstantSDNode>(Amt2)) {
14072       // Replace this node with two shifts followed by a MOVSS/MOVSD.
14073       EVT CastVT = MVT::v4i32;
14074       SDValue Splat1 = 
14075         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14076       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14077       SDValue Splat2 = 
14078         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14079       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14080       if (TargetOpcode == X86ISD::MOVSD)
14081         CastVT = MVT::v2i64;
14082       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14083       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14084       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14085                                             BitCast1, DAG);
14086       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14087     }
14088   }
14089
14090   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14091     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14092
14093     // a = a << 5;
14094     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14095     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14096
14097     // Turn 'a' into a mask suitable for VSELECT
14098     SDValue VSelM = DAG.getConstant(0x80, VT);
14099     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14100     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14101
14102     SDValue CM1 = DAG.getConstant(0x0f, VT);
14103     SDValue CM2 = DAG.getConstant(0x3f, VT);
14104
14105     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14106     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14107     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14108     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14109     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14110
14111     // a += a
14112     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14113     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14114     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14115
14116     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14117     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14118     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14119     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14120     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14121
14122     // a += a
14123     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14124     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14125     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14126
14127     // return VSELECT(r, r+r, a);
14128     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14129                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14130     return R;
14131   }
14132
14133   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14134   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14135   // solution better.
14136   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14137     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14138     unsigned ExtOpc =
14139         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14140     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14141     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14142     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14143                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14144     }
14145
14146   // Decompose 256-bit shifts into smaller 128-bit shifts.
14147   if (VT.is256BitVector()) {
14148     unsigned NumElems = VT.getVectorNumElements();
14149     MVT EltVT = VT.getVectorElementType();
14150     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14151
14152     // Extract the two vectors
14153     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14154     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14155
14156     // Recreate the shift amount vectors
14157     SDValue Amt1, Amt2;
14158     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14159       // Constant shift amount
14160       SmallVector<SDValue, 4> Amt1Csts;
14161       SmallVector<SDValue, 4> Amt2Csts;
14162       for (unsigned i = 0; i != NumElems/2; ++i)
14163         Amt1Csts.push_back(Amt->getOperand(i));
14164       for (unsigned i = NumElems/2; i != NumElems; ++i)
14165         Amt2Csts.push_back(Amt->getOperand(i));
14166
14167       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14168       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14169     } else {
14170       // Variable shift amount
14171       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14172       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14173     }
14174
14175     // Issue new vector shifts for the smaller types
14176     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14177     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14178
14179     // Concatenate the result back
14180     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14181   }
14182
14183   return SDValue();
14184 }
14185
14186 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14187   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14188   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14189   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14190   // has only one use.
14191   SDNode *N = Op.getNode();
14192   SDValue LHS = N->getOperand(0);
14193   SDValue RHS = N->getOperand(1);
14194   unsigned BaseOp = 0;
14195   unsigned Cond = 0;
14196   SDLoc DL(Op);
14197   switch (Op.getOpcode()) {
14198   default: llvm_unreachable("Unknown ovf instruction!");
14199   case ISD::SADDO:
14200     // A subtract of one will be selected as a INC. Note that INC doesn't
14201     // set CF, so we can't do this for UADDO.
14202     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14203       if (C->isOne()) {
14204         BaseOp = X86ISD::INC;
14205         Cond = X86::COND_O;
14206         break;
14207       }
14208     BaseOp = X86ISD::ADD;
14209     Cond = X86::COND_O;
14210     break;
14211   case ISD::UADDO:
14212     BaseOp = X86ISD::ADD;
14213     Cond = X86::COND_B;
14214     break;
14215   case ISD::SSUBO:
14216     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14217     // set CF, so we can't do this for USUBO.
14218     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14219       if (C->isOne()) {
14220         BaseOp = X86ISD::DEC;
14221         Cond = X86::COND_O;
14222         break;
14223       }
14224     BaseOp = X86ISD::SUB;
14225     Cond = X86::COND_O;
14226     break;
14227   case ISD::USUBO:
14228     BaseOp = X86ISD::SUB;
14229     Cond = X86::COND_B;
14230     break;
14231   case ISD::SMULO:
14232     BaseOp = X86ISD::SMUL;
14233     Cond = X86::COND_O;
14234     break;
14235   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14236     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14237                                  MVT::i32);
14238     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14239
14240     SDValue SetCC =
14241       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14242                   DAG.getConstant(X86::COND_O, MVT::i32),
14243                   SDValue(Sum.getNode(), 2));
14244
14245     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14246   }
14247   }
14248
14249   // Also sets EFLAGS.
14250   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14251   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14252
14253   SDValue SetCC =
14254     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14255                 DAG.getConstant(Cond, MVT::i32),
14256                 SDValue(Sum.getNode(), 1));
14257
14258   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14259 }
14260
14261 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14262                                                   SelectionDAG &DAG) const {
14263   SDLoc dl(Op);
14264   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14265   MVT VT = Op.getSimpleValueType();
14266
14267   if (!Subtarget->hasSSE2() || !VT.isVector())
14268     return SDValue();
14269
14270   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14271                       ExtraVT.getScalarType().getSizeInBits();
14272
14273   switch (VT.SimpleTy) {
14274     default: return SDValue();
14275     case MVT::v8i32:
14276     case MVT::v16i16:
14277       if (!Subtarget->hasFp256())
14278         return SDValue();
14279       if (!Subtarget->hasInt256()) {
14280         // needs to be split
14281         unsigned NumElems = VT.getVectorNumElements();
14282
14283         // Extract the LHS vectors
14284         SDValue LHS = Op.getOperand(0);
14285         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14286         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14287
14288         MVT EltVT = VT.getVectorElementType();
14289         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14290
14291         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14292         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14293         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14294                                    ExtraNumElems/2);
14295         SDValue Extra = DAG.getValueType(ExtraVT);
14296
14297         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14298         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14299
14300         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14301       }
14302       // fall through
14303     case MVT::v4i32:
14304     case MVT::v8i16: {
14305       SDValue Op0 = Op.getOperand(0);
14306       SDValue Op00 = Op0.getOperand(0);
14307       SDValue Tmp1;
14308       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14309       if (Op0.getOpcode() == ISD::BITCAST &&
14310           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14311         // (sext (vzext x)) -> (vsext x)
14312         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14313         if (Tmp1.getNode()) {
14314           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14315           // This folding is only valid when the in-reg type is a vector of i8,
14316           // i16, or i32.
14317           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14318               ExtraEltVT == MVT::i32) {
14319             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14320             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14321                    "This optimization is invalid without a VZEXT.");
14322             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14323           }
14324           Op0 = Tmp1;
14325         }
14326       }
14327
14328       // If the above didn't work, then just use Shift-Left + Shift-Right.
14329       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14330                                         DAG);
14331       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14332                                         DAG);
14333     }
14334   }
14335 }
14336
14337 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14338                                  SelectionDAG &DAG) {
14339   SDLoc dl(Op);
14340   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14341     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14342   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14343     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14344
14345   // The only fence that needs an instruction is a sequentially-consistent
14346   // cross-thread fence.
14347   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14348     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14349     // no-sse2). There isn't any reason to disable it if the target processor
14350     // supports it.
14351     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14352       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14353
14354     SDValue Chain = Op.getOperand(0);
14355     SDValue Zero = DAG.getConstant(0, MVT::i32);
14356     SDValue Ops[] = {
14357       DAG.getRegister(X86::ESP, MVT::i32), // Base
14358       DAG.getTargetConstant(1, MVT::i8),   // Scale
14359       DAG.getRegister(0, MVT::i32),        // Index
14360       DAG.getTargetConstant(0, MVT::i32),  // Disp
14361       DAG.getRegister(0, MVT::i32),        // Segment.
14362       Zero,
14363       Chain
14364     };
14365     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14366     return SDValue(Res, 0);
14367   }
14368
14369   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14370   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14371 }
14372
14373 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14374                              SelectionDAG &DAG) {
14375   MVT T = Op.getSimpleValueType();
14376   SDLoc DL(Op);
14377   unsigned Reg = 0;
14378   unsigned size = 0;
14379   switch(T.SimpleTy) {
14380   default: llvm_unreachable("Invalid value type!");
14381   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14382   case MVT::i16: Reg = X86::AX;  size = 2; break;
14383   case MVT::i32: Reg = X86::EAX; size = 4; break;
14384   case MVT::i64:
14385     assert(Subtarget->is64Bit() && "Node not type legal!");
14386     Reg = X86::RAX; size = 8;
14387     break;
14388   }
14389   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14390                                     Op.getOperand(2), SDValue());
14391   SDValue Ops[] = { cpIn.getValue(0),
14392                     Op.getOperand(1),
14393                     Op.getOperand(3),
14394                     DAG.getTargetConstant(size, MVT::i8),
14395                     cpIn.getValue(1) };
14396   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14397   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14398   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14399                                            Ops, T, MMO);
14400   SDValue cpOut =
14401     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14402   return cpOut;
14403 }
14404
14405 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14406                             SelectionDAG &DAG) {
14407   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14408   MVT DstVT = Op.getSimpleValueType();
14409
14410   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14411     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14412     if (DstVT != MVT::f64)
14413       // This conversion needs to be expanded.
14414       return SDValue();
14415
14416     SDValue InVec = Op->getOperand(0);
14417     SDLoc dl(Op);
14418     unsigned NumElts = SrcVT.getVectorNumElements();
14419     EVT SVT = SrcVT.getVectorElementType();
14420
14421     // Widen the vector in input in the case of MVT::v2i32.
14422     // Example: from MVT::v2i32 to MVT::v4i32.
14423     SmallVector<SDValue, 16> Elts;
14424     for (unsigned i = 0, e = NumElts; i != e; ++i)
14425       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14426                                  DAG.getIntPtrConstant(i)));
14427
14428     // Explicitly mark the extra elements as Undef.
14429     SDValue Undef = DAG.getUNDEF(SVT);
14430     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14431       Elts.push_back(Undef);
14432
14433     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14434     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14435     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14436     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14437                        DAG.getIntPtrConstant(0));
14438   }
14439
14440   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14441          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14442   assert((DstVT == MVT::i64 ||
14443           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14444          "Unexpected custom BITCAST");
14445   // i64 <=> MMX conversions are Legal.
14446   if (SrcVT==MVT::i64 && DstVT.isVector())
14447     return Op;
14448   if (DstVT==MVT::i64 && SrcVT.isVector())
14449     return Op;
14450   // MMX <=> MMX conversions are Legal.
14451   if (SrcVT.isVector() && DstVT.isVector())
14452     return Op;
14453   // All other conversions need to be expanded.
14454   return SDValue();
14455 }
14456
14457 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14458   SDNode *Node = Op.getNode();
14459   SDLoc dl(Node);
14460   EVT T = Node->getValueType(0);
14461   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14462                               DAG.getConstant(0, T), Node->getOperand(2));
14463   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14464                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14465                        Node->getOperand(0),
14466                        Node->getOperand(1), negOp,
14467                        cast<AtomicSDNode>(Node)->getMemOperand(),
14468                        cast<AtomicSDNode>(Node)->getOrdering(),
14469                        cast<AtomicSDNode>(Node)->getSynchScope());
14470 }
14471
14472 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14473   SDNode *Node = Op.getNode();
14474   SDLoc dl(Node);
14475   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14476
14477   // Convert seq_cst store -> xchg
14478   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14479   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14480   //        (The only way to get a 16-byte store is cmpxchg16b)
14481   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14482   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14483       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14484     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14485                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14486                                  Node->getOperand(0),
14487                                  Node->getOperand(1), Node->getOperand(2),
14488                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14489                                  cast<AtomicSDNode>(Node)->getOrdering(),
14490                                  cast<AtomicSDNode>(Node)->getSynchScope());
14491     return Swap.getValue(1);
14492   }
14493   // Other atomic stores have a simple pattern.
14494   return Op;
14495 }
14496
14497 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14498   EVT VT = Op.getNode()->getSimpleValueType(0);
14499
14500   // Let legalize expand this if it isn't a legal type yet.
14501   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14502     return SDValue();
14503
14504   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14505
14506   unsigned Opc;
14507   bool ExtraOp = false;
14508   switch (Op.getOpcode()) {
14509   default: llvm_unreachable("Invalid code");
14510   case ISD::ADDC: Opc = X86ISD::ADD; break;
14511   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14512   case ISD::SUBC: Opc = X86ISD::SUB; break;
14513   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14514   }
14515
14516   if (!ExtraOp)
14517     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14518                        Op.getOperand(1));
14519   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14520                      Op.getOperand(1), Op.getOperand(2));
14521 }
14522
14523 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14524                             SelectionDAG &DAG) {
14525   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14526
14527   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14528   // which returns the values as { float, float } (in XMM0) or
14529   // { double, double } (which is returned in XMM0, XMM1).
14530   SDLoc dl(Op);
14531   SDValue Arg = Op.getOperand(0);
14532   EVT ArgVT = Arg.getValueType();
14533   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14534
14535   TargetLowering::ArgListTy Args;
14536   TargetLowering::ArgListEntry Entry;
14537
14538   Entry.Node = Arg;
14539   Entry.Ty = ArgTy;
14540   Entry.isSExt = false;
14541   Entry.isZExt = false;
14542   Args.push_back(Entry);
14543
14544   bool isF64 = ArgVT == MVT::f64;
14545   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14546   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14547   // the results are returned via SRet in memory.
14548   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14550   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14551
14552   Type *RetTy = isF64
14553     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14554     : (Type*)VectorType::get(ArgTy, 4);
14555
14556   TargetLowering::CallLoweringInfo CLI(DAG);
14557   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14558     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14559
14560   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14561
14562   if (isF64)
14563     // Returned in xmm0 and xmm1.
14564     return CallResult.first;
14565
14566   // Returned in bits 0:31 and 32:64 xmm0.
14567   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14568                                CallResult.first, DAG.getIntPtrConstant(0));
14569   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14570                                CallResult.first, DAG.getIntPtrConstant(1));
14571   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14572   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14573 }
14574
14575 /// LowerOperation - Provide custom lowering hooks for some operations.
14576 ///
14577 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14578   switch (Op.getOpcode()) {
14579   default: llvm_unreachable("Should not custom lower this!");
14580   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14581   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14582   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14583   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14584   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14585   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14586   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14587   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14588   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14589   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14590   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14591   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14592   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14593   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14594   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14595   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14596   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14597   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14598   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14599   case ISD::SHL_PARTS:
14600   case ISD::SRA_PARTS:
14601   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14602   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14603   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14604   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14605   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14606   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14607   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14608   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14609   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14610   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14611   case ISD::FABS:               return LowerFABS(Op, DAG);
14612   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14613   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14614   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14615   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14616   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14617   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14618   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14619   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14620   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14621   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14622   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14623   case ISD::INTRINSIC_VOID:
14624   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14625   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14626   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14627   case ISD::FRAME_TO_ARGS_OFFSET:
14628                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14629   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14630   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14631   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14632   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14633   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14634   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14635   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14636   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14637   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14638   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14639   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14640   case ISD::UMUL_LOHI:
14641   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14642   case ISD::SRA:
14643   case ISD::SRL:
14644   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14645   case ISD::SADDO:
14646   case ISD::UADDO:
14647   case ISD::SSUBO:
14648   case ISD::USUBO:
14649   case ISD::SMULO:
14650   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14651   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14652   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14653   case ISD::ADDC:
14654   case ISD::ADDE:
14655   case ISD::SUBC:
14656   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14657   case ISD::ADD:                return LowerADD(Op, DAG);
14658   case ISD::SUB:                return LowerSUB(Op, DAG);
14659   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14660   }
14661 }
14662
14663 static void ReplaceATOMIC_LOAD(SDNode *Node,
14664                                   SmallVectorImpl<SDValue> &Results,
14665                                   SelectionDAG &DAG) {
14666   SDLoc dl(Node);
14667   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14668
14669   // Convert wide load -> cmpxchg8b/cmpxchg16b
14670   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14671   //        (The only way to get a 16-byte load is cmpxchg16b)
14672   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14673   SDValue Zero = DAG.getConstant(0, VT);
14674   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14675                                Node->getOperand(0),
14676                                Node->getOperand(1), Zero, Zero,
14677                                cast<AtomicSDNode>(Node)->getMemOperand(),
14678                                cast<AtomicSDNode>(Node)->getOrdering(),
14679                                cast<AtomicSDNode>(Node)->getOrdering(),
14680                                cast<AtomicSDNode>(Node)->getSynchScope());
14681   Results.push_back(Swap.getValue(0));
14682   Results.push_back(Swap.getValue(1));
14683 }
14684
14685 static void
14686 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14687                         SelectionDAG &DAG, unsigned NewOp) {
14688   SDLoc dl(Node);
14689   assert (Node->getValueType(0) == MVT::i64 &&
14690           "Only know how to expand i64 atomics");
14691
14692   SDValue Chain = Node->getOperand(0);
14693   SDValue In1 = Node->getOperand(1);
14694   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14695                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14696   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14697                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14698   SDValue Ops[] = { Chain, In1, In2L, In2H };
14699   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14700   SDValue Result =
14701     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14702                             cast<MemSDNode>(Node)->getMemOperand());
14703   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14704   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14705   Results.push_back(Result.getValue(2));
14706 }
14707
14708 /// ReplaceNodeResults - Replace a node with an illegal result type
14709 /// with a new node built out of custom code.
14710 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14711                                            SmallVectorImpl<SDValue>&Results,
14712                                            SelectionDAG &DAG) const {
14713   SDLoc dl(N);
14714   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14715   switch (N->getOpcode()) {
14716   default:
14717     llvm_unreachable("Do not know how to custom type legalize this operation!");
14718   case ISD::SIGN_EXTEND_INREG:
14719   case ISD::ADDC:
14720   case ISD::ADDE:
14721   case ISD::SUBC:
14722   case ISD::SUBE:
14723     // We don't want to expand or promote these.
14724     return;
14725   case ISD::SDIV:
14726   case ISD::UDIV:
14727   case ISD::SREM:
14728   case ISD::UREM:
14729   case ISD::SDIVREM:
14730   case ISD::UDIVREM: {
14731     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14732     Results.push_back(V);
14733     return;
14734   }
14735   case ISD::FP_TO_SINT:
14736   case ISD::FP_TO_UINT: {
14737     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14738
14739     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14740       return;
14741
14742     std::pair<SDValue,SDValue> Vals =
14743         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14744     SDValue FIST = Vals.first, StackSlot = Vals.second;
14745     if (FIST.getNode()) {
14746       EVT VT = N->getValueType(0);
14747       // Return a load from the stack slot.
14748       if (StackSlot.getNode())
14749         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14750                                       MachinePointerInfo(),
14751                                       false, false, false, 0));
14752       else
14753         Results.push_back(FIST);
14754     }
14755     return;
14756   }
14757   case ISD::UINT_TO_FP: {
14758     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14759     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14760         N->getValueType(0) != MVT::v2f32)
14761       return;
14762     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14763                                  N->getOperand(0));
14764     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14765                                      MVT::f64);
14766     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14767     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14768                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14769     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14770     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14771     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14772     return;
14773   }
14774   case ISD::FP_ROUND: {
14775     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14776         return;
14777     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14778     Results.push_back(V);
14779     return;
14780   }
14781   case ISD::INTRINSIC_W_CHAIN: {
14782     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14783     switch (IntNo) {
14784     default : llvm_unreachable("Do not know how to custom type "
14785                                "legalize this intrinsic operation!");
14786     case Intrinsic::x86_rdtsc:
14787       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14788                                      Results);
14789     case Intrinsic::x86_rdtscp:
14790       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14791                                      Results);
14792     }
14793   }
14794   case ISD::READCYCLECOUNTER: {
14795     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14796                                    Results);
14797   }
14798   case ISD::ATOMIC_CMP_SWAP: {
14799     EVT T = N->getValueType(0);
14800     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14801     bool Regs64bit = T == MVT::i128;
14802     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14803     SDValue cpInL, cpInH;
14804     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14805                         DAG.getConstant(0, HalfT));
14806     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14807                         DAG.getConstant(1, HalfT));
14808     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14809                              Regs64bit ? X86::RAX : X86::EAX,
14810                              cpInL, SDValue());
14811     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14812                              Regs64bit ? X86::RDX : X86::EDX,
14813                              cpInH, cpInL.getValue(1));
14814     SDValue swapInL, swapInH;
14815     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14816                           DAG.getConstant(0, HalfT));
14817     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14818                           DAG.getConstant(1, HalfT));
14819     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14820                                Regs64bit ? X86::RBX : X86::EBX,
14821                                swapInL, cpInH.getValue(1));
14822     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14823                                Regs64bit ? X86::RCX : X86::ECX,
14824                                swapInH, swapInL.getValue(1));
14825     SDValue Ops[] = { swapInH.getValue(0),
14826                       N->getOperand(1),
14827                       swapInH.getValue(1) };
14828     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14829     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14830     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14831                                   X86ISD::LCMPXCHG8_DAG;
14832     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14833     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14834                                         Regs64bit ? X86::RAX : X86::EAX,
14835                                         HalfT, Result.getValue(1));
14836     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14837                                         Regs64bit ? X86::RDX : X86::EDX,
14838                                         HalfT, cpOutL.getValue(2));
14839     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14840     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14841     Results.push_back(cpOutH.getValue(1));
14842     return;
14843   }
14844   case ISD::ATOMIC_LOAD_ADD:
14845   case ISD::ATOMIC_LOAD_AND:
14846   case ISD::ATOMIC_LOAD_NAND:
14847   case ISD::ATOMIC_LOAD_OR:
14848   case ISD::ATOMIC_LOAD_SUB:
14849   case ISD::ATOMIC_LOAD_XOR:
14850   case ISD::ATOMIC_LOAD_MAX:
14851   case ISD::ATOMIC_LOAD_MIN:
14852   case ISD::ATOMIC_LOAD_UMAX:
14853   case ISD::ATOMIC_LOAD_UMIN:
14854   case ISD::ATOMIC_SWAP: {
14855     unsigned Opc;
14856     switch (N->getOpcode()) {
14857     default: llvm_unreachable("Unexpected opcode");
14858     case ISD::ATOMIC_LOAD_ADD:
14859       Opc = X86ISD::ATOMADD64_DAG;
14860       break;
14861     case ISD::ATOMIC_LOAD_AND:
14862       Opc = X86ISD::ATOMAND64_DAG;
14863       break;
14864     case ISD::ATOMIC_LOAD_NAND:
14865       Opc = X86ISD::ATOMNAND64_DAG;
14866       break;
14867     case ISD::ATOMIC_LOAD_OR:
14868       Opc = X86ISD::ATOMOR64_DAG;
14869       break;
14870     case ISD::ATOMIC_LOAD_SUB:
14871       Opc = X86ISD::ATOMSUB64_DAG;
14872       break;
14873     case ISD::ATOMIC_LOAD_XOR:
14874       Opc = X86ISD::ATOMXOR64_DAG;
14875       break;
14876     case ISD::ATOMIC_LOAD_MAX:
14877       Opc = X86ISD::ATOMMAX64_DAG;
14878       break;
14879     case ISD::ATOMIC_LOAD_MIN:
14880       Opc = X86ISD::ATOMMIN64_DAG;
14881       break;
14882     case ISD::ATOMIC_LOAD_UMAX:
14883       Opc = X86ISD::ATOMUMAX64_DAG;
14884       break;
14885     case ISD::ATOMIC_LOAD_UMIN:
14886       Opc = X86ISD::ATOMUMIN64_DAG;
14887       break;
14888     case ISD::ATOMIC_SWAP:
14889       Opc = X86ISD::ATOMSWAP64_DAG;
14890       break;
14891     }
14892     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14893     return;
14894   }
14895   case ISD::ATOMIC_LOAD: {
14896     ReplaceATOMIC_LOAD(N, Results, DAG);
14897     return;
14898   }
14899   case ISD::BITCAST: {
14900     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14901     EVT DstVT = N->getValueType(0);
14902     EVT SrcVT = N->getOperand(0)->getValueType(0);
14903
14904     if (SrcVT != MVT::f64 ||
14905         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14906       return;
14907
14908     unsigned NumElts = DstVT.getVectorNumElements();
14909     EVT SVT = DstVT.getVectorElementType();
14910     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14911     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14912                                    MVT::v2f64, N->getOperand(0));
14913     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14914
14915     SmallVector<SDValue, 8> Elts;
14916     for (unsigned i = 0, e = NumElts; i != e; ++i)
14917       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14918                                    ToVecInt, DAG.getIntPtrConstant(i)));
14919
14920     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14921   }
14922   }
14923 }
14924
14925 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14926   switch (Opcode) {
14927   default: return nullptr;
14928   case X86ISD::BSF:                return "X86ISD::BSF";
14929   case X86ISD::BSR:                return "X86ISD::BSR";
14930   case X86ISD::SHLD:               return "X86ISD::SHLD";
14931   case X86ISD::SHRD:               return "X86ISD::SHRD";
14932   case X86ISD::FAND:               return "X86ISD::FAND";
14933   case X86ISD::FANDN:              return "X86ISD::FANDN";
14934   case X86ISD::FOR:                return "X86ISD::FOR";
14935   case X86ISD::FXOR:               return "X86ISD::FXOR";
14936   case X86ISD::FSRL:               return "X86ISD::FSRL";
14937   case X86ISD::FILD:               return "X86ISD::FILD";
14938   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14939   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14940   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14941   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14942   case X86ISD::FLD:                return "X86ISD::FLD";
14943   case X86ISD::FST:                return "X86ISD::FST";
14944   case X86ISD::CALL:               return "X86ISD::CALL";
14945   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14946   case X86ISD::BT:                 return "X86ISD::BT";
14947   case X86ISD::CMP:                return "X86ISD::CMP";
14948   case X86ISD::COMI:               return "X86ISD::COMI";
14949   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14950   case X86ISD::CMPM:               return "X86ISD::CMPM";
14951   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14952   case X86ISD::SETCC:              return "X86ISD::SETCC";
14953   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14954   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14955   case X86ISD::CMOV:               return "X86ISD::CMOV";
14956   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14957   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14958   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14959   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14960   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14961   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14962   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14963   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14964   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14965   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14966   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14967   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14968   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14969   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14970   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14971   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14972   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14973   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14974   case X86ISD::HADD:               return "X86ISD::HADD";
14975   case X86ISD::HSUB:               return "X86ISD::HSUB";
14976   case X86ISD::FHADD:              return "X86ISD::FHADD";
14977   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14978   case X86ISD::UMAX:               return "X86ISD::UMAX";
14979   case X86ISD::UMIN:               return "X86ISD::UMIN";
14980   case X86ISD::SMAX:               return "X86ISD::SMAX";
14981   case X86ISD::SMIN:               return "X86ISD::SMIN";
14982   case X86ISD::FMAX:               return "X86ISD::FMAX";
14983   case X86ISD::FMIN:               return "X86ISD::FMIN";
14984   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14985   case X86ISD::FMINC:              return "X86ISD::FMINC";
14986   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14987   case X86ISD::FRCP:               return "X86ISD::FRCP";
14988   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14989   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14990   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14991   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14992   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14993   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14994   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14995   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14996   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14997   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14998   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14999   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
15000   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
15001   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
15002   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
15003   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
15004   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
15005   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
15006   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
15007   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
15008   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
15009   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
15010   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
15011   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
15012   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
15013   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
15014   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
15015   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
15016   case X86ISD::VSHL:               return "X86ISD::VSHL";
15017   case X86ISD::VSRL:               return "X86ISD::VSRL";
15018   case X86ISD::VSRA:               return "X86ISD::VSRA";
15019   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
15020   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
15021   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
15022   case X86ISD::CMPP:               return "X86ISD::CMPP";
15023   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
15024   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
15025   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
15026   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
15027   case X86ISD::ADD:                return "X86ISD::ADD";
15028   case X86ISD::SUB:                return "X86ISD::SUB";
15029   case X86ISD::ADC:                return "X86ISD::ADC";
15030   case X86ISD::SBB:                return "X86ISD::SBB";
15031   case X86ISD::SMUL:               return "X86ISD::SMUL";
15032   case X86ISD::UMUL:               return "X86ISD::UMUL";
15033   case X86ISD::INC:                return "X86ISD::INC";
15034   case X86ISD::DEC:                return "X86ISD::DEC";
15035   case X86ISD::OR:                 return "X86ISD::OR";
15036   case X86ISD::XOR:                return "X86ISD::XOR";
15037   case X86ISD::AND:                return "X86ISD::AND";
15038   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
15039   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
15040   case X86ISD::PTEST:              return "X86ISD::PTEST";
15041   case X86ISD::TESTP:              return "X86ISD::TESTP";
15042   case X86ISD::TESTM:              return "X86ISD::TESTM";
15043   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
15044   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
15045   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
15046   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
15047   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
15048   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
15049   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
15050   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
15051   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
15052   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
15053   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
15054   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
15055   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
15056   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
15057   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
15058   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
15059   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
15060   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
15061   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
15062   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
15063   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
15064   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
15065   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
15066   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
15067   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
15068   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
15069   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
15070   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
15071   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
15072   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
15073   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15074   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
15075   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
15076   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
15077   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
15078   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
15079   case X86ISD::SAHF:               return "X86ISD::SAHF";
15080   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
15081   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
15082   case X86ISD::FMADD:              return "X86ISD::FMADD";
15083   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
15084   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
15085   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
15086   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
15087   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
15088   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
15089   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
15090   case X86ISD::XTEST:              return "X86ISD::XTEST";
15091   }
15092 }
15093
15094 // isLegalAddressingMode - Return true if the addressing mode represented
15095 // by AM is legal for this target, for a load/store of the specified type.
15096 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15097                                               Type *Ty) const {
15098   // X86 supports extremely general addressing modes.
15099   CodeModel::Model M = getTargetMachine().getCodeModel();
15100   Reloc::Model R = getTargetMachine().getRelocationModel();
15101
15102   // X86 allows a sign-extended 32-bit immediate field as a displacement.
15103   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15104     return false;
15105
15106   if (AM.BaseGV) {
15107     unsigned GVFlags =
15108       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15109
15110     // If a reference to this global requires an extra load, we can't fold it.
15111     if (isGlobalStubReference(GVFlags))
15112       return false;
15113
15114     // If BaseGV requires a register for the PIC base, we cannot also have a
15115     // BaseReg specified.
15116     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15117       return false;
15118
15119     // If lower 4G is not available, then we must use rip-relative addressing.
15120     if ((M != CodeModel::Small || R != Reloc::Static) &&
15121         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15122       return false;
15123   }
15124
15125   switch (AM.Scale) {
15126   case 0:
15127   case 1:
15128   case 2:
15129   case 4:
15130   case 8:
15131     // These scales always work.
15132     break;
15133   case 3:
15134   case 5:
15135   case 9:
15136     // These scales are formed with basereg+scalereg.  Only accept if there is
15137     // no basereg yet.
15138     if (AM.HasBaseReg)
15139       return false;
15140     break;
15141   default:  // Other stuff never works.
15142     return false;
15143   }
15144
15145   return true;
15146 }
15147
15148 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15149   unsigned Bits = Ty->getScalarSizeInBits();
15150
15151   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15152   // particularly cheaper than those without.
15153   if (Bits == 8)
15154     return false;
15155
15156   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15157   // variable shifts just as cheap as scalar ones.
15158   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15159     return false;
15160
15161   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15162   // fully general vector.
15163   return true;
15164 }
15165
15166 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15167   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15168     return false;
15169   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15170   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15171   return NumBits1 > NumBits2;
15172 }
15173
15174 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15175   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15176     return false;
15177
15178   if (!isTypeLegal(EVT::getEVT(Ty1)))
15179     return false;
15180
15181   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15182
15183   // Assuming the caller doesn't have a zeroext or signext return parameter,
15184   // truncation all the way down to i1 is valid.
15185   return true;
15186 }
15187
15188 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15189   return isInt<32>(Imm);
15190 }
15191
15192 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15193   // Can also use sub to handle negated immediates.
15194   return isInt<32>(Imm);
15195 }
15196
15197 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15198   if (!VT1.isInteger() || !VT2.isInteger())
15199     return false;
15200   unsigned NumBits1 = VT1.getSizeInBits();
15201   unsigned NumBits2 = VT2.getSizeInBits();
15202   return NumBits1 > NumBits2;
15203 }
15204
15205 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15206   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15207   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15208 }
15209
15210 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15211   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15212   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15213 }
15214
15215 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15216   EVT VT1 = Val.getValueType();
15217   if (isZExtFree(VT1, VT2))
15218     return true;
15219
15220   if (Val.getOpcode() != ISD::LOAD)
15221     return false;
15222
15223   if (!VT1.isSimple() || !VT1.isInteger() ||
15224       !VT2.isSimple() || !VT2.isInteger())
15225     return false;
15226
15227   switch (VT1.getSimpleVT().SimpleTy) {
15228   default: break;
15229   case MVT::i8:
15230   case MVT::i16:
15231   case MVT::i32:
15232     // X86 has 8, 16, and 32-bit zero-extending loads.
15233     return true;
15234   }
15235
15236   return false;
15237 }
15238
15239 bool
15240 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15241   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15242     return false;
15243
15244   VT = VT.getScalarType();
15245
15246   if (!VT.isSimple())
15247     return false;
15248
15249   switch (VT.getSimpleVT().SimpleTy) {
15250   case MVT::f32:
15251   case MVT::f64:
15252     return true;
15253   default:
15254     break;
15255   }
15256
15257   return false;
15258 }
15259
15260 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15261   // i16 instructions are longer (0x66 prefix) and potentially slower.
15262   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15263 }
15264
15265 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15266 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15267 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15268 /// are assumed to be legal.
15269 bool
15270 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15271                                       EVT VT) const {
15272   if (!VT.isSimple())
15273     return false;
15274
15275   MVT SVT = VT.getSimpleVT();
15276
15277   // Very little shuffling can be done for 64-bit vectors right now.
15278   if (VT.getSizeInBits() == 64)
15279     return false;
15280
15281   // If this is a single-input shuffle with no 128 bit lane crossings we can
15282   // lower it into pshufb.
15283   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15284       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15285     bool isLegal = true;
15286     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15287       if (M[I] >= (int)SVT.getVectorNumElements() ||
15288           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15289         isLegal = false;
15290         break;
15291       }
15292     }
15293     if (isLegal)
15294       return true;
15295   }
15296
15297   // FIXME: blends, shifts.
15298   return (SVT.getVectorNumElements() == 2 ||
15299           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15300           isMOVLMask(M, SVT) ||
15301           isSHUFPMask(M, SVT) ||
15302           isPSHUFDMask(M, SVT) ||
15303           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15304           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15305           isPALIGNRMask(M, SVT, Subtarget) ||
15306           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15307           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15308           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15309           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15310           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15311 }
15312
15313 bool
15314 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15315                                           EVT VT) const {
15316   if (!VT.isSimple())
15317     return false;
15318
15319   MVT SVT = VT.getSimpleVT();
15320   unsigned NumElts = SVT.getVectorNumElements();
15321   // FIXME: This collection of masks seems suspect.
15322   if (NumElts == 2)
15323     return true;
15324   if (NumElts == 4 && SVT.is128BitVector()) {
15325     return (isMOVLMask(Mask, SVT)  ||
15326             isCommutedMOVLMask(Mask, SVT, true) ||
15327             isSHUFPMask(Mask, SVT) ||
15328             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15329   }
15330   return false;
15331 }
15332
15333 //===----------------------------------------------------------------------===//
15334 //                           X86 Scheduler Hooks
15335 //===----------------------------------------------------------------------===//
15336
15337 /// Utility function to emit xbegin specifying the start of an RTM region.
15338 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15339                                      const TargetInstrInfo *TII) {
15340   DebugLoc DL = MI->getDebugLoc();
15341
15342   const BasicBlock *BB = MBB->getBasicBlock();
15343   MachineFunction::iterator I = MBB;
15344   ++I;
15345
15346   // For the v = xbegin(), we generate
15347   //
15348   // thisMBB:
15349   //  xbegin sinkMBB
15350   //
15351   // mainMBB:
15352   //  eax = -1
15353   //
15354   // sinkMBB:
15355   //  v = eax
15356
15357   MachineBasicBlock *thisMBB = MBB;
15358   MachineFunction *MF = MBB->getParent();
15359   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15360   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15361   MF->insert(I, mainMBB);
15362   MF->insert(I, sinkMBB);
15363
15364   // Transfer the remainder of BB and its successor edges to sinkMBB.
15365   sinkMBB->splice(sinkMBB->begin(), MBB,
15366                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15367   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15368
15369   // thisMBB:
15370   //  xbegin sinkMBB
15371   //  # fallthrough to mainMBB
15372   //  # abortion to sinkMBB
15373   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15374   thisMBB->addSuccessor(mainMBB);
15375   thisMBB->addSuccessor(sinkMBB);
15376
15377   // mainMBB:
15378   //  EAX = -1
15379   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15380   mainMBB->addSuccessor(sinkMBB);
15381
15382   // sinkMBB:
15383   // EAX is live into the sinkMBB
15384   sinkMBB->addLiveIn(X86::EAX);
15385   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15386           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15387     .addReg(X86::EAX);
15388
15389   MI->eraseFromParent();
15390   return sinkMBB;
15391 }
15392
15393 // Get CMPXCHG opcode for the specified data type.
15394 static unsigned getCmpXChgOpcode(EVT VT) {
15395   switch (VT.getSimpleVT().SimpleTy) {
15396   case MVT::i8:  return X86::LCMPXCHG8;
15397   case MVT::i16: return X86::LCMPXCHG16;
15398   case MVT::i32: return X86::LCMPXCHG32;
15399   case MVT::i64: return X86::LCMPXCHG64;
15400   default:
15401     break;
15402   }
15403   llvm_unreachable("Invalid operand size!");
15404 }
15405
15406 // Get LOAD opcode for the specified data type.
15407 static unsigned getLoadOpcode(EVT VT) {
15408   switch (VT.getSimpleVT().SimpleTy) {
15409   case MVT::i8:  return X86::MOV8rm;
15410   case MVT::i16: return X86::MOV16rm;
15411   case MVT::i32: return X86::MOV32rm;
15412   case MVT::i64: return X86::MOV64rm;
15413   default:
15414     break;
15415   }
15416   llvm_unreachable("Invalid operand size!");
15417 }
15418
15419 // Get opcode of the non-atomic one from the specified atomic instruction.
15420 static unsigned getNonAtomicOpcode(unsigned Opc) {
15421   switch (Opc) {
15422   case X86::ATOMAND8:  return X86::AND8rr;
15423   case X86::ATOMAND16: return X86::AND16rr;
15424   case X86::ATOMAND32: return X86::AND32rr;
15425   case X86::ATOMAND64: return X86::AND64rr;
15426   case X86::ATOMOR8:   return X86::OR8rr;
15427   case X86::ATOMOR16:  return X86::OR16rr;
15428   case X86::ATOMOR32:  return X86::OR32rr;
15429   case X86::ATOMOR64:  return X86::OR64rr;
15430   case X86::ATOMXOR8:  return X86::XOR8rr;
15431   case X86::ATOMXOR16: return X86::XOR16rr;
15432   case X86::ATOMXOR32: return X86::XOR32rr;
15433   case X86::ATOMXOR64: return X86::XOR64rr;
15434   }
15435   llvm_unreachable("Unhandled atomic-load-op opcode!");
15436 }
15437
15438 // Get opcode of the non-atomic one from the specified atomic instruction with
15439 // extra opcode.
15440 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15441                                                unsigned &ExtraOpc) {
15442   switch (Opc) {
15443   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15444   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15445   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15446   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15447   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15448   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15449   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15450   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15451   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15452   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15453   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15454   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15455   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15456   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15457   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15458   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15459   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15460   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15461   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15462   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15463   }
15464   llvm_unreachable("Unhandled atomic-load-op opcode!");
15465 }
15466
15467 // Get opcode of the non-atomic one from the specified atomic instruction for
15468 // 64-bit data type on 32-bit target.
15469 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15470   switch (Opc) {
15471   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15472   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15473   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15474   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15475   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15476   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15477   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15478   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15479   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15480   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15481   }
15482   llvm_unreachable("Unhandled atomic-load-op opcode!");
15483 }
15484
15485 // Get opcode of the non-atomic one from the specified atomic instruction for
15486 // 64-bit data type on 32-bit target with extra opcode.
15487 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15488                                                    unsigned &HiOpc,
15489                                                    unsigned &ExtraOpc) {
15490   switch (Opc) {
15491   case X86::ATOMNAND6432:
15492     ExtraOpc = X86::NOT32r;
15493     HiOpc = X86::AND32rr;
15494     return X86::AND32rr;
15495   }
15496   llvm_unreachable("Unhandled atomic-load-op opcode!");
15497 }
15498
15499 // Get pseudo CMOV opcode from the specified data type.
15500 static unsigned getPseudoCMOVOpc(EVT VT) {
15501   switch (VT.getSimpleVT().SimpleTy) {
15502   case MVT::i8:  return X86::CMOV_GR8;
15503   case MVT::i16: return X86::CMOV_GR16;
15504   case MVT::i32: return X86::CMOV_GR32;
15505   default:
15506     break;
15507   }
15508   llvm_unreachable("Unknown CMOV opcode!");
15509 }
15510
15511 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15512 // They will be translated into a spin-loop or compare-exchange loop from
15513 //
15514 //    ...
15515 //    dst = atomic-fetch-op MI.addr, MI.val
15516 //    ...
15517 //
15518 // to
15519 //
15520 //    ...
15521 //    t1 = LOAD MI.addr
15522 // loop:
15523 //    t4 = phi(t1, t3 / loop)
15524 //    t2 = OP MI.val, t4
15525 //    EAX = t4
15526 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15527 //    t3 = EAX
15528 //    JNE loop
15529 // sink:
15530 //    dst = t3
15531 //    ...
15532 MachineBasicBlock *
15533 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15534                                        MachineBasicBlock *MBB) const {
15535   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15536   DebugLoc DL = MI->getDebugLoc();
15537
15538   MachineFunction *MF = MBB->getParent();
15539   MachineRegisterInfo &MRI = MF->getRegInfo();
15540
15541   const BasicBlock *BB = MBB->getBasicBlock();
15542   MachineFunction::iterator I = MBB;
15543   ++I;
15544
15545   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15546          "Unexpected number of operands");
15547
15548   assert(MI->hasOneMemOperand() &&
15549          "Expected atomic-load-op to have one memoperand");
15550
15551   // Memory Reference
15552   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15553   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15554
15555   unsigned DstReg, SrcReg;
15556   unsigned MemOpndSlot;
15557
15558   unsigned CurOp = 0;
15559
15560   DstReg = MI->getOperand(CurOp++).getReg();
15561   MemOpndSlot = CurOp;
15562   CurOp += X86::AddrNumOperands;
15563   SrcReg = MI->getOperand(CurOp++).getReg();
15564
15565   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15566   MVT::SimpleValueType VT = *RC->vt_begin();
15567   unsigned t1 = MRI.createVirtualRegister(RC);
15568   unsigned t2 = MRI.createVirtualRegister(RC);
15569   unsigned t3 = MRI.createVirtualRegister(RC);
15570   unsigned t4 = MRI.createVirtualRegister(RC);
15571   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15572
15573   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15574   unsigned LOADOpc = getLoadOpcode(VT);
15575
15576   // For the atomic load-arith operator, we generate
15577   //
15578   //  thisMBB:
15579   //    t1 = LOAD [MI.addr]
15580   //  mainMBB:
15581   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15582   //    t1 = OP MI.val, EAX
15583   //    EAX = t4
15584   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15585   //    t3 = EAX
15586   //    JNE mainMBB
15587   //  sinkMBB:
15588   //    dst = t3
15589
15590   MachineBasicBlock *thisMBB = MBB;
15591   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15592   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15593   MF->insert(I, mainMBB);
15594   MF->insert(I, sinkMBB);
15595
15596   MachineInstrBuilder MIB;
15597
15598   // Transfer the remainder of BB and its successor edges to sinkMBB.
15599   sinkMBB->splice(sinkMBB->begin(), MBB,
15600                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15601   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15602
15603   // thisMBB:
15604   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15605   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15606     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15607     if (NewMO.isReg())
15608       NewMO.setIsKill(false);
15609     MIB.addOperand(NewMO);
15610   }
15611   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15612     unsigned flags = (*MMOI)->getFlags();
15613     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15614     MachineMemOperand *MMO =
15615       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15616                                (*MMOI)->getSize(),
15617                                (*MMOI)->getBaseAlignment(),
15618                                (*MMOI)->getTBAAInfo(),
15619                                (*MMOI)->getRanges());
15620     MIB.addMemOperand(MMO);
15621   }
15622
15623   thisMBB->addSuccessor(mainMBB);
15624
15625   // mainMBB:
15626   MachineBasicBlock *origMainMBB = mainMBB;
15627
15628   // Add a PHI.
15629   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15630                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15631
15632   unsigned Opc = MI->getOpcode();
15633   switch (Opc) {
15634   default:
15635     llvm_unreachable("Unhandled atomic-load-op opcode!");
15636   case X86::ATOMAND8:
15637   case X86::ATOMAND16:
15638   case X86::ATOMAND32:
15639   case X86::ATOMAND64:
15640   case X86::ATOMOR8:
15641   case X86::ATOMOR16:
15642   case X86::ATOMOR32:
15643   case X86::ATOMOR64:
15644   case X86::ATOMXOR8:
15645   case X86::ATOMXOR16:
15646   case X86::ATOMXOR32:
15647   case X86::ATOMXOR64: {
15648     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15649     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15650       .addReg(t4);
15651     break;
15652   }
15653   case X86::ATOMNAND8:
15654   case X86::ATOMNAND16:
15655   case X86::ATOMNAND32:
15656   case X86::ATOMNAND64: {
15657     unsigned Tmp = MRI.createVirtualRegister(RC);
15658     unsigned NOTOpc;
15659     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15660     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15661       .addReg(t4);
15662     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15663     break;
15664   }
15665   case X86::ATOMMAX8:
15666   case X86::ATOMMAX16:
15667   case X86::ATOMMAX32:
15668   case X86::ATOMMAX64:
15669   case X86::ATOMMIN8:
15670   case X86::ATOMMIN16:
15671   case X86::ATOMMIN32:
15672   case X86::ATOMMIN64:
15673   case X86::ATOMUMAX8:
15674   case X86::ATOMUMAX16:
15675   case X86::ATOMUMAX32:
15676   case X86::ATOMUMAX64:
15677   case X86::ATOMUMIN8:
15678   case X86::ATOMUMIN16:
15679   case X86::ATOMUMIN32:
15680   case X86::ATOMUMIN64: {
15681     unsigned CMPOpc;
15682     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15683
15684     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15685       .addReg(SrcReg)
15686       .addReg(t4);
15687
15688     if (Subtarget->hasCMov()) {
15689       if (VT != MVT::i8) {
15690         // Native support
15691         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15692           .addReg(SrcReg)
15693           .addReg(t4);
15694       } else {
15695         // Promote i8 to i32 to use CMOV32
15696         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15697         const TargetRegisterClass *RC32 =
15698           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15699         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15700         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15701         unsigned Tmp = MRI.createVirtualRegister(RC32);
15702
15703         unsigned Undef = MRI.createVirtualRegister(RC32);
15704         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15705
15706         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15707           .addReg(Undef)
15708           .addReg(SrcReg)
15709           .addImm(X86::sub_8bit);
15710         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15711           .addReg(Undef)
15712           .addReg(t4)
15713           .addImm(X86::sub_8bit);
15714
15715         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15716           .addReg(SrcReg32)
15717           .addReg(AccReg32);
15718
15719         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15720           .addReg(Tmp, 0, X86::sub_8bit);
15721       }
15722     } else {
15723       // Use pseudo select and lower them.
15724       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15725              "Invalid atomic-load-op transformation!");
15726       unsigned SelOpc = getPseudoCMOVOpc(VT);
15727       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15728       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15729       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15730               .addReg(SrcReg).addReg(t4)
15731               .addImm(CC);
15732       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15733       // Replace the original PHI node as mainMBB is changed after CMOV
15734       // lowering.
15735       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15736         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15737       Phi->eraseFromParent();
15738     }
15739     break;
15740   }
15741   }
15742
15743   // Copy PhyReg back from virtual register.
15744   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15745     .addReg(t4);
15746
15747   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15748   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15749     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15750     if (NewMO.isReg())
15751       NewMO.setIsKill(false);
15752     MIB.addOperand(NewMO);
15753   }
15754   MIB.addReg(t2);
15755   MIB.setMemRefs(MMOBegin, MMOEnd);
15756
15757   // Copy PhyReg back to virtual register.
15758   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15759     .addReg(PhyReg);
15760
15761   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15762
15763   mainMBB->addSuccessor(origMainMBB);
15764   mainMBB->addSuccessor(sinkMBB);
15765
15766   // sinkMBB:
15767   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15768           TII->get(TargetOpcode::COPY), DstReg)
15769     .addReg(t3);
15770
15771   MI->eraseFromParent();
15772   return sinkMBB;
15773 }
15774
15775 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15776 // instructions. They will be translated into a spin-loop or compare-exchange
15777 // loop from
15778 //
15779 //    ...
15780 //    dst = atomic-fetch-op MI.addr, MI.val
15781 //    ...
15782 //
15783 // to
15784 //
15785 //    ...
15786 //    t1L = LOAD [MI.addr + 0]
15787 //    t1H = LOAD [MI.addr + 4]
15788 // loop:
15789 //    t4L = phi(t1L, t3L / loop)
15790 //    t4H = phi(t1H, t3H / loop)
15791 //    t2L = OP MI.val.lo, t4L
15792 //    t2H = OP MI.val.hi, t4H
15793 //    EAX = t4L
15794 //    EDX = t4H
15795 //    EBX = t2L
15796 //    ECX = t2H
15797 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15798 //    t3L = EAX
15799 //    t3H = EDX
15800 //    JNE loop
15801 // sink:
15802 //    dstL = t3L
15803 //    dstH = t3H
15804 //    ...
15805 MachineBasicBlock *
15806 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15807                                            MachineBasicBlock *MBB) const {
15808   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15809   DebugLoc DL = MI->getDebugLoc();
15810
15811   MachineFunction *MF = MBB->getParent();
15812   MachineRegisterInfo &MRI = MF->getRegInfo();
15813
15814   const BasicBlock *BB = MBB->getBasicBlock();
15815   MachineFunction::iterator I = MBB;
15816   ++I;
15817
15818   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15819          "Unexpected number of operands");
15820
15821   assert(MI->hasOneMemOperand() &&
15822          "Expected atomic-load-op32 to have one memoperand");
15823
15824   // Memory Reference
15825   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15826   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15827
15828   unsigned DstLoReg, DstHiReg;
15829   unsigned SrcLoReg, SrcHiReg;
15830   unsigned MemOpndSlot;
15831
15832   unsigned CurOp = 0;
15833
15834   DstLoReg = MI->getOperand(CurOp++).getReg();
15835   DstHiReg = MI->getOperand(CurOp++).getReg();
15836   MemOpndSlot = CurOp;
15837   CurOp += X86::AddrNumOperands;
15838   SrcLoReg = MI->getOperand(CurOp++).getReg();
15839   SrcHiReg = MI->getOperand(CurOp++).getReg();
15840
15841   const TargetRegisterClass *RC = &X86::GR32RegClass;
15842   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15843
15844   unsigned t1L = MRI.createVirtualRegister(RC);
15845   unsigned t1H = MRI.createVirtualRegister(RC);
15846   unsigned t2L = MRI.createVirtualRegister(RC);
15847   unsigned t2H = MRI.createVirtualRegister(RC);
15848   unsigned t3L = MRI.createVirtualRegister(RC);
15849   unsigned t3H = MRI.createVirtualRegister(RC);
15850   unsigned t4L = MRI.createVirtualRegister(RC);
15851   unsigned t4H = MRI.createVirtualRegister(RC);
15852
15853   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15854   unsigned LOADOpc = X86::MOV32rm;
15855
15856   // For the atomic load-arith operator, we generate
15857   //
15858   //  thisMBB:
15859   //    t1L = LOAD [MI.addr + 0]
15860   //    t1H = LOAD [MI.addr + 4]
15861   //  mainMBB:
15862   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15863   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15864   //    t2L = OP MI.val.lo, t4L
15865   //    t2H = OP MI.val.hi, t4H
15866   //    EBX = t2L
15867   //    ECX = t2H
15868   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15869   //    t3L = EAX
15870   //    t3H = EDX
15871   //    JNE loop
15872   //  sinkMBB:
15873   //    dstL = t3L
15874   //    dstH = t3H
15875
15876   MachineBasicBlock *thisMBB = MBB;
15877   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15878   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15879   MF->insert(I, mainMBB);
15880   MF->insert(I, sinkMBB);
15881
15882   MachineInstrBuilder MIB;
15883
15884   // Transfer the remainder of BB and its successor edges to sinkMBB.
15885   sinkMBB->splice(sinkMBB->begin(), MBB,
15886                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15887   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15888
15889   // thisMBB:
15890   // Lo
15891   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
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   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15899     unsigned flags = (*MMOI)->getFlags();
15900     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15901     MachineMemOperand *MMO =
15902       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15903                                (*MMOI)->getSize(),
15904                                (*MMOI)->getBaseAlignment(),
15905                                (*MMOI)->getTBAAInfo(),
15906                                (*MMOI)->getRanges());
15907     MIB.addMemOperand(MMO);
15908   };
15909   MachineInstr *LowMI = MIB;
15910
15911   // Hi
15912   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15913   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15914     if (i == X86::AddrDisp) {
15915       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15916     } else {
15917       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15918       if (NewMO.isReg())
15919         NewMO.setIsKill(false);
15920       MIB.addOperand(NewMO);
15921     }
15922   }
15923   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15924
15925   thisMBB->addSuccessor(mainMBB);
15926
15927   // mainMBB:
15928   MachineBasicBlock *origMainMBB = mainMBB;
15929
15930   // Add PHIs.
15931   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15932                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15933   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15934                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15935
15936   unsigned Opc = MI->getOpcode();
15937   switch (Opc) {
15938   default:
15939     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15940   case X86::ATOMAND6432:
15941   case X86::ATOMOR6432:
15942   case X86::ATOMXOR6432:
15943   case X86::ATOMADD6432:
15944   case X86::ATOMSUB6432: {
15945     unsigned HiOpc;
15946     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15947     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15948       .addReg(SrcLoReg);
15949     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15950       .addReg(SrcHiReg);
15951     break;
15952   }
15953   case X86::ATOMNAND6432: {
15954     unsigned HiOpc, NOTOpc;
15955     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15956     unsigned TmpL = MRI.createVirtualRegister(RC);
15957     unsigned TmpH = MRI.createVirtualRegister(RC);
15958     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15959       .addReg(t4L);
15960     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15961       .addReg(t4H);
15962     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15963     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15964     break;
15965   }
15966   case X86::ATOMMAX6432:
15967   case X86::ATOMMIN6432:
15968   case X86::ATOMUMAX6432:
15969   case X86::ATOMUMIN6432: {
15970     unsigned HiOpc;
15971     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15972     unsigned cL = MRI.createVirtualRegister(RC8);
15973     unsigned cH = MRI.createVirtualRegister(RC8);
15974     unsigned cL32 = MRI.createVirtualRegister(RC);
15975     unsigned cH32 = MRI.createVirtualRegister(RC);
15976     unsigned cc = MRI.createVirtualRegister(RC);
15977     // cl := cmp src_lo, lo
15978     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15979       .addReg(SrcLoReg).addReg(t4L);
15980     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15981     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15982     // ch := cmp src_hi, hi
15983     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15984       .addReg(SrcHiReg).addReg(t4H);
15985     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15986     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15987     // cc := if (src_hi == hi) ? cl : ch;
15988     if (Subtarget->hasCMov()) {
15989       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15990         .addReg(cH32).addReg(cL32);
15991     } else {
15992       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15993               .addReg(cH32).addReg(cL32)
15994               .addImm(X86::COND_E);
15995       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15996     }
15997     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15998     if (Subtarget->hasCMov()) {
15999       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16000         .addReg(SrcLoReg).addReg(t4L);
16001       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16002         .addReg(SrcHiReg).addReg(t4H);
16003     } else {
16004       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16005               .addReg(SrcLoReg).addReg(t4L)
16006               .addImm(X86::COND_NE);
16007       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16008       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16009       // 2nd CMOV lowering.
16010       mainMBB->addLiveIn(X86::EFLAGS);
16011       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16012               .addReg(SrcHiReg).addReg(t4H)
16013               .addImm(X86::COND_NE);
16014       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16015       // Replace the original PHI node as mainMBB is changed after CMOV
16016       // lowering.
16017       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16018         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16019       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16020         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16021       PhiL->eraseFromParent();
16022       PhiH->eraseFromParent();
16023     }
16024     break;
16025   }
16026   case X86::ATOMSWAP6432: {
16027     unsigned HiOpc;
16028     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16029     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16030     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16031     break;
16032   }
16033   }
16034
16035   // Copy EDX:EAX back from HiReg:LoReg
16036   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16037   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16038   // Copy ECX:EBX from t1H:t1L
16039   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16040   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16041
16042   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16043   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16044     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16045     if (NewMO.isReg())
16046       NewMO.setIsKill(false);
16047     MIB.addOperand(NewMO);
16048   }
16049   MIB.setMemRefs(MMOBegin, MMOEnd);
16050
16051   // Copy EDX:EAX back to t3H:t3L
16052   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16053   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16054
16055   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16056
16057   mainMBB->addSuccessor(origMainMBB);
16058   mainMBB->addSuccessor(sinkMBB);
16059
16060   // sinkMBB:
16061   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16062           TII->get(TargetOpcode::COPY), DstLoReg)
16063     .addReg(t3L);
16064   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16065           TII->get(TargetOpcode::COPY), DstHiReg)
16066     .addReg(t3H);
16067
16068   MI->eraseFromParent();
16069   return sinkMBB;
16070 }
16071
16072 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16073 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16074 // in the .td file.
16075 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16076                                        const TargetInstrInfo *TII) {
16077   unsigned Opc;
16078   switch (MI->getOpcode()) {
16079   default: llvm_unreachable("illegal opcode!");
16080   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16081   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16082   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16083   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16084   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16085   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16086   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16087   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16088   }
16089
16090   DebugLoc dl = MI->getDebugLoc();
16091   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16092
16093   unsigned NumArgs = MI->getNumOperands();
16094   for (unsigned i = 1; i < NumArgs; ++i) {
16095     MachineOperand &Op = MI->getOperand(i);
16096     if (!(Op.isReg() && Op.isImplicit()))
16097       MIB.addOperand(Op);
16098   }
16099   if (MI->hasOneMemOperand())
16100     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16101
16102   BuildMI(*BB, MI, dl,
16103     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16104     .addReg(X86::XMM0);
16105
16106   MI->eraseFromParent();
16107   return BB;
16108 }
16109
16110 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16111 // defs in an instruction pattern
16112 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16113                                        const TargetInstrInfo *TII) {
16114   unsigned Opc;
16115   switch (MI->getOpcode()) {
16116   default: llvm_unreachable("illegal opcode!");
16117   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16118   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16119   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16120   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16121   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16122   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16123   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16124   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16125   }
16126
16127   DebugLoc dl = MI->getDebugLoc();
16128   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16129
16130   unsigned NumArgs = MI->getNumOperands(); // remove the results
16131   for (unsigned i = 1; i < NumArgs; ++i) {
16132     MachineOperand &Op = MI->getOperand(i);
16133     if (!(Op.isReg() && Op.isImplicit()))
16134       MIB.addOperand(Op);
16135   }
16136   if (MI->hasOneMemOperand())
16137     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16138
16139   BuildMI(*BB, MI, dl,
16140     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16141     .addReg(X86::ECX);
16142
16143   MI->eraseFromParent();
16144   return BB;
16145 }
16146
16147 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16148                                        const TargetInstrInfo *TII,
16149                                        const X86Subtarget* Subtarget) {
16150   DebugLoc dl = MI->getDebugLoc();
16151
16152   // Address into RAX/EAX, other two args into ECX, EDX.
16153   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16154   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16155   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16156   for (int i = 0; i < X86::AddrNumOperands; ++i)
16157     MIB.addOperand(MI->getOperand(i));
16158
16159   unsigned ValOps = X86::AddrNumOperands;
16160   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16161     .addReg(MI->getOperand(ValOps).getReg());
16162   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16163     .addReg(MI->getOperand(ValOps+1).getReg());
16164
16165   // The instruction doesn't actually take any operands though.
16166   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16167
16168   MI->eraseFromParent(); // The pseudo is gone now.
16169   return BB;
16170 }
16171
16172 MachineBasicBlock *
16173 X86TargetLowering::EmitVAARG64WithCustomInserter(
16174                    MachineInstr *MI,
16175                    MachineBasicBlock *MBB) const {
16176   // Emit va_arg instruction on X86-64.
16177
16178   // Operands to this pseudo-instruction:
16179   // 0  ) Output        : destination address (reg)
16180   // 1-5) Input         : va_list address (addr, i64mem)
16181   // 6  ) ArgSize       : Size (in bytes) of vararg type
16182   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16183   // 8  ) Align         : Alignment of type
16184   // 9  ) EFLAGS (implicit-def)
16185
16186   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16187   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16188
16189   unsigned DestReg = MI->getOperand(0).getReg();
16190   MachineOperand &Base = MI->getOperand(1);
16191   MachineOperand &Scale = MI->getOperand(2);
16192   MachineOperand &Index = MI->getOperand(3);
16193   MachineOperand &Disp = MI->getOperand(4);
16194   MachineOperand &Segment = MI->getOperand(5);
16195   unsigned ArgSize = MI->getOperand(6).getImm();
16196   unsigned ArgMode = MI->getOperand(7).getImm();
16197   unsigned Align = MI->getOperand(8).getImm();
16198
16199   // Memory Reference
16200   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16201   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16202   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16203
16204   // Machine Information
16205   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16206   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16207   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16208   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16209   DebugLoc DL = MI->getDebugLoc();
16210
16211   // struct va_list {
16212   //   i32   gp_offset
16213   //   i32   fp_offset
16214   //   i64   overflow_area (address)
16215   //   i64   reg_save_area (address)
16216   // }
16217   // sizeof(va_list) = 24
16218   // alignment(va_list) = 8
16219
16220   unsigned TotalNumIntRegs = 6;
16221   unsigned TotalNumXMMRegs = 8;
16222   bool UseGPOffset = (ArgMode == 1);
16223   bool UseFPOffset = (ArgMode == 2);
16224   unsigned MaxOffset = TotalNumIntRegs * 8 +
16225                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16226
16227   /* Align ArgSize to a multiple of 8 */
16228   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16229   bool NeedsAlign = (Align > 8);
16230
16231   MachineBasicBlock *thisMBB = MBB;
16232   MachineBasicBlock *overflowMBB;
16233   MachineBasicBlock *offsetMBB;
16234   MachineBasicBlock *endMBB;
16235
16236   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16237   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16238   unsigned OffsetReg = 0;
16239
16240   if (!UseGPOffset && !UseFPOffset) {
16241     // If we only pull from the overflow region, we don't create a branch.
16242     // We don't need to alter control flow.
16243     OffsetDestReg = 0; // unused
16244     OverflowDestReg = DestReg;
16245
16246     offsetMBB = nullptr;
16247     overflowMBB = thisMBB;
16248     endMBB = thisMBB;
16249   } else {
16250     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16251     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16252     // If not, pull from overflow_area. (branch to overflowMBB)
16253     //
16254     //       thisMBB
16255     //         |     .
16256     //         |        .
16257     //     offsetMBB   overflowMBB
16258     //         |        .
16259     //         |     .
16260     //        endMBB
16261
16262     // Registers for the PHI in endMBB
16263     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16264     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16265
16266     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16267     MachineFunction *MF = MBB->getParent();
16268     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16269     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16270     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16271
16272     MachineFunction::iterator MBBIter = MBB;
16273     ++MBBIter;
16274
16275     // Insert the new basic blocks
16276     MF->insert(MBBIter, offsetMBB);
16277     MF->insert(MBBIter, overflowMBB);
16278     MF->insert(MBBIter, endMBB);
16279
16280     // Transfer the remainder of MBB and its successor edges to endMBB.
16281     endMBB->splice(endMBB->begin(), thisMBB,
16282                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16283     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16284
16285     // Make offsetMBB and overflowMBB successors of thisMBB
16286     thisMBB->addSuccessor(offsetMBB);
16287     thisMBB->addSuccessor(overflowMBB);
16288
16289     // endMBB is a successor of both offsetMBB and overflowMBB
16290     offsetMBB->addSuccessor(endMBB);
16291     overflowMBB->addSuccessor(endMBB);
16292
16293     // Load the offset value into a register
16294     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16295     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16296       .addOperand(Base)
16297       .addOperand(Scale)
16298       .addOperand(Index)
16299       .addDisp(Disp, UseFPOffset ? 4 : 0)
16300       .addOperand(Segment)
16301       .setMemRefs(MMOBegin, MMOEnd);
16302
16303     // Check if there is enough room left to pull this argument.
16304     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16305       .addReg(OffsetReg)
16306       .addImm(MaxOffset + 8 - ArgSizeA8);
16307
16308     // Branch to "overflowMBB" if offset >= max
16309     // Fall through to "offsetMBB" otherwise
16310     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16311       .addMBB(overflowMBB);
16312   }
16313
16314   // In offsetMBB, emit code to use the reg_save_area.
16315   if (offsetMBB) {
16316     assert(OffsetReg != 0);
16317
16318     // Read the reg_save_area address.
16319     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16320     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16321       .addOperand(Base)
16322       .addOperand(Scale)
16323       .addOperand(Index)
16324       .addDisp(Disp, 16)
16325       .addOperand(Segment)
16326       .setMemRefs(MMOBegin, MMOEnd);
16327
16328     // Zero-extend the offset
16329     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16330       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16331         .addImm(0)
16332         .addReg(OffsetReg)
16333         .addImm(X86::sub_32bit);
16334
16335     // Add the offset to the reg_save_area to get the final address.
16336     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16337       .addReg(OffsetReg64)
16338       .addReg(RegSaveReg);
16339
16340     // Compute the offset for the next argument
16341     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16342     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16343       .addReg(OffsetReg)
16344       .addImm(UseFPOffset ? 16 : 8);
16345
16346     // Store it back into the va_list.
16347     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16348       .addOperand(Base)
16349       .addOperand(Scale)
16350       .addOperand(Index)
16351       .addDisp(Disp, UseFPOffset ? 4 : 0)
16352       .addOperand(Segment)
16353       .addReg(NextOffsetReg)
16354       .setMemRefs(MMOBegin, MMOEnd);
16355
16356     // Jump to endMBB
16357     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16358       .addMBB(endMBB);
16359   }
16360
16361   //
16362   // Emit code to use overflow area
16363   //
16364
16365   // Load the overflow_area address into a register.
16366   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16367   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16368     .addOperand(Base)
16369     .addOperand(Scale)
16370     .addOperand(Index)
16371     .addDisp(Disp, 8)
16372     .addOperand(Segment)
16373     .setMemRefs(MMOBegin, MMOEnd);
16374
16375   // If we need to align it, do so. Otherwise, just copy the address
16376   // to OverflowDestReg.
16377   if (NeedsAlign) {
16378     // Align the overflow address
16379     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16380     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16381
16382     // aligned_addr = (addr + (align-1)) & ~(align-1)
16383     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16384       .addReg(OverflowAddrReg)
16385       .addImm(Align-1);
16386
16387     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16388       .addReg(TmpReg)
16389       .addImm(~(uint64_t)(Align-1));
16390   } else {
16391     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16392       .addReg(OverflowAddrReg);
16393   }
16394
16395   // Compute the next overflow address after this argument.
16396   // (the overflow address should be kept 8-byte aligned)
16397   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16398   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16399     .addReg(OverflowDestReg)
16400     .addImm(ArgSizeA8);
16401
16402   // Store the new overflow address.
16403   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16404     .addOperand(Base)
16405     .addOperand(Scale)
16406     .addOperand(Index)
16407     .addDisp(Disp, 8)
16408     .addOperand(Segment)
16409     .addReg(NextAddrReg)
16410     .setMemRefs(MMOBegin, MMOEnd);
16411
16412   // If we branched, emit the PHI to the front of endMBB.
16413   if (offsetMBB) {
16414     BuildMI(*endMBB, endMBB->begin(), DL,
16415             TII->get(X86::PHI), DestReg)
16416       .addReg(OffsetDestReg).addMBB(offsetMBB)
16417       .addReg(OverflowDestReg).addMBB(overflowMBB);
16418   }
16419
16420   // Erase the pseudo instruction
16421   MI->eraseFromParent();
16422
16423   return endMBB;
16424 }
16425
16426 MachineBasicBlock *
16427 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16428                                                  MachineInstr *MI,
16429                                                  MachineBasicBlock *MBB) const {
16430   // Emit code to save XMM registers to the stack. The ABI says that the
16431   // number of registers to save is given in %al, so it's theoretically
16432   // possible to do an indirect jump trick to avoid saving all of them,
16433   // however this code takes a simpler approach and just executes all
16434   // of the stores if %al is non-zero. It's less code, and it's probably
16435   // easier on the hardware branch predictor, and stores aren't all that
16436   // expensive anyway.
16437
16438   // Create the new basic blocks. One block contains all the XMM stores,
16439   // and one block is the final destination regardless of whether any
16440   // stores were performed.
16441   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16442   MachineFunction *F = MBB->getParent();
16443   MachineFunction::iterator MBBIter = MBB;
16444   ++MBBIter;
16445   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16446   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16447   F->insert(MBBIter, XMMSaveMBB);
16448   F->insert(MBBIter, EndMBB);
16449
16450   // Transfer the remainder of MBB and its successor edges to EndMBB.
16451   EndMBB->splice(EndMBB->begin(), MBB,
16452                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16453   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16454
16455   // The original block will now fall through to the XMM save block.
16456   MBB->addSuccessor(XMMSaveMBB);
16457   // The XMMSaveMBB will fall through to the end block.
16458   XMMSaveMBB->addSuccessor(EndMBB);
16459
16460   // Now add the instructions.
16461   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16462   DebugLoc DL = MI->getDebugLoc();
16463
16464   unsigned CountReg = MI->getOperand(0).getReg();
16465   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16466   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16467
16468   if (!Subtarget->isTargetWin64()) {
16469     // If %al is 0, branch around the XMM save block.
16470     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16471     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16472     MBB->addSuccessor(EndMBB);
16473   }
16474
16475   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16476   // that was just emitted, but clearly shouldn't be "saved".
16477   assert((MI->getNumOperands() <= 3 ||
16478           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16479           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16480          && "Expected last argument to be EFLAGS");
16481   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16482   // In the XMM save block, save all the XMM argument registers.
16483   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16484     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16485     MachineMemOperand *MMO =
16486       F->getMachineMemOperand(
16487           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16488         MachineMemOperand::MOStore,
16489         /*Size=*/16, /*Align=*/16);
16490     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16491       .addFrameIndex(RegSaveFrameIndex)
16492       .addImm(/*Scale=*/1)
16493       .addReg(/*IndexReg=*/0)
16494       .addImm(/*Disp=*/Offset)
16495       .addReg(/*Segment=*/0)
16496       .addReg(MI->getOperand(i).getReg())
16497       .addMemOperand(MMO);
16498   }
16499
16500   MI->eraseFromParent();   // The pseudo instruction is gone now.
16501
16502   return EndMBB;
16503 }
16504
16505 // The EFLAGS operand of SelectItr might be missing a kill marker
16506 // because there were multiple uses of EFLAGS, and ISel didn't know
16507 // which to mark. Figure out whether SelectItr should have had a
16508 // kill marker, and set it if it should. Returns the correct kill
16509 // marker value.
16510 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16511                                      MachineBasicBlock* BB,
16512                                      const TargetRegisterInfo* TRI) {
16513   // Scan forward through BB for a use/def of EFLAGS.
16514   MachineBasicBlock::iterator miI(std::next(SelectItr));
16515   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16516     const MachineInstr& mi = *miI;
16517     if (mi.readsRegister(X86::EFLAGS))
16518       return false;
16519     if (mi.definesRegister(X86::EFLAGS))
16520       break; // Should have kill-flag - update below.
16521   }
16522
16523   // If we hit the end of the block, check whether EFLAGS is live into a
16524   // successor.
16525   if (miI == BB->end()) {
16526     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16527                                           sEnd = BB->succ_end();
16528          sItr != sEnd; ++sItr) {
16529       MachineBasicBlock* succ = *sItr;
16530       if (succ->isLiveIn(X86::EFLAGS))
16531         return false;
16532     }
16533   }
16534
16535   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16536   // out. SelectMI should have a kill flag on EFLAGS.
16537   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16538   return true;
16539 }
16540
16541 MachineBasicBlock *
16542 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16543                                      MachineBasicBlock *BB) const {
16544   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16545   DebugLoc DL = MI->getDebugLoc();
16546
16547   // To "insert" a SELECT_CC instruction, we actually have to insert the
16548   // diamond control-flow pattern.  The incoming instruction knows the
16549   // destination vreg to set, the condition code register to branch on, the
16550   // true/false values to select between, and a branch opcode to use.
16551   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16552   MachineFunction::iterator It = BB;
16553   ++It;
16554
16555   //  thisMBB:
16556   //  ...
16557   //   TrueVal = ...
16558   //   cmpTY ccX, r1, r2
16559   //   bCC copy1MBB
16560   //   fallthrough --> copy0MBB
16561   MachineBasicBlock *thisMBB = BB;
16562   MachineFunction *F = BB->getParent();
16563   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16564   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16565   F->insert(It, copy0MBB);
16566   F->insert(It, sinkMBB);
16567
16568   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16569   // live into the sink and copy blocks.
16570   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16571   if (!MI->killsRegister(X86::EFLAGS) &&
16572       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16573     copy0MBB->addLiveIn(X86::EFLAGS);
16574     sinkMBB->addLiveIn(X86::EFLAGS);
16575   }
16576
16577   // Transfer the remainder of BB and its successor edges to sinkMBB.
16578   sinkMBB->splice(sinkMBB->begin(), BB,
16579                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16580   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16581
16582   // Add the true and fallthrough blocks as its successors.
16583   BB->addSuccessor(copy0MBB);
16584   BB->addSuccessor(sinkMBB);
16585
16586   // Create the conditional branch instruction.
16587   unsigned Opc =
16588     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16589   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16590
16591   //  copy0MBB:
16592   //   %FalseValue = ...
16593   //   # fallthrough to sinkMBB
16594   copy0MBB->addSuccessor(sinkMBB);
16595
16596   //  sinkMBB:
16597   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16598   //  ...
16599   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16600           TII->get(X86::PHI), MI->getOperand(0).getReg())
16601     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16602     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16603
16604   MI->eraseFromParent();   // The pseudo instruction is gone now.
16605   return sinkMBB;
16606 }
16607
16608 MachineBasicBlock *
16609 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16610                                         bool Is64Bit) const {
16611   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16612   DebugLoc DL = MI->getDebugLoc();
16613   MachineFunction *MF = BB->getParent();
16614   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16615
16616   assert(MF->shouldSplitStack());
16617
16618   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16619   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16620
16621   // BB:
16622   //  ... [Till the alloca]
16623   // If stacklet is not large enough, jump to mallocMBB
16624   //
16625   // bumpMBB:
16626   //  Allocate by subtracting from RSP
16627   //  Jump to continueMBB
16628   //
16629   // mallocMBB:
16630   //  Allocate by call to runtime
16631   //
16632   // continueMBB:
16633   //  ...
16634   //  [rest of original BB]
16635   //
16636
16637   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16638   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16639   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16640
16641   MachineRegisterInfo &MRI = MF->getRegInfo();
16642   const TargetRegisterClass *AddrRegClass =
16643     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16644
16645   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16646     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16647     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16648     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16649     sizeVReg = MI->getOperand(1).getReg(),
16650     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16651
16652   MachineFunction::iterator MBBIter = BB;
16653   ++MBBIter;
16654
16655   MF->insert(MBBIter, bumpMBB);
16656   MF->insert(MBBIter, mallocMBB);
16657   MF->insert(MBBIter, continueMBB);
16658
16659   continueMBB->splice(continueMBB->begin(), BB,
16660                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16661   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16662
16663   // Add code to the main basic block to check if the stack limit has been hit,
16664   // and if so, jump to mallocMBB otherwise to bumpMBB.
16665   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16666   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16667     .addReg(tmpSPVReg).addReg(sizeVReg);
16668   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16669     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16670     .addReg(SPLimitVReg);
16671   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16672
16673   // bumpMBB simply decreases the stack pointer, since we know the current
16674   // stacklet has enough space.
16675   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16676     .addReg(SPLimitVReg);
16677   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16678     .addReg(SPLimitVReg);
16679   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16680
16681   // Calls into a routine in libgcc to allocate more space from the heap.
16682   const uint32_t *RegMask =
16683     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16684   if (Is64Bit) {
16685     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16686       .addReg(sizeVReg);
16687     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16688       .addExternalSymbol("__morestack_allocate_stack_space")
16689       .addRegMask(RegMask)
16690       .addReg(X86::RDI, RegState::Implicit)
16691       .addReg(X86::RAX, RegState::ImplicitDefine);
16692   } else {
16693     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16694       .addImm(12);
16695     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16696     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16697       .addExternalSymbol("__morestack_allocate_stack_space")
16698       .addRegMask(RegMask)
16699       .addReg(X86::EAX, RegState::ImplicitDefine);
16700   }
16701
16702   if (!Is64Bit)
16703     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16704       .addImm(16);
16705
16706   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16707     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16708   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16709
16710   // Set up the CFG correctly.
16711   BB->addSuccessor(bumpMBB);
16712   BB->addSuccessor(mallocMBB);
16713   mallocMBB->addSuccessor(continueMBB);
16714   bumpMBB->addSuccessor(continueMBB);
16715
16716   // Take care of the PHI nodes.
16717   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16718           MI->getOperand(0).getReg())
16719     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16720     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16721
16722   // Delete the original pseudo instruction.
16723   MI->eraseFromParent();
16724
16725   // And we're done.
16726   return continueMBB;
16727 }
16728
16729 MachineBasicBlock *
16730 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16731                                           MachineBasicBlock *BB) const {
16732   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16733   DebugLoc DL = MI->getDebugLoc();
16734
16735   assert(!Subtarget->isTargetMacho());
16736
16737   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16738   // non-trivial part is impdef of ESP.
16739
16740   if (Subtarget->isTargetWin64()) {
16741     if (Subtarget->isTargetCygMing()) {
16742       // ___chkstk(Mingw64):
16743       // Clobbers R10, R11, RAX and EFLAGS.
16744       // Updates RSP.
16745       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16746         .addExternalSymbol("___chkstk")
16747         .addReg(X86::RAX, RegState::Implicit)
16748         .addReg(X86::RSP, RegState::Implicit)
16749         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16750         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16751         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16752     } else {
16753       // __chkstk(MSVCRT): does not update stack pointer.
16754       // Clobbers R10, R11 and EFLAGS.
16755       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16756         .addExternalSymbol("__chkstk")
16757         .addReg(X86::RAX, RegState::Implicit)
16758         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16759       // RAX has the offset to be subtracted from RSP.
16760       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16761         .addReg(X86::RSP)
16762         .addReg(X86::RAX);
16763     }
16764   } else {
16765     const char *StackProbeSymbol =
16766       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16767
16768     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16769       .addExternalSymbol(StackProbeSymbol)
16770       .addReg(X86::EAX, RegState::Implicit)
16771       .addReg(X86::ESP, RegState::Implicit)
16772       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16773       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16774       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16775   }
16776
16777   MI->eraseFromParent();   // The pseudo instruction is gone now.
16778   return BB;
16779 }
16780
16781 MachineBasicBlock *
16782 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16783                                       MachineBasicBlock *BB) const {
16784   // This is pretty easy.  We're taking the value that we received from
16785   // our load from the relocation, sticking it in either RDI (x86-64)
16786   // or EAX and doing an indirect call.  The return value will then
16787   // be in the normal return register.
16788   const X86InstrInfo *TII
16789     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16790   DebugLoc DL = MI->getDebugLoc();
16791   MachineFunction *F = BB->getParent();
16792
16793   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16794   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16795
16796   // Get a register mask for the lowered call.
16797   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16798   // proper register mask.
16799   const uint32_t *RegMask =
16800     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16801   if (Subtarget->is64Bit()) {
16802     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16803                                       TII->get(X86::MOV64rm), X86::RDI)
16804     .addReg(X86::RIP)
16805     .addImm(0).addReg(0)
16806     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16807                       MI->getOperand(3).getTargetFlags())
16808     .addReg(0);
16809     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16810     addDirectMem(MIB, X86::RDI);
16811     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16812   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16813     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16814                                       TII->get(X86::MOV32rm), X86::EAX)
16815     .addReg(0)
16816     .addImm(0).addReg(0)
16817     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16818                       MI->getOperand(3).getTargetFlags())
16819     .addReg(0);
16820     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16821     addDirectMem(MIB, X86::EAX);
16822     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16823   } else {
16824     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16825                                       TII->get(X86::MOV32rm), X86::EAX)
16826     .addReg(TII->getGlobalBaseReg(F))
16827     .addImm(0).addReg(0)
16828     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16829                       MI->getOperand(3).getTargetFlags())
16830     .addReg(0);
16831     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16832     addDirectMem(MIB, X86::EAX);
16833     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16834   }
16835
16836   MI->eraseFromParent(); // The pseudo instruction is gone now.
16837   return BB;
16838 }
16839
16840 MachineBasicBlock *
16841 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16842                                     MachineBasicBlock *MBB) const {
16843   DebugLoc DL = MI->getDebugLoc();
16844   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16845
16846   MachineFunction *MF = MBB->getParent();
16847   MachineRegisterInfo &MRI = MF->getRegInfo();
16848
16849   const BasicBlock *BB = MBB->getBasicBlock();
16850   MachineFunction::iterator I = MBB;
16851   ++I;
16852
16853   // Memory Reference
16854   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16855   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16856
16857   unsigned DstReg;
16858   unsigned MemOpndSlot = 0;
16859
16860   unsigned CurOp = 0;
16861
16862   DstReg = MI->getOperand(CurOp++).getReg();
16863   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16864   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16865   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16866   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16867
16868   MemOpndSlot = CurOp;
16869
16870   MVT PVT = getPointerTy();
16871   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16872          "Invalid Pointer Size!");
16873
16874   // For v = setjmp(buf), we generate
16875   //
16876   // thisMBB:
16877   //  buf[LabelOffset] = restoreMBB
16878   //  SjLjSetup restoreMBB
16879   //
16880   // mainMBB:
16881   //  v_main = 0
16882   //
16883   // sinkMBB:
16884   //  v = phi(main, restore)
16885   //
16886   // restoreMBB:
16887   //  v_restore = 1
16888
16889   MachineBasicBlock *thisMBB = MBB;
16890   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16891   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16892   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16893   MF->insert(I, mainMBB);
16894   MF->insert(I, sinkMBB);
16895   MF->push_back(restoreMBB);
16896
16897   MachineInstrBuilder MIB;
16898
16899   // Transfer the remainder of BB and its successor edges to sinkMBB.
16900   sinkMBB->splice(sinkMBB->begin(), MBB,
16901                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16902   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16903
16904   // thisMBB:
16905   unsigned PtrStoreOpc = 0;
16906   unsigned LabelReg = 0;
16907   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16908   Reloc::Model RM = getTargetMachine().getRelocationModel();
16909   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16910                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16911
16912   // Prepare IP either in reg or imm.
16913   if (!UseImmLabel) {
16914     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16915     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16916     LabelReg = MRI.createVirtualRegister(PtrRC);
16917     if (Subtarget->is64Bit()) {
16918       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16919               .addReg(X86::RIP)
16920               .addImm(0)
16921               .addReg(0)
16922               .addMBB(restoreMBB)
16923               .addReg(0);
16924     } else {
16925       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16926       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16927               .addReg(XII->getGlobalBaseReg(MF))
16928               .addImm(0)
16929               .addReg(0)
16930               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16931               .addReg(0);
16932     }
16933   } else
16934     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16935   // Store IP
16936   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16937   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16938     if (i == X86::AddrDisp)
16939       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16940     else
16941       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16942   }
16943   if (!UseImmLabel)
16944     MIB.addReg(LabelReg);
16945   else
16946     MIB.addMBB(restoreMBB);
16947   MIB.setMemRefs(MMOBegin, MMOEnd);
16948   // Setup
16949   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16950           .addMBB(restoreMBB);
16951
16952   const X86RegisterInfo *RegInfo =
16953     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16954   MIB.addRegMask(RegInfo->getNoPreservedMask());
16955   thisMBB->addSuccessor(mainMBB);
16956   thisMBB->addSuccessor(restoreMBB);
16957
16958   // mainMBB:
16959   //  EAX = 0
16960   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16961   mainMBB->addSuccessor(sinkMBB);
16962
16963   // sinkMBB:
16964   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16965           TII->get(X86::PHI), DstReg)
16966     .addReg(mainDstReg).addMBB(mainMBB)
16967     .addReg(restoreDstReg).addMBB(restoreMBB);
16968
16969   // restoreMBB:
16970   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16971   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16972   restoreMBB->addSuccessor(sinkMBB);
16973
16974   MI->eraseFromParent();
16975   return sinkMBB;
16976 }
16977
16978 MachineBasicBlock *
16979 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16980                                      MachineBasicBlock *MBB) const {
16981   DebugLoc DL = MI->getDebugLoc();
16982   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16983
16984   MachineFunction *MF = MBB->getParent();
16985   MachineRegisterInfo &MRI = MF->getRegInfo();
16986
16987   // Memory Reference
16988   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16989   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16990
16991   MVT PVT = getPointerTy();
16992   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16993          "Invalid Pointer Size!");
16994
16995   const TargetRegisterClass *RC =
16996     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16997   unsigned Tmp = MRI.createVirtualRegister(RC);
16998   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16999   const X86RegisterInfo *RegInfo =
17000     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
17001   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17002   unsigned SP = RegInfo->getStackRegister();
17003
17004   MachineInstrBuilder MIB;
17005
17006   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17007   const int64_t SPOffset = 2 * PVT.getStoreSize();
17008
17009   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17010   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17011
17012   // Reload FP
17013   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17014   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17015     MIB.addOperand(MI->getOperand(i));
17016   MIB.setMemRefs(MMOBegin, MMOEnd);
17017   // Reload IP
17018   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17019   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17020     if (i == X86::AddrDisp)
17021       MIB.addDisp(MI->getOperand(i), LabelOffset);
17022     else
17023       MIB.addOperand(MI->getOperand(i));
17024   }
17025   MIB.setMemRefs(MMOBegin, MMOEnd);
17026   // Reload SP
17027   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17028   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17029     if (i == X86::AddrDisp)
17030       MIB.addDisp(MI->getOperand(i), SPOffset);
17031     else
17032       MIB.addOperand(MI->getOperand(i));
17033   }
17034   MIB.setMemRefs(MMOBegin, MMOEnd);
17035   // Jump
17036   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17037
17038   MI->eraseFromParent();
17039   return MBB;
17040 }
17041
17042 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17043 // accumulator loops. Writing back to the accumulator allows the coalescer
17044 // to remove extra copies in the loop.   
17045 MachineBasicBlock *
17046 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17047                                  MachineBasicBlock *MBB) const {
17048   MachineOperand &AddendOp = MI->getOperand(3);
17049
17050   // Bail out early if the addend isn't a register - we can't switch these.
17051   if (!AddendOp.isReg())
17052     return MBB;
17053
17054   MachineFunction &MF = *MBB->getParent();
17055   MachineRegisterInfo &MRI = MF.getRegInfo();
17056
17057   // Check whether the addend is defined by a PHI:
17058   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17059   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17060   if (!AddendDef.isPHI())
17061     return MBB;
17062
17063   // Look for the following pattern:
17064   // loop:
17065   //   %addend = phi [%entry, 0], [%loop, %result]
17066   //   ...
17067   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17068
17069   // Replace with:
17070   //   loop:
17071   //   %addend = phi [%entry, 0], [%loop, %result]
17072   //   ...
17073   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17074
17075   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17076     assert(AddendDef.getOperand(i).isReg());
17077     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17078     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17079     if (&PHISrcInst == MI) {
17080       // Found a matching instruction.
17081       unsigned NewFMAOpc = 0;
17082       switch (MI->getOpcode()) {
17083         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17084         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17085         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17086         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17087         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17088         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17089         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17090         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17091         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17092         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17093         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17094         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17095         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17096         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17097         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17098         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17099         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17100         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17101         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17102         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17103         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17104         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17105         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17106         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17107         default: llvm_unreachable("Unrecognized FMA variant.");
17108       }
17109
17110       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17111       MachineInstrBuilder MIB =
17112         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17113         .addOperand(MI->getOperand(0))
17114         .addOperand(MI->getOperand(3))
17115         .addOperand(MI->getOperand(2))
17116         .addOperand(MI->getOperand(1));
17117       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17118       MI->eraseFromParent();
17119     }
17120   }
17121
17122   return MBB;
17123 }
17124
17125 MachineBasicBlock *
17126 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17127                                                MachineBasicBlock *BB) const {
17128   switch (MI->getOpcode()) {
17129   default: llvm_unreachable("Unexpected instr type to insert");
17130   case X86::TAILJMPd64:
17131   case X86::TAILJMPr64:
17132   case X86::TAILJMPm64:
17133     llvm_unreachable("TAILJMP64 would not be touched here.");
17134   case X86::TCRETURNdi64:
17135   case X86::TCRETURNri64:
17136   case X86::TCRETURNmi64:
17137     return BB;
17138   case X86::WIN_ALLOCA:
17139     return EmitLoweredWinAlloca(MI, BB);
17140   case X86::SEG_ALLOCA_32:
17141     return EmitLoweredSegAlloca(MI, BB, false);
17142   case X86::SEG_ALLOCA_64:
17143     return EmitLoweredSegAlloca(MI, BB, true);
17144   case X86::TLSCall_32:
17145   case X86::TLSCall_64:
17146     return EmitLoweredTLSCall(MI, BB);
17147   case X86::CMOV_GR8:
17148   case X86::CMOV_FR32:
17149   case X86::CMOV_FR64:
17150   case X86::CMOV_V4F32:
17151   case X86::CMOV_V2F64:
17152   case X86::CMOV_V2I64:
17153   case X86::CMOV_V8F32:
17154   case X86::CMOV_V4F64:
17155   case X86::CMOV_V4I64:
17156   case X86::CMOV_V16F32:
17157   case X86::CMOV_V8F64:
17158   case X86::CMOV_V8I64:
17159   case X86::CMOV_GR16:
17160   case X86::CMOV_GR32:
17161   case X86::CMOV_RFP32:
17162   case X86::CMOV_RFP64:
17163   case X86::CMOV_RFP80:
17164     return EmitLoweredSelect(MI, BB);
17165
17166   case X86::FP32_TO_INT16_IN_MEM:
17167   case X86::FP32_TO_INT32_IN_MEM:
17168   case X86::FP32_TO_INT64_IN_MEM:
17169   case X86::FP64_TO_INT16_IN_MEM:
17170   case X86::FP64_TO_INT32_IN_MEM:
17171   case X86::FP64_TO_INT64_IN_MEM:
17172   case X86::FP80_TO_INT16_IN_MEM:
17173   case X86::FP80_TO_INT32_IN_MEM:
17174   case X86::FP80_TO_INT64_IN_MEM: {
17175     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17176     DebugLoc DL = MI->getDebugLoc();
17177
17178     // Change the floating point control register to use "round towards zero"
17179     // mode when truncating to an integer value.
17180     MachineFunction *F = BB->getParent();
17181     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17182     addFrameReference(BuildMI(*BB, MI, DL,
17183                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17184
17185     // Load the old value of the high byte of the control word...
17186     unsigned OldCW =
17187       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17188     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17189                       CWFrameIdx);
17190
17191     // Set the high part to be round to zero...
17192     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17193       .addImm(0xC7F);
17194
17195     // Reload the modified control word now...
17196     addFrameReference(BuildMI(*BB, MI, DL,
17197                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17198
17199     // Restore the memory image of control word to original value
17200     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17201       .addReg(OldCW);
17202
17203     // Get the X86 opcode to use.
17204     unsigned Opc;
17205     switch (MI->getOpcode()) {
17206     default: llvm_unreachable("illegal opcode!");
17207     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17208     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17209     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17210     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17211     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17212     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17213     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17214     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17215     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17216     }
17217
17218     X86AddressMode AM;
17219     MachineOperand &Op = MI->getOperand(0);
17220     if (Op.isReg()) {
17221       AM.BaseType = X86AddressMode::RegBase;
17222       AM.Base.Reg = Op.getReg();
17223     } else {
17224       AM.BaseType = X86AddressMode::FrameIndexBase;
17225       AM.Base.FrameIndex = Op.getIndex();
17226     }
17227     Op = MI->getOperand(1);
17228     if (Op.isImm())
17229       AM.Scale = Op.getImm();
17230     Op = MI->getOperand(2);
17231     if (Op.isImm())
17232       AM.IndexReg = Op.getImm();
17233     Op = MI->getOperand(3);
17234     if (Op.isGlobal()) {
17235       AM.GV = Op.getGlobal();
17236     } else {
17237       AM.Disp = Op.getImm();
17238     }
17239     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17240                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17241
17242     // Reload the original control word now.
17243     addFrameReference(BuildMI(*BB, MI, DL,
17244                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17245
17246     MI->eraseFromParent();   // The pseudo instruction is gone now.
17247     return BB;
17248   }
17249     // String/text processing lowering.
17250   case X86::PCMPISTRM128REG:
17251   case X86::VPCMPISTRM128REG:
17252   case X86::PCMPISTRM128MEM:
17253   case X86::VPCMPISTRM128MEM:
17254   case X86::PCMPESTRM128REG:
17255   case X86::VPCMPESTRM128REG:
17256   case X86::PCMPESTRM128MEM:
17257   case X86::VPCMPESTRM128MEM:
17258     assert(Subtarget->hasSSE42() &&
17259            "Target must have SSE4.2 or AVX features enabled");
17260     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17261
17262   // String/text processing lowering.
17263   case X86::PCMPISTRIREG:
17264   case X86::VPCMPISTRIREG:
17265   case X86::PCMPISTRIMEM:
17266   case X86::VPCMPISTRIMEM:
17267   case X86::PCMPESTRIREG:
17268   case X86::VPCMPESTRIREG:
17269   case X86::PCMPESTRIMEM:
17270   case X86::VPCMPESTRIMEM:
17271     assert(Subtarget->hasSSE42() &&
17272            "Target must have SSE4.2 or AVX features enabled");
17273     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17274
17275   // Thread synchronization.
17276   case X86::MONITOR:
17277     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17278
17279   // xbegin
17280   case X86::XBEGIN:
17281     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17282
17283   // Atomic Lowering.
17284   case X86::ATOMAND8:
17285   case X86::ATOMAND16:
17286   case X86::ATOMAND32:
17287   case X86::ATOMAND64:
17288     // Fall through
17289   case X86::ATOMOR8:
17290   case X86::ATOMOR16:
17291   case X86::ATOMOR32:
17292   case X86::ATOMOR64:
17293     // Fall through
17294   case X86::ATOMXOR16:
17295   case X86::ATOMXOR8:
17296   case X86::ATOMXOR32:
17297   case X86::ATOMXOR64:
17298     // Fall through
17299   case X86::ATOMNAND8:
17300   case X86::ATOMNAND16:
17301   case X86::ATOMNAND32:
17302   case X86::ATOMNAND64:
17303     // Fall through
17304   case X86::ATOMMAX8:
17305   case X86::ATOMMAX16:
17306   case X86::ATOMMAX32:
17307   case X86::ATOMMAX64:
17308     // Fall through
17309   case X86::ATOMMIN8:
17310   case X86::ATOMMIN16:
17311   case X86::ATOMMIN32:
17312   case X86::ATOMMIN64:
17313     // Fall through
17314   case X86::ATOMUMAX8:
17315   case X86::ATOMUMAX16:
17316   case X86::ATOMUMAX32:
17317   case X86::ATOMUMAX64:
17318     // Fall through
17319   case X86::ATOMUMIN8:
17320   case X86::ATOMUMIN16:
17321   case X86::ATOMUMIN32:
17322   case X86::ATOMUMIN64:
17323     return EmitAtomicLoadArith(MI, BB);
17324
17325   // This group does 64-bit operations on a 32-bit host.
17326   case X86::ATOMAND6432:
17327   case X86::ATOMOR6432:
17328   case X86::ATOMXOR6432:
17329   case X86::ATOMNAND6432:
17330   case X86::ATOMADD6432:
17331   case X86::ATOMSUB6432:
17332   case X86::ATOMMAX6432:
17333   case X86::ATOMMIN6432:
17334   case X86::ATOMUMAX6432:
17335   case X86::ATOMUMIN6432:
17336   case X86::ATOMSWAP6432:
17337     return EmitAtomicLoadArith6432(MI, BB);
17338
17339   case X86::VASTART_SAVE_XMM_REGS:
17340     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17341
17342   case X86::VAARG_64:
17343     return EmitVAARG64WithCustomInserter(MI, BB);
17344
17345   case X86::EH_SjLj_SetJmp32:
17346   case X86::EH_SjLj_SetJmp64:
17347     return emitEHSjLjSetJmp(MI, BB);
17348
17349   case X86::EH_SjLj_LongJmp32:
17350   case X86::EH_SjLj_LongJmp64:
17351     return emitEHSjLjLongJmp(MI, BB);
17352
17353   case TargetOpcode::STACKMAP:
17354   case TargetOpcode::PATCHPOINT:
17355     return emitPatchPoint(MI, BB);
17356
17357   case X86::VFMADDPDr213r:
17358   case X86::VFMADDPSr213r:
17359   case X86::VFMADDSDr213r:
17360   case X86::VFMADDSSr213r:
17361   case X86::VFMSUBPDr213r:
17362   case X86::VFMSUBPSr213r:
17363   case X86::VFMSUBSDr213r:
17364   case X86::VFMSUBSSr213r:
17365   case X86::VFNMADDPDr213r:
17366   case X86::VFNMADDPSr213r:
17367   case X86::VFNMADDSDr213r:
17368   case X86::VFNMADDSSr213r:
17369   case X86::VFNMSUBPDr213r:
17370   case X86::VFNMSUBPSr213r:
17371   case X86::VFNMSUBSDr213r:
17372   case X86::VFNMSUBSSr213r:
17373   case X86::VFMADDPDr213rY:
17374   case X86::VFMADDPSr213rY:
17375   case X86::VFMSUBPDr213rY:
17376   case X86::VFMSUBPSr213rY:
17377   case X86::VFNMADDPDr213rY:
17378   case X86::VFNMADDPSr213rY:
17379   case X86::VFNMSUBPDr213rY:
17380   case X86::VFNMSUBPSr213rY:
17381     return emitFMA3Instr(MI, BB);
17382   }
17383 }
17384
17385 //===----------------------------------------------------------------------===//
17386 //                           X86 Optimization Hooks
17387 //===----------------------------------------------------------------------===//
17388
17389 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17390                                                       APInt &KnownZero,
17391                                                       APInt &KnownOne,
17392                                                       const SelectionDAG &DAG,
17393                                                       unsigned Depth) const {
17394   unsigned BitWidth = KnownZero.getBitWidth();
17395   unsigned Opc = Op.getOpcode();
17396   assert((Opc >= ISD::BUILTIN_OP_END ||
17397           Opc == ISD::INTRINSIC_WO_CHAIN ||
17398           Opc == ISD::INTRINSIC_W_CHAIN ||
17399           Opc == ISD::INTRINSIC_VOID) &&
17400          "Should use MaskedValueIsZero if you don't know whether Op"
17401          " is a target node!");
17402
17403   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17404   switch (Opc) {
17405   default: break;
17406   case X86ISD::ADD:
17407   case X86ISD::SUB:
17408   case X86ISD::ADC:
17409   case X86ISD::SBB:
17410   case X86ISD::SMUL:
17411   case X86ISD::UMUL:
17412   case X86ISD::INC:
17413   case X86ISD::DEC:
17414   case X86ISD::OR:
17415   case X86ISD::XOR:
17416   case X86ISD::AND:
17417     // These nodes' second result is a boolean.
17418     if (Op.getResNo() == 0)
17419       break;
17420     // Fallthrough
17421   case X86ISD::SETCC:
17422     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17423     break;
17424   case ISD::INTRINSIC_WO_CHAIN: {
17425     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17426     unsigned NumLoBits = 0;
17427     switch (IntId) {
17428     default: break;
17429     case Intrinsic::x86_sse_movmsk_ps:
17430     case Intrinsic::x86_avx_movmsk_ps_256:
17431     case Intrinsic::x86_sse2_movmsk_pd:
17432     case Intrinsic::x86_avx_movmsk_pd_256:
17433     case Intrinsic::x86_mmx_pmovmskb:
17434     case Intrinsic::x86_sse2_pmovmskb_128:
17435     case Intrinsic::x86_avx2_pmovmskb: {
17436       // High bits of movmskp{s|d}, pmovmskb are known zero.
17437       switch (IntId) {
17438         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17439         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17440         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17441         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17442         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17443         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17444         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17445         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17446       }
17447       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17448       break;
17449     }
17450     }
17451     break;
17452   }
17453   }
17454 }
17455
17456 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17457   SDValue Op,
17458   const SelectionDAG &,
17459   unsigned Depth) const {
17460   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17461   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17462     return Op.getValueType().getScalarType().getSizeInBits();
17463
17464   // Fallback case.
17465   return 1;
17466 }
17467
17468 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17469 /// node is a GlobalAddress + offset.
17470 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17471                                        const GlobalValue* &GA,
17472                                        int64_t &Offset) const {
17473   if (N->getOpcode() == X86ISD::Wrapper) {
17474     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17475       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17476       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17477       return true;
17478     }
17479   }
17480   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17481 }
17482
17483 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17484 /// same as extracting the high 128-bit part of 256-bit vector and then
17485 /// inserting the result into the low part of a new 256-bit vector
17486 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17487   EVT VT = SVOp->getValueType(0);
17488   unsigned NumElems = VT.getVectorNumElements();
17489
17490   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17491   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17492     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17493         SVOp->getMaskElt(j) >= 0)
17494       return false;
17495
17496   return true;
17497 }
17498
17499 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17500 /// same as extracting the low 128-bit part of 256-bit vector and then
17501 /// inserting the result into the high part of a new 256-bit vector
17502 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17503   EVT VT = SVOp->getValueType(0);
17504   unsigned NumElems = VT.getVectorNumElements();
17505
17506   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17507   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17508     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17509         SVOp->getMaskElt(j) >= 0)
17510       return false;
17511
17512   return true;
17513 }
17514
17515 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17516 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17517                                         TargetLowering::DAGCombinerInfo &DCI,
17518                                         const X86Subtarget* Subtarget) {
17519   SDLoc dl(N);
17520   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17521   SDValue V1 = SVOp->getOperand(0);
17522   SDValue V2 = SVOp->getOperand(1);
17523   EVT VT = SVOp->getValueType(0);
17524   unsigned NumElems = VT.getVectorNumElements();
17525
17526   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17527       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17528     //
17529     //                   0,0,0,...
17530     //                      |
17531     //    V      UNDEF    BUILD_VECTOR    UNDEF
17532     //     \      /           \           /
17533     //  CONCAT_VECTOR         CONCAT_VECTOR
17534     //         \                  /
17535     //          \                /
17536     //          RESULT: V + zero extended
17537     //
17538     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17539         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17540         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17541       return SDValue();
17542
17543     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17544       return SDValue();
17545
17546     // To match the shuffle mask, the first half of the mask should
17547     // be exactly the first vector, and all the rest a splat with the
17548     // first element of the second one.
17549     for (unsigned i = 0; i != NumElems/2; ++i)
17550       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17551           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17552         return SDValue();
17553
17554     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17555     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17556       if (Ld->hasNUsesOfValue(1, 0)) {
17557         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17558         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17559         SDValue ResNode =
17560           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17561                                   Ld->getMemoryVT(),
17562                                   Ld->getPointerInfo(),
17563                                   Ld->getAlignment(),
17564                                   false/*isVolatile*/, true/*ReadMem*/,
17565                                   false/*WriteMem*/);
17566
17567         // Make sure the newly-created LOAD is in the same position as Ld in
17568         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17569         // and update uses of Ld's output chain to use the TokenFactor.
17570         if (Ld->hasAnyUseOfValue(1)) {
17571           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17572                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17573           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17574           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17575                                  SDValue(ResNode.getNode(), 1));
17576         }
17577
17578         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17579       }
17580     }
17581
17582     // Emit a zeroed vector and insert the desired subvector on its
17583     // first half.
17584     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17585     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17586     return DCI.CombineTo(N, InsV);
17587   }
17588
17589   //===--------------------------------------------------------------------===//
17590   // Combine some shuffles into subvector extracts and inserts:
17591   //
17592
17593   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17594   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17595     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17596     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17597     return DCI.CombineTo(N, InsV);
17598   }
17599
17600   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17601   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17602     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17603     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17604     return DCI.CombineTo(N, InsV);
17605   }
17606
17607   return SDValue();
17608 }
17609
17610 /// PerformShuffleCombine - Performs several different shuffle combines.
17611 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17612                                      TargetLowering::DAGCombinerInfo &DCI,
17613                                      const X86Subtarget *Subtarget) {
17614   SDLoc dl(N);
17615   SDValue N0 = N->getOperand(0);
17616   SDValue N1 = N->getOperand(1);
17617   EVT VT = N->getValueType(0);
17618
17619   // Don't create instructions with illegal types after legalize types has run.
17620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17621   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17622     return SDValue();
17623
17624   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17625   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17626       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17627     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17628
17629   // During Type Legalization, when promoting illegal vector types,
17630   // the backend might introduce new shuffle dag nodes and bitcasts.
17631   //
17632   // This code performs the following transformation:
17633   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17634   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17635   //
17636   // We do this only if both the bitcast and the BINOP dag nodes have
17637   // one use. Also, perform this transformation only if the new binary
17638   // operation is legal. This is to avoid introducing dag nodes that
17639   // potentially need to be further expanded (or custom lowered) into a
17640   // less optimal sequence of dag nodes.
17641   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17642       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17643       N0.getOpcode() == ISD::BITCAST) {
17644     SDValue BC0 = N0.getOperand(0);
17645     EVT SVT = BC0.getValueType();
17646     unsigned Opcode = BC0.getOpcode();
17647     unsigned NumElts = VT.getVectorNumElements();
17648     
17649     if (BC0.hasOneUse() && SVT.isVector() &&
17650         SVT.getVectorNumElements() * 2 == NumElts &&
17651         TLI.isOperationLegal(Opcode, VT)) {
17652       bool CanFold = false;
17653       switch (Opcode) {
17654       default : break;
17655       case ISD::ADD :
17656       case ISD::FADD :
17657       case ISD::SUB :
17658       case ISD::FSUB :
17659       case ISD::MUL :
17660       case ISD::FMUL :
17661         CanFold = true;
17662       }
17663
17664       unsigned SVTNumElts = SVT.getVectorNumElements();
17665       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17666       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17667         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17668       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17669         CanFold = SVOp->getMaskElt(i) < 0;
17670
17671       if (CanFold) {
17672         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17673         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17674         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17675         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17676       }
17677     }
17678   }
17679
17680   // Only handle 128 wide vector from here on.
17681   if (!VT.is128BitVector())
17682     return SDValue();
17683
17684   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17685   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17686   // consecutive, non-overlapping, and in the right order.
17687   SmallVector<SDValue, 16> Elts;
17688   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17689     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17690
17691   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17692 }
17693
17694 /// PerformTruncateCombine - Converts truncate operation to
17695 /// a sequence of vector shuffle operations.
17696 /// It is possible when we truncate 256-bit vector to 128-bit vector
17697 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17698                                       TargetLowering::DAGCombinerInfo &DCI,
17699                                       const X86Subtarget *Subtarget)  {
17700   return SDValue();
17701 }
17702
17703 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17704 /// specific shuffle of a load can be folded into a single element load.
17705 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17706 /// shuffles have been customed lowered so we need to handle those here.
17707 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17708                                          TargetLowering::DAGCombinerInfo &DCI) {
17709   if (DCI.isBeforeLegalizeOps())
17710     return SDValue();
17711
17712   SDValue InVec = N->getOperand(0);
17713   SDValue EltNo = N->getOperand(1);
17714
17715   if (!isa<ConstantSDNode>(EltNo))
17716     return SDValue();
17717
17718   EVT VT = InVec.getValueType();
17719
17720   bool HasShuffleIntoBitcast = false;
17721   if (InVec.getOpcode() == ISD::BITCAST) {
17722     // Don't duplicate a load with other uses.
17723     if (!InVec.hasOneUse())
17724       return SDValue();
17725     EVT BCVT = InVec.getOperand(0).getValueType();
17726     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17727       return SDValue();
17728     InVec = InVec.getOperand(0);
17729     HasShuffleIntoBitcast = true;
17730   }
17731
17732   if (!isTargetShuffle(InVec.getOpcode()))
17733     return SDValue();
17734
17735   // Don't duplicate a load with other uses.
17736   if (!InVec.hasOneUse())
17737     return SDValue();
17738
17739   SmallVector<int, 16> ShuffleMask;
17740   bool UnaryShuffle;
17741   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17742                             UnaryShuffle))
17743     return SDValue();
17744
17745   // Select the input vector, guarding against out of range extract vector.
17746   unsigned NumElems = VT.getVectorNumElements();
17747   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17748   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17749   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17750                                          : InVec.getOperand(1);
17751
17752   // If inputs to shuffle are the same for both ops, then allow 2 uses
17753   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17754
17755   if (LdNode.getOpcode() == ISD::BITCAST) {
17756     // Don't duplicate a load with other uses.
17757     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17758       return SDValue();
17759
17760     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17761     LdNode = LdNode.getOperand(0);
17762   }
17763
17764   if (!ISD::isNormalLoad(LdNode.getNode()))
17765     return SDValue();
17766
17767   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17768
17769   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17770     return SDValue();
17771
17772   if (HasShuffleIntoBitcast) {
17773     // If there's a bitcast before the shuffle, check if the load type and
17774     // alignment is valid.
17775     unsigned Align = LN0->getAlignment();
17776     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17777     unsigned NewAlign = TLI.getDataLayout()->
17778       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17779
17780     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17781       return SDValue();
17782   }
17783
17784   // All checks match so transform back to vector_shuffle so that DAG combiner
17785   // can finish the job
17786   SDLoc dl(N);
17787
17788   // Create shuffle node taking into account the case that its a unary shuffle
17789   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17790   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17791                                  InVec.getOperand(0), Shuffle,
17792                                  &ShuffleMask[0]);
17793   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17794   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17795                      EltNo);
17796 }
17797
17798 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17799 /// generation and convert it from being a bunch of shuffles and extracts
17800 /// to a simple store and scalar loads to extract the elements.
17801 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17802                                          TargetLowering::DAGCombinerInfo &DCI) {
17803   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17804   if (NewOp.getNode())
17805     return NewOp;
17806
17807   SDValue InputVector = N->getOperand(0);
17808
17809   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17810   // from mmx to v2i32 has a single usage.
17811   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17812       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17813       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17814     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17815                        N->getValueType(0),
17816                        InputVector.getNode()->getOperand(0));
17817
17818   // Only operate on vectors of 4 elements, where the alternative shuffling
17819   // gets to be more expensive.
17820   if (InputVector.getValueType() != MVT::v4i32)
17821     return SDValue();
17822
17823   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17824   // single use which is a sign-extend or zero-extend, and all elements are
17825   // used.
17826   SmallVector<SDNode *, 4> Uses;
17827   unsigned ExtractedElements = 0;
17828   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17829        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17830     if (UI.getUse().getResNo() != InputVector.getResNo())
17831       return SDValue();
17832
17833     SDNode *Extract = *UI;
17834     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17835       return SDValue();
17836
17837     if (Extract->getValueType(0) != MVT::i32)
17838       return SDValue();
17839     if (!Extract->hasOneUse())
17840       return SDValue();
17841     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17842         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17843       return SDValue();
17844     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17845       return SDValue();
17846
17847     // Record which element was extracted.
17848     ExtractedElements |=
17849       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17850
17851     Uses.push_back(Extract);
17852   }
17853
17854   // If not all the elements were used, this may not be worthwhile.
17855   if (ExtractedElements != 15)
17856     return SDValue();
17857
17858   // Ok, we've now decided to do the transformation.
17859   SDLoc dl(InputVector);
17860
17861   // Store the value to a temporary stack slot.
17862   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17863   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17864                             MachinePointerInfo(), false, false, 0);
17865
17866   // Replace each use (extract) with a load of the appropriate element.
17867   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17868        UE = Uses.end(); UI != UE; ++UI) {
17869     SDNode *Extract = *UI;
17870
17871     // cOMpute the element's address.
17872     SDValue Idx = Extract->getOperand(1);
17873     unsigned EltSize =
17874         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17875     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17876     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17877     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17878
17879     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17880                                      StackPtr, OffsetVal);
17881
17882     // Load the scalar.
17883     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17884                                      ScalarAddr, MachinePointerInfo(),
17885                                      false, false, false, 0);
17886
17887     // Replace the exact with the load.
17888     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17889   }
17890
17891   // The replacement was made in place; don't return anything.
17892   return SDValue();
17893 }
17894
17895 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17896 static std::pair<unsigned, bool>
17897 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17898                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17899   if (!VT.isVector())
17900     return std::make_pair(0, false);
17901
17902   bool NeedSplit = false;
17903   switch (VT.getSimpleVT().SimpleTy) {
17904   default: return std::make_pair(0, false);
17905   case MVT::v32i8:
17906   case MVT::v16i16:
17907   case MVT::v8i32:
17908     if (!Subtarget->hasAVX2())
17909       NeedSplit = true;
17910     if (!Subtarget->hasAVX())
17911       return std::make_pair(0, false);
17912     break;
17913   case MVT::v16i8:
17914   case MVT::v8i16:
17915   case MVT::v4i32:
17916     if (!Subtarget->hasSSE2())
17917       return std::make_pair(0, false);
17918   }
17919
17920   // SSE2 has only a small subset of the operations.
17921   bool hasUnsigned = Subtarget->hasSSE41() ||
17922                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17923   bool hasSigned = Subtarget->hasSSE41() ||
17924                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17925
17926   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17927
17928   unsigned Opc = 0;
17929   // Check for x CC y ? x : y.
17930   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17931       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17932     switch (CC) {
17933     default: break;
17934     case ISD::SETULT:
17935     case ISD::SETULE:
17936       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17937     case ISD::SETUGT:
17938     case ISD::SETUGE:
17939       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17940     case ISD::SETLT:
17941     case ISD::SETLE:
17942       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17943     case ISD::SETGT:
17944     case ISD::SETGE:
17945       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17946     }
17947   // Check for x CC y ? y : x -- a min/max with reversed arms.
17948   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17949              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17950     switch (CC) {
17951     default: break;
17952     case ISD::SETULT:
17953     case ISD::SETULE:
17954       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17955     case ISD::SETUGT:
17956     case ISD::SETUGE:
17957       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17958     case ISD::SETLT:
17959     case ISD::SETLE:
17960       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17961     case ISD::SETGT:
17962     case ISD::SETGE:
17963       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17964     }
17965   }
17966
17967   return std::make_pair(Opc, NeedSplit);
17968 }
17969
17970 static SDValue
17971 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17972                                       const X86Subtarget *Subtarget) {
17973   SDLoc dl(N);
17974   SDValue Cond = N->getOperand(0);
17975   SDValue LHS = N->getOperand(1);
17976   SDValue RHS = N->getOperand(2);
17977
17978   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17979     SDValue CondSrc = Cond->getOperand(0);
17980     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17981       Cond = CondSrc->getOperand(0);
17982   }
17983
17984   MVT VT = N->getSimpleValueType(0);
17985   MVT EltVT = VT.getVectorElementType();
17986   unsigned NumElems = VT.getVectorNumElements();
17987   // There is no blend with immediate in AVX-512.
17988   if (VT.is512BitVector())
17989     return SDValue();
17990
17991   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17992     return SDValue();
17993   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17994     return SDValue();
17995
17996   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17997     return SDValue();
17998
17999   unsigned MaskValue = 0;
18000   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18001     return SDValue();
18002
18003   SmallVector<int, 8> ShuffleMask(NumElems, -1);
18004   for (unsigned i = 0; i < NumElems; ++i) {
18005     // Be sure we emit undef where we can.
18006     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18007       ShuffleMask[i] = -1;
18008     else
18009       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18010   }
18011
18012   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18013 }
18014
18015 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18016 /// nodes.
18017 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18018                                     TargetLowering::DAGCombinerInfo &DCI,
18019                                     const X86Subtarget *Subtarget) {
18020   SDLoc DL(N);
18021   SDValue Cond = N->getOperand(0);
18022   // Get the LHS/RHS of the select.
18023   SDValue LHS = N->getOperand(1);
18024   SDValue RHS = N->getOperand(2);
18025   EVT VT = LHS.getValueType();
18026   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18027
18028   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18029   // instructions match the semantics of the common C idiom x<y?x:y but not
18030   // x<=y?x:y, because of how they handle negative zero (which can be
18031   // ignored in unsafe-math mode).
18032   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18033       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18034       (Subtarget->hasSSE2() ||
18035        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18036     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18037
18038     unsigned Opcode = 0;
18039     // Check for x CC y ? x : y.
18040     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18041         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18042       switch (CC) {
18043       default: break;
18044       case ISD::SETULT:
18045         // Converting this to a min would handle NaNs incorrectly, and swapping
18046         // the operands would cause it to handle comparisons between positive
18047         // and negative zero incorrectly.
18048         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18049           if (!DAG.getTarget().Options.UnsafeFPMath &&
18050               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18051             break;
18052           std::swap(LHS, RHS);
18053         }
18054         Opcode = X86ISD::FMIN;
18055         break;
18056       case ISD::SETOLE:
18057         // Converting this to a min would handle comparisons between positive
18058         // and negative zero incorrectly.
18059         if (!DAG.getTarget().Options.UnsafeFPMath &&
18060             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18061           break;
18062         Opcode = X86ISD::FMIN;
18063         break;
18064       case ISD::SETULE:
18065         // Converting this to a min would handle both negative zeros and NaNs
18066         // incorrectly, but we can swap the operands to fix both.
18067         std::swap(LHS, RHS);
18068       case ISD::SETOLT:
18069       case ISD::SETLT:
18070       case ISD::SETLE:
18071         Opcode = X86ISD::FMIN;
18072         break;
18073
18074       case ISD::SETOGE:
18075         // Converting this to a max would handle comparisons between positive
18076         // and negative zero incorrectly.
18077         if (!DAG.getTarget().Options.UnsafeFPMath &&
18078             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18079           break;
18080         Opcode = X86ISD::FMAX;
18081         break;
18082       case ISD::SETUGT:
18083         // Converting this to a max would handle NaNs incorrectly, and swapping
18084         // the operands would cause it to handle comparisons between positive
18085         // and negative zero incorrectly.
18086         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18087           if (!DAG.getTarget().Options.UnsafeFPMath &&
18088               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18089             break;
18090           std::swap(LHS, RHS);
18091         }
18092         Opcode = X86ISD::FMAX;
18093         break;
18094       case ISD::SETUGE:
18095         // Converting this to a max would handle both negative zeros and NaNs
18096         // incorrectly, but we can swap the operands to fix both.
18097         std::swap(LHS, RHS);
18098       case ISD::SETOGT:
18099       case ISD::SETGT:
18100       case ISD::SETGE:
18101         Opcode = X86ISD::FMAX;
18102         break;
18103       }
18104     // Check for x CC y ? y : x -- a min/max with reversed arms.
18105     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18106                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18107       switch (CC) {
18108       default: break;
18109       case ISD::SETOGE:
18110         // Converting this to a min would handle comparisons between positive
18111         // and negative zero incorrectly, and swapping the operands would
18112         // cause it to handle NaNs incorrectly.
18113         if (!DAG.getTarget().Options.UnsafeFPMath &&
18114             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18115           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18116             break;
18117           std::swap(LHS, RHS);
18118         }
18119         Opcode = X86ISD::FMIN;
18120         break;
18121       case ISD::SETUGT:
18122         // Converting this to a min would handle NaNs incorrectly.
18123         if (!DAG.getTarget().Options.UnsafeFPMath &&
18124             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18125           break;
18126         Opcode = X86ISD::FMIN;
18127         break;
18128       case ISD::SETUGE:
18129         // Converting this to a min would handle both negative zeros and NaNs
18130         // incorrectly, but we can swap the operands to fix both.
18131         std::swap(LHS, RHS);
18132       case ISD::SETOGT:
18133       case ISD::SETGT:
18134       case ISD::SETGE:
18135         Opcode = X86ISD::FMIN;
18136         break;
18137
18138       case ISD::SETULT:
18139         // Converting this to a max would handle NaNs incorrectly.
18140         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18141           break;
18142         Opcode = X86ISD::FMAX;
18143         break;
18144       case ISD::SETOLE:
18145         // Converting this to a max would handle comparisons between positive
18146         // and negative zero incorrectly, and swapping the operands would
18147         // cause it to handle NaNs incorrectly.
18148         if (!DAG.getTarget().Options.UnsafeFPMath &&
18149             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18150           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18151             break;
18152           std::swap(LHS, RHS);
18153         }
18154         Opcode = X86ISD::FMAX;
18155         break;
18156       case ISD::SETULE:
18157         // Converting this to a max would handle both negative zeros and NaNs
18158         // incorrectly, but we can swap the operands to fix both.
18159         std::swap(LHS, RHS);
18160       case ISD::SETOLT:
18161       case ISD::SETLT:
18162       case ISD::SETLE:
18163         Opcode = X86ISD::FMAX;
18164         break;
18165       }
18166     }
18167
18168     if (Opcode)
18169       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18170   }
18171
18172   EVT CondVT = Cond.getValueType();
18173   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18174       CondVT.getVectorElementType() == MVT::i1) {
18175     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18176     // lowering on AVX-512. In this case we convert it to
18177     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18178     // The same situation for all 128 and 256-bit vectors of i8 and i16
18179     EVT OpVT = LHS.getValueType();
18180     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18181         (OpVT.getVectorElementType() == MVT::i8 ||
18182          OpVT.getVectorElementType() == MVT::i16)) {
18183       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18184       DCI.AddToWorklist(Cond.getNode());
18185       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18186     }
18187   }
18188   // If this is a select between two integer constants, try to do some
18189   // optimizations.
18190   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18191     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18192       // Don't do this for crazy integer types.
18193       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18194         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18195         // so that TrueC (the true value) is larger than FalseC.
18196         bool NeedsCondInvert = false;
18197
18198         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18199             // Efficiently invertible.
18200             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
18201              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
18202               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18203           NeedsCondInvert = true;
18204           std::swap(TrueC, FalseC);
18205         }
18206
18207         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18208         if (FalseC->getAPIntValue() == 0 &&
18209             TrueC->getAPIntValue().isPowerOf2()) {
18210           if (NeedsCondInvert) // Invert the condition if needed.
18211             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18212                                DAG.getConstant(1, Cond.getValueType()));
18213
18214           // Zero extend the condition if needed.
18215           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18216
18217           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18218           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18219                              DAG.getConstant(ShAmt, MVT::i8));
18220         }
18221
18222         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18223         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18224           if (NeedsCondInvert) // Invert the condition if needed.
18225             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18226                                DAG.getConstant(1, Cond.getValueType()));
18227
18228           // Zero extend the condition if needed.
18229           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18230                              FalseC->getValueType(0), Cond);
18231           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18232                              SDValue(FalseC, 0));
18233         }
18234
18235         // Optimize cases that will turn into an LEA instruction.  This requires
18236         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18237         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18238           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18239           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18240
18241           bool isFastMultiplier = false;
18242           if (Diff < 10) {
18243             switch ((unsigned char)Diff) {
18244               default: break;
18245               case 1:  // result = add base, cond
18246               case 2:  // result = lea base(    , cond*2)
18247               case 3:  // result = lea base(cond, cond*2)
18248               case 4:  // result = lea base(    , cond*4)
18249               case 5:  // result = lea base(cond, cond*4)
18250               case 8:  // result = lea base(    , cond*8)
18251               case 9:  // result = lea base(cond, cond*8)
18252                 isFastMultiplier = true;
18253                 break;
18254             }
18255           }
18256
18257           if (isFastMultiplier) {
18258             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18259             if (NeedsCondInvert) // Invert the condition if needed.
18260               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18261                                  DAG.getConstant(1, Cond.getValueType()));
18262
18263             // Zero extend the condition if needed.
18264             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18265                                Cond);
18266             // Scale the condition by the difference.
18267             if (Diff != 1)
18268               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18269                                  DAG.getConstant(Diff, Cond.getValueType()));
18270
18271             // Add the base if non-zero.
18272             if (FalseC->getAPIntValue() != 0)
18273               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18274                                  SDValue(FalseC, 0));
18275             return Cond;
18276           }
18277         }
18278       }
18279   }
18280
18281   // Canonicalize max and min:
18282   // (x > y) ? x : y -> (x >= y) ? x : y
18283   // (x < y) ? x : y -> (x <= y) ? x : y
18284   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18285   // the need for an extra compare
18286   // against zero. e.g.
18287   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18288   // subl   %esi, %edi
18289   // testl  %edi, %edi
18290   // movl   $0, %eax
18291   // cmovgl %edi, %eax
18292   // =>
18293   // xorl   %eax, %eax
18294   // subl   %esi, $edi
18295   // cmovsl %eax, %edi
18296   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18297       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18298       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18299     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18300     switch (CC) {
18301     default: break;
18302     case ISD::SETLT:
18303     case ISD::SETGT: {
18304       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18305       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18306                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18307       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18308     }
18309     }
18310   }
18311
18312   // Early exit check
18313   if (!TLI.isTypeLegal(VT))
18314     return SDValue();
18315
18316   // Match VSELECTs into subs with unsigned saturation.
18317   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18318       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18319       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18320        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18321     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18322
18323     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18324     // left side invert the predicate to simplify logic below.
18325     SDValue Other;
18326     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18327       Other = RHS;
18328       CC = ISD::getSetCCInverse(CC, true);
18329     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18330       Other = LHS;
18331     }
18332
18333     if (Other.getNode() && Other->getNumOperands() == 2 &&
18334         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18335       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18336       SDValue CondRHS = Cond->getOperand(1);
18337
18338       // Look for a general sub with unsigned saturation first.
18339       // x >= y ? x-y : 0 --> subus x, y
18340       // x >  y ? x-y : 0 --> subus x, y
18341       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18342           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18343         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18344
18345       // If the RHS is a constant we have to reverse the const canonicalization.
18346       // x > C-1 ? x+-C : 0 --> subus x, C
18347       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18348           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18349         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18350         if (CondRHS.getConstantOperandVal(0) == -A-1)
18351           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18352                              DAG.getConstant(-A, VT));
18353       }
18354
18355       // Another special case: If C was a sign bit, the sub has been
18356       // canonicalized into a xor.
18357       // FIXME: Would it be better to use computeKnownBits to determine whether
18358       //        it's safe to decanonicalize the xor?
18359       // x s< 0 ? x^C : 0 --> subus x, C
18360       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18361           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18362           isSplatVector(OpRHS.getNode())) {
18363         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18364         if (A.isSignBit())
18365           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18366       }
18367     }
18368   }
18369
18370   // Try to match a min/max vector operation.
18371   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18372     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18373     unsigned Opc = ret.first;
18374     bool NeedSplit = ret.second;
18375
18376     if (Opc && NeedSplit) {
18377       unsigned NumElems = VT.getVectorNumElements();
18378       // Extract the LHS vectors
18379       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18380       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18381
18382       // Extract the RHS vectors
18383       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18384       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18385
18386       // Create min/max for each subvector
18387       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18388       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18389
18390       // Merge the result
18391       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18392     } else if (Opc)
18393       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18394   }
18395
18396   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18397   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18398       // Check if SETCC has already been promoted
18399       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18400       // Check that condition value type matches vselect operand type
18401       CondVT == VT) { 
18402
18403     assert(Cond.getValueType().isVector() &&
18404            "vector select expects a vector selector!");
18405
18406     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18407     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18408
18409     if (!TValIsAllOnes && !FValIsAllZeros) {
18410       // Try invert the condition if true value is not all 1s and false value
18411       // is not all 0s.
18412       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18413       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18414
18415       if (TValIsAllZeros || FValIsAllOnes) {
18416         SDValue CC = Cond.getOperand(2);
18417         ISD::CondCode NewCC =
18418           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18419                                Cond.getOperand(0).getValueType().isInteger());
18420         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18421         std::swap(LHS, RHS);
18422         TValIsAllOnes = FValIsAllOnes;
18423         FValIsAllZeros = TValIsAllZeros;
18424       }
18425     }
18426
18427     if (TValIsAllOnes || FValIsAllZeros) {
18428       SDValue Ret;
18429
18430       if (TValIsAllOnes && FValIsAllZeros)
18431         Ret = Cond;
18432       else if (TValIsAllOnes)
18433         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18434                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18435       else if (FValIsAllZeros)
18436         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18437                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18438
18439       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18440     }
18441   }
18442
18443   // Try to fold this VSELECT into a MOVSS/MOVSD
18444   if (N->getOpcode() == ISD::VSELECT &&
18445       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18446     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18447         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18448       bool CanFold = false;
18449       unsigned NumElems = Cond.getNumOperands();
18450       SDValue A = LHS;
18451       SDValue B = RHS;
18452       
18453       if (isZero(Cond.getOperand(0))) {
18454         CanFold = true;
18455
18456         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18457         // fold (vselect <0,-1> -> (movsd A, B)
18458         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18459           CanFold = isAllOnes(Cond.getOperand(i));
18460       } else if (isAllOnes(Cond.getOperand(0))) {
18461         CanFold = true;
18462         std::swap(A, B);
18463
18464         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18465         // fold (vselect <-1,0> -> (movsd B, A)
18466         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18467           CanFold = isZero(Cond.getOperand(i));
18468       }
18469
18470       if (CanFold) {
18471         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18472           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18473         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18474       }
18475
18476       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18477         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18478         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18479         //                             (v2i64 (bitcast B)))))
18480         //
18481         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18482         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18483         //                             (v2f64 (bitcast B)))))
18484         //
18485         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18486         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18487         //                             (v2i64 (bitcast A)))))
18488         //
18489         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18490         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18491         //                             (v2f64 (bitcast A)))))
18492
18493         CanFold = (isZero(Cond.getOperand(0)) &&
18494                    isZero(Cond.getOperand(1)) &&
18495                    isAllOnes(Cond.getOperand(2)) &&
18496                    isAllOnes(Cond.getOperand(3)));
18497
18498         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18499             isAllOnes(Cond.getOperand(1)) &&
18500             isZero(Cond.getOperand(2)) &&
18501             isZero(Cond.getOperand(3))) {
18502           CanFold = true;
18503           std::swap(LHS, RHS);
18504         }
18505
18506         if (CanFold) {
18507           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18508           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18509           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18510           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18511                                                 NewB, DAG);
18512           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18513         }
18514       }
18515     }
18516   }
18517
18518   // If we know that this node is legal then we know that it is going to be
18519   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18520   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18521   // to simplify previous instructions.
18522   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18523       !DCI.isBeforeLegalize() &&
18524       // We explicitly check against v8i16 and v16i16 because, although
18525       // they're marked as Custom, they might only be legal when Cond is a
18526       // build_vector of constants. This will be taken care in a later
18527       // condition.
18528       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18529        VT != MVT::v8i16)) {
18530     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18531
18532     // Don't optimize vector selects that map to mask-registers.
18533     if (BitWidth == 1)
18534       return SDValue();
18535
18536     // Check all uses of that condition operand to check whether it will be
18537     // consumed by non-BLEND instructions, which may depend on all bits are set
18538     // properly.
18539     for (SDNode::use_iterator I = Cond->use_begin(),
18540                               E = Cond->use_end(); I != E; ++I)
18541       if (I->getOpcode() != ISD::VSELECT)
18542         // TODO: Add other opcodes eventually lowered into BLEND.
18543         return SDValue();
18544
18545     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18546     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18547
18548     APInt KnownZero, KnownOne;
18549     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18550                                           DCI.isBeforeLegalizeOps());
18551     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18552         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18553       DCI.CommitTargetLoweringOpt(TLO);
18554   }
18555
18556   // We should generate an X86ISD::BLENDI from a vselect if its argument
18557   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18558   // constants. This specific pattern gets generated when we split a
18559   // selector for a 512 bit vector in a machine without AVX512 (but with
18560   // 256-bit vectors), during legalization:
18561   //
18562   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18563   //
18564   // Iff we find this pattern and the build_vectors are built from
18565   // constants, we translate the vselect into a shuffle_vector that we
18566   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18567   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18568     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18569     if (Shuffle.getNode())
18570       return Shuffle;
18571   }
18572
18573   return SDValue();
18574 }
18575
18576 // Check whether a boolean test is testing a boolean value generated by
18577 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18578 // code.
18579 //
18580 // Simplify the following patterns:
18581 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18582 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18583 // to (Op EFLAGS Cond)
18584 //
18585 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18586 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18587 // to (Op EFLAGS !Cond)
18588 //
18589 // where Op could be BRCOND or CMOV.
18590 //
18591 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18592   // Quit if not CMP and SUB with its value result used.
18593   if (Cmp.getOpcode() != X86ISD::CMP &&
18594       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18595       return SDValue();
18596
18597   // Quit if not used as a boolean value.
18598   if (CC != X86::COND_E && CC != X86::COND_NE)
18599     return SDValue();
18600
18601   // Check CMP operands. One of them should be 0 or 1 and the other should be
18602   // an SetCC or extended from it.
18603   SDValue Op1 = Cmp.getOperand(0);
18604   SDValue Op2 = Cmp.getOperand(1);
18605
18606   SDValue SetCC;
18607   const ConstantSDNode* C = nullptr;
18608   bool needOppositeCond = (CC == X86::COND_E);
18609   bool checkAgainstTrue = false; // Is it a comparison against 1?
18610
18611   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18612     SetCC = Op2;
18613   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18614     SetCC = Op1;
18615   else // Quit if all operands are not constants.
18616     return SDValue();
18617
18618   if (C->getZExtValue() == 1) {
18619     needOppositeCond = !needOppositeCond;
18620     checkAgainstTrue = true;
18621   } else if (C->getZExtValue() != 0)
18622     // Quit if the constant is neither 0 or 1.
18623     return SDValue();
18624
18625   bool truncatedToBoolWithAnd = false;
18626   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18627   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18628          SetCC.getOpcode() == ISD::TRUNCATE ||
18629          SetCC.getOpcode() == ISD::AND) {
18630     if (SetCC.getOpcode() == ISD::AND) {
18631       int OpIdx = -1;
18632       ConstantSDNode *CS;
18633       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18634           CS->getZExtValue() == 1)
18635         OpIdx = 1;
18636       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18637           CS->getZExtValue() == 1)
18638         OpIdx = 0;
18639       if (OpIdx == -1)
18640         break;
18641       SetCC = SetCC.getOperand(OpIdx);
18642       truncatedToBoolWithAnd = true;
18643     } else
18644       SetCC = SetCC.getOperand(0);
18645   }
18646
18647   switch (SetCC.getOpcode()) {
18648   case X86ISD::SETCC_CARRY:
18649     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18650     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18651     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18652     // truncated to i1 using 'and'.
18653     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18654       break;
18655     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18656            "Invalid use of SETCC_CARRY!");
18657     // FALL THROUGH
18658   case X86ISD::SETCC:
18659     // Set the condition code or opposite one if necessary.
18660     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18661     if (needOppositeCond)
18662       CC = X86::GetOppositeBranchCondition(CC);
18663     return SetCC.getOperand(1);
18664   case X86ISD::CMOV: {
18665     // Check whether false/true value has canonical one, i.e. 0 or 1.
18666     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18667     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18668     // Quit if true value is not a constant.
18669     if (!TVal)
18670       return SDValue();
18671     // Quit if false value is not a constant.
18672     if (!FVal) {
18673       SDValue Op = SetCC.getOperand(0);
18674       // Skip 'zext' or 'trunc' node.
18675       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18676           Op.getOpcode() == ISD::TRUNCATE)
18677         Op = Op.getOperand(0);
18678       // A special case for rdrand/rdseed, where 0 is set if false cond is
18679       // found.
18680       if ((Op.getOpcode() != X86ISD::RDRAND &&
18681            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18682         return SDValue();
18683     }
18684     // Quit if false value is not the constant 0 or 1.
18685     bool FValIsFalse = true;
18686     if (FVal && FVal->getZExtValue() != 0) {
18687       if (FVal->getZExtValue() != 1)
18688         return SDValue();
18689       // If FVal is 1, opposite cond is needed.
18690       needOppositeCond = !needOppositeCond;
18691       FValIsFalse = false;
18692     }
18693     // Quit if TVal is not the constant opposite of FVal.
18694     if (FValIsFalse && TVal->getZExtValue() != 1)
18695       return SDValue();
18696     if (!FValIsFalse && TVal->getZExtValue() != 0)
18697       return SDValue();
18698     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18699     if (needOppositeCond)
18700       CC = X86::GetOppositeBranchCondition(CC);
18701     return SetCC.getOperand(3);
18702   }
18703   }
18704
18705   return SDValue();
18706 }
18707
18708 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18709 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18710                                   TargetLowering::DAGCombinerInfo &DCI,
18711                                   const X86Subtarget *Subtarget) {
18712   SDLoc DL(N);
18713
18714   // If the flag operand isn't dead, don't touch this CMOV.
18715   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18716     return SDValue();
18717
18718   SDValue FalseOp = N->getOperand(0);
18719   SDValue TrueOp = N->getOperand(1);
18720   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18721   SDValue Cond = N->getOperand(3);
18722
18723   if (CC == X86::COND_E || CC == X86::COND_NE) {
18724     switch (Cond.getOpcode()) {
18725     default: break;
18726     case X86ISD::BSR:
18727     case X86ISD::BSF:
18728       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18729       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18730         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18731     }
18732   }
18733
18734   SDValue Flags;
18735
18736   Flags = checkBoolTestSetCCCombine(Cond, CC);
18737   if (Flags.getNode() &&
18738       // Extra check as FCMOV only supports a subset of X86 cond.
18739       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18740     SDValue Ops[] = { FalseOp, TrueOp,
18741                       DAG.getConstant(CC, MVT::i8), Flags };
18742     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18743   }
18744
18745   // If this is a select between two integer constants, try to do some
18746   // optimizations.  Note that the operands are ordered the opposite of SELECT
18747   // operands.
18748   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18749     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18750       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18751       // larger than FalseC (the false value).
18752       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18753         CC = X86::GetOppositeBranchCondition(CC);
18754         std::swap(TrueC, FalseC);
18755         std::swap(TrueOp, FalseOp);
18756       }
18757
18758       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18759       // This is efficient for any integer data type (including i8/i16) and
18760       // shift amount.
18761       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18762         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18763                            DAG.getConstant(CC, MVT::i8), Cond);
18764
18765         // Zero extend the condition if needed.
18766         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18767
18768         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18769         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18770                            DAG.getConstant(ShAmt, MVT::i8));
18771         if (N->getNumValues() == 2)  // Dead flag value?
18772           return DCI.CombineTo(N, Cond, SDValue());
18773         return Cond;
18774       }
18775
18776       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18777       // for any integer data type, including i8/i16.
18778       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18779         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18780                            DAG.getConstant(CC, MVT::i8), Cond);
18781
18782         // Zero extend the condition if needed.
18783         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18784                            FalseC->getValueType(0), Cond);
18785         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18786                            SDValue(FalseC, 0));
18787
18788         if (N->getNumValues() == 2)  // Dead flag value?
18789           return DCI.CombineTo(N, Cond, SDValue());
18790         return Cond;
18791       }
18792
18793       // Optimize cases that will turn into an LEA instruction.  This requires
18794       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18795       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18796         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18797         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18798
18799         bool isFastMultiplier = false;
18800         if (Diff < 10) {
18801           switch ((unsigned char)Diff) {
18802           default: break;
18803           case 1:  // result = add base, cond
18804           case 2:  // result = lea base(    , cond*2)
18805           case 3:  // result = lea base(cond, cond*2)
18806           case 4:  // result = lea base(    , cond*4)
18807           case 5:  // result = lea base(cond, cond*4)
18808           case 8:  // result = lea base(    , cond*8)
18809           case 9:  // result = lea base(cond, cond*8)
18810             isFastMultiplier = true;
18811             break;
18812           }
18813         }
18814
18815         if (isFastMultiplier) {
18816           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18817           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18818                              DAG.getConstant(CC, MVT::i8), Cond);
18819           // Zero extend the condition if needed.
18820           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18821                              Cond);
18822           // Scale the condition by the difference.
18823           if (Diff != 1)
18824             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18825                                DAG.getConstant(Diff, Cond.getValueType()));
18826
18827           // Add the base if non-zero.
18828           if (FalseC->getAPIntValue() != 0)
18829             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18830                                SDValue(FalseC, 0));
18831           if (N->getNumValues() == 2)  // Dead flag value?
18832             return DCI.CombineTo(N, Cond, SDValue());
18833           return Cond;
18834         }
18835       }
18836     }
18837   }
18838
18839   // Handle these cases:
18840   //   (select (x != c), e, c) -> select (x != c), e, x),
18841   //   (select (x == c), c, e) -> select (x == c), x, e)
18842   // where the c is an integer constant, and the "select" is the combination
18843   // of CMOV and CMP.
18844   //
18845   // The rationale for this change is that the conditional-move from a constant
18846   // needs two instructions, however, conditional-move from a register needs
18847   // only one instruction.
18848   //
18849   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18850   //  some instruction-combining opportunities. This opt needs to be
18851   //  postponed as late as possible.
18852   //
18853   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18854     // the DCI.xxxx conditions are provided to postpone the optimization as
18855     // late as possible.
18856
18857     ConstantSDNode *CmpAgainst = nullptr;
18858     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18859         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18860         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18861
18862       if (CC == X86::COND_NE &&
18863           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18864         CC = X86::GetOppositeBranchCondition(CC);
18865         std::swap(TrueOp, FalseOp);
18866       }
18867
18868       if (CC == X86::COND_E &&
18869           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18870         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18871                           DAG.getConstant(CC, MVT::i8), Cond };
18872         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18873       }
18874     }
18875   }
18876
18877   return SDValue();
18878 }
18879
18880 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18881                                                 const X86Subtarget *Subtarget) {
18882   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18883   switch (IntNo) {
18884   default: return SDValue();
18885   // SSE/AVX/AVX2 blend intrinsics.
18886   case Intrinsic::x86_avx2_pblendvb:
18887   case Intrinsic::x86_avx2_pblendw:
18888   case Intrinsic::x86_avx2_pblendd_128:
18889   case Intrinsic::x86_avx2_pblendd_256:
18890     // Don't try to simplify this intrinsic if we don't have AVX2.
18891     if (!Subtarget->hasAVX2())
18892       return SDValue();
18893     // FALL-THROUGH
18894   case Intrinsic::x86_avx_blend_pd_256:
18895   case Intrinsic::x86_avx_blend_ps_256:
18896   case Intrinsic::x86_avx_blendv_pd_256:
18897   case Intrinsic::x86_avx_blendv_ps_256:
18898     // Don't try to simplify this intrinsic if we don't have AVX.
18899     if (!Subtarget->hasAVX())
18900       return SDValue();
18901     // FALL-THROUGH
18902   case Intrinsic::x86_sse41_pblendw:
18903   case Intrinsic::x86_sse41_blendpd:
18904   case Intrinsic::x86_sse41_blendps:
18905   case Intrinsic::x86_sse41_blendvps:
18906   case Intrinsic::x86_sse41_blendvpd:
18907   case Intrinsic::x86_sse41_pblendvb: {
18908     SDValue Op0 = N->getOperand(1);
18909     SDValue Op1 = N->getOperand(2);
18910     SDValue Mask = N->getOperand(3);
18911
18912     // Don't try to simplify this intrinsic if we don't have SSE4.1.
18913     if (!Subtarget->hasSSE41())
18914       return SDValue();
18915
18916     // fold (blend A, A, Mask) -> A
18917     if (Op0 == Op1)
18918       return Op0;
18919     // fold (blend A, B, allZeros) -> A
18920     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18921       return Op0;
18922     // fold (blend A, B, allOnes) -> B
18923     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18924       return Op1;
18925     
18926     // Simplify the case where the mask is a constant i32 value.
18927     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18928       if (C->isNullValue())
18929         return Op0;
18930       if (C->isAllOnesValue())
18931         return Op1;
18932     }
18933   }
18934
18935   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18936   case Intrinsic::x86_sse2_psrai_w:
18937   case Intrinsic::x86_sse2_psrai_d:
18938   case Intrinsic::x86_avx2_psrai_w:
18939   case Intrinsic::x86_avx2_psrai_d:
18940   case Intrinsic::x86_sse2_psra_w:
18941   case Intrinsic::x86_sse2_psra_d:
18942   case Intrinsic::x86_avx2_psra_w:
18943   case Intrinsic::x86_avx2_psra_d: {
18944     SDValue Op0 = N->getOperand(1);
18945     SDValue Op1 = N->getOperand(2);
18946     EVT VT = Op0.getValueType();
18947     assert(VT.isVector() && "Expected a vector type!");
18948
18949     if (isa<BuildVectorSDNode>(Op1))
18950       Op1 = Op1.getOperand(0);
18951
18952     if (!isa<ConstantSDNode>(Op1))
18953       return SDValue();
18954
18955     EVT SVT = VT.getVectorElementType();
18956     unsigned SVTBits = SVT.getSizeInBits();
18957
18958     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18959     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18960     uint64_t ShAmt = C.getZExtValue();
18961
18962     // Don't try to convert this shift into a ISD::SRA if the shift
18963     // count is bigger than or equal to the element size.
18964     if (ShAmt >= SVTBits)
18965       return SDValue();
18966
18967     // Trivial case: if the shift count is zero, then fold this
18968     // into the first operand.
18969     if (ShAmt == 0)
18970       return Op0;
18971
18972     // Replace this packed shift intrinsic with a target independent
18973     // shift dag node.
18974     SDValue Splat = DAG.getConstant(C, VT);
18975     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18976   }
18977   }
18978 }
18979
18980 /// PerformMulCombine - Optimize a single multiply with constant into two
18981 /// in order to implement it with two cheaper instructions, e.g.
18982 /// LEA + SHL, LEA + LEA.
18983 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18984                                  TargetLowering::DAGCombinerInfo &DCI) {
18985   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18986     return SDValue();
18987
18988   EVT VT = N->getValueType(0);
18989   if (VT != MVT::i64)
18990     return SDValue();
18991
18992   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18993   if (!C)
18994     return SDValue();
18995   uint64_t MulAmt = C->getZExtValue();
18996   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18997     return SDValue();
18998
18999   uint64_t MulAmt1 = 0;
19000   uint64_t MulAmt2 = 0;
19001   if ((MulAmt % 9) == 0) {
19002     MulAmt1 = 9;
19003     MulAmt2 = MulAmt / 9;
19004   } else if ((MulAmt % 5) == 0) {
19005     MulAmt1 = 5;
19006     MulAmt2 = MulAmt / 5;
19007   } else if ((MulAmt % 3) == 0) {
19008     MulAmt1 = 3;
19009     MulAmt2 = MulAmt / 3;
19010   }
19011   if (MulAmt2 &&
19012       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19013     SDLoc DL(N);
19014
19015     if (isPowerOf2_64(MulAmt2) &&
19016         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19017       // If second multiplifer is pow2, issue it first. We want the multiply by
19018       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19019       // is an add.
19020       std::swap(MulAmt1, MulAmt2);
19021
19022     SDValue NewMul;
19023     if (isPowerOf2_64(MulAmt1))
19024       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19025                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19026     else
19027       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19028                            DAG.getConstant(MulAmt1, VT));
19029
19030     if (isPowerOf2_64(MulAmt2))
19031       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19032                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19033     else
19034       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19035                            DAG.getConstant(MulAmt2, VT));
19036
19037     // Do not add new nodes to DAG combiner worklist.
19038     DCI.CombineTo(N, NewMul, false);
19039   }
19040   return SDValue();
19041 }
19042
19043 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19044   SDValue N0 = N->getOperand(0);
19045   SDValue N1 = N->getOperand(1);
19046   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19047   EVT VT = N0.getValueType();
19048
19049   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19050   // since the result of setcc_c is all zero's or all ones.
19051   if (VT.isInteger() && !VT.isVector() &&
19052       N1C && N0.getOpcode() == ISD::AND &&
19053       N0.getOperand(1).getOpcode() == ISD::Constant) {
19054     SDValue N00 = N0.getOperand(0);
19055     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19056         ((N00.getOpcode() == ISD::ANY_EXTEND ||
19057           N00.getOpcode() == ISD::ZERO_EXTEND) &&
19058          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19059       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19060       APInt ShAmt = N1C->getAPIntValue();
19061       Mask = Mask.shl(ShAmt);
19062       if (Mask != 0)
19063         return DAG.getNode(ISD::AND, SDLoc(N), VT,
19064                            N00, DAG.getConstant(Mask, VT));
19065     }
19066   }
19067
19068   // Hardware support for vector shifts is sparse which makes us scalarize the
19069   // vector operations in many cases. Also, on sandybridge ADD is faster than
19070   // shl.
19071   // (shl V, 1) -> add V,V
19072   if (isSplatVector(N1.getNode())) {
19073     assert(N0.getValueType().isVector() && "Invalid vector shift type");
19074     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19075     // We shift all of the values by one. In many cases we do not have
19076     // hardware support for this operation. This is better expressed as an ADD
19077     // of two values.
19078     if (N1C && (1 == N1C->getZExtValue())) {
19079       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19080     }
19081   }
19082
19083   return SDValue();
19084 }
19085
19086 /// \brief Returns a vector of 0s if the node in input is a vector logical
19087 /// shift by a constant amount which is known to be bigger than or equal
19088 /// to the vector element size in bits.
19089 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19090                                       const X86Subtarget *Subtarget) {
19091   EVT VT = N->getValueType(0);
19092
19093   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19094       (!Subtarget->hasInt256() ||
19095        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19096     return SDValue();
19097
19098   SDValue Amt = N->getOperand(1);
19099   SDLoc DL(N);
19100   if (isSplatVector(Amt.getNode())) {
19101     SDValue SclrAmt = Amt->getOperand(0);
19102     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19103       APInt ShiftAmt = C->getAPIntValue();
19104       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19105
19106       // SSE2/AVX2 logical shifts always return a vector of 0s
19107       // if the shift amount is bigger than or equal to
19108       // the element size. The constant shift amount will be
19109       // encoded as a 8-bit immediate.
19110       if (ShiftAmt.trunc(8).uge(MaxAmount))
19111         return getZeroVector(VT, Subtarget, DAG, DL);
19112     }
19113   }
19114
19115   return SDValue();
19116 }
19117
19118 /// PerformShiftCombine - Combine shifts.
19119 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19120                                    TargetLowering::DAGCombinerInfo &DCI,
19121                                    const X86Subtarget *Subtarget) {
19122   if (N->getOpcode() == ISD::SHL) {
19123     SDValue V = PerformSHLCombine(N, DAG);
19124     if (V.getNode()) return V;
19125   }
19126
19127   if (N->getOpcode() != ISD::SRA) {
19128     // Try to fold this logical shift into a zero vector.
19129     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19130     if (V.getNode()) return V;
19131   }
19132
19133   return SDValue();
19134 }
19135
19136 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
19137 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19138 // and friends.  Likewise for OR -> CMPNEQSS.
19139 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19140                             TargetLowering::DAGCombinerInfo &DCI,
19141                             const X86Subtarget *Subtarget) {
19142   unsigned opcode;
19143
19144   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19145   // we're requiring SSE2 for both.
19146   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19147     SDValue N0 = N->getOperand(0);
19148     SDValue N1 = N->getOperand(1);
19149     SDValue CMP0 = N0->getOperand(1);
19150     SDValue CMP1 = N1->getOperand(1);
19151     SDLoc DL(N);
19152
19153     // The SETCCs should both refer to the same CMP.
19154     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19155       return SDValue();
19156
19157     SDValue CMP00 = CMP0->getOperand(0);
19158     SDValue CMP01 = CMP0->getOperand(1);
19159     EVT     VT    = CMP00.getValueType();
19160
19161     if (VT == MVT::f32 || VT == MVT::f64) {
19162       bool ExpectingFlags = false;
19163       // Check for any users that want flags:
19164       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19165            !ExpectingFlags && UI != UE; ++UI)
19166         switch (UI->getOpcode()) {
19167         default:
19168         case ISD::BR_CC:
19169         case ISD::BRCOND:
19170         case ISD::SELECT:
19171           ExpectingFlags = true;
19172           break;
19173         case ISD::CopyToReg:
19174         case ISD::SIGN_EXTEND:
19175         case ISD::ZERO_EXTEND:
19176         case ISD::ANY_EXTEND:
19177           break;
19178         }
19179
19180       if (!ExpectingFlags) {
19181         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19182         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19183
19184         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19185           X86::CondCode tmp = cc0;
19186           cc0 = cc1;
19187           cc1 = tmp;
19188         }
19189
19190         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
19191             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19192           // FIXME: need symbolic constants for these magic numbers.
19193           // See X86ATTInstPrinter.cpp:printSSECC().
19194           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19195           if (Subtarget->hasAVX512()) {
19196             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19197                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
19198             if (N->getValueType(0) != MVT::i1)
19199               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19200                                  FSetCC);
19201             return FSetCC;
19202           }
19203           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19204                                               CMP00.getValueType(), CMP00, CMP01,
19205                                               DAG.getConstant(x86cc, MVT::i8));
19206
19207           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19208           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19209
19210           if (is64BitFP && !Subtarget->is64Bit()) {
19211             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19212             // 64-bit integer, since that's not a legal type. Since
19213             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19214             // bits, but can do this little dance to extract the lowest 32 bits
19215             // and work with those going forward.
19216             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19217                                            OnesOrZeroesF);
19218             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19219                                            Vector64);
19220             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19221                                         Vector32, DAG.getIntPtrConstant(0));
19222             IntVT = MVT::i32;
19223           }
19224
19225           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19226           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19227                                       DAG.getConstant(1, IntVT));
19228           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19229           return OneBitOfTruth;
19230         }
19231       }
19232     }
19233   }
19234   return SDValue();
19235 }
19236
19237 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19238 /// so it can be folded inside ANDNP.
19239 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19240   EVT VT = N->getValueType(0);
19241
19242   // Match direct AllOnes for 128 and 256-bit vectors
19243   if (ISD::isBuildVectorAllOnes(N))
19244     return true;
19245
19246   // Look through a bit convert.
19247   if (N->getOpcode() == ISD::BITCAST)
19248     N = N->getOperand(0).getNode();
19249
19250   // Sometimes the operand may come from a insert_subvector building a 256-bit
19251   // allones vector
19252   if (VT.is256BitVector() &&
19253       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19254     SDValue V1 = N->getOperand(0);
19255     SDValue V2 = N->getOperand(1);
19256
19257     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19258         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19259         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19260         ISD::isBuildVectorAllOnes(V2.getNode()))
19261       return true;
19262   }
19263
19264   return false;
19265 }
19266
19267 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19268 // register. In most cases we actually compare or select YMM-sized registers
19269 // and mixing the two types creates horrible code. This method optimizes
19270 // some of the transition sequences.
19271 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19272                                  TargetLowering::DAGCombinerInfo &DCI,
19273                                  const X86Subtarget *Subtarget) {
19274   EVT VT = N->getValueType(0);
19275   if (!VT.is256BitVector())
19276     return SDValue();
19277
19278   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19279           N->getOpcode() == ISD::ZERO_EXTEND ||
19280           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19281
19282   SDValue Narrow = N->getOperand(0);
19283   EVT NarrowVT = Narrow->getValueType(0);
19284   if (!NarrowVT.is128BitVector())
19285     return SDValue();
19286
19287   if (Narrow->getOpcode() != ISD::XOR &&
19288       Narrow->getOpcode() != ISD::AND &&
19289       Narrow->getOpcode() != ISD::OR)
19290     return SDValue();
19291
19292   SDValue N0  = Narrow->getOperand(0);
19293   SDValue N1  = Narrow->getOperand(1);
19294   SDLoc DL(Narrow);
19295
19296   // The Left side has to be a trunc.
19297   if (N0.getOpcode() != ISD::TRUNCATE)
19298     return SDValue();
19299
19300   // The type of the truncated inputs.
19301   EVT WideVT = N0->getOperand(0)->getValueType(0);
19302   if (WideVT != VT)
19303     return SDValue();
19304
19305   // The right side has to be a 'trunc' or a constant vector.
19306   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19307   bool RHSConst = (isSplatVector(N1.getNode()) &&
19308                    isa<ConstantSDNode>(N1->getOperand(0)));
19309   if (!RHSTrunc && !RHSConst)
19310     return SDValue();
19311
19312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19313
19314   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19315     return SDValue();
19316
19317   // Set N0 and N1 to hold the inputs to the new wide operation.
19318   N0 = N0->getOperand(0);
19319   if (RHSConst) {
19320     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19321                      N1->getOperand(0));
19322     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19323     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19324   } else if (RHSTrunc) {
19325     N1 = N1->getOperand(0);
19326   }
19327
19328   // Generate the wide operation.
19329   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19330   unsigned Opcode = N->getOpcode();
19331   switch (Opcode) {
19332   case ISD::ANY_EXTEND:
19333     return Op;
19334   case ISD::ZERO_EXTEND: {
19335     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19336     APInt Mask = APInt::getAllOnesValue(InBits);
19337     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19338     return DAG.getNode(ISD::AND, DL, VT,
19339                        Op, DAG.getConstant(Mask, VT));
19340   }
19341   case ISD::SIGN_EXTEND:
19342     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19343                        Op, DAG.getValueType(NarrowVT));
19344   default:
19345     llvm_unreachable("Unexpected opcode");
19346   }
19347 }
19348
19349 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19350                                  TargetLowering::DAGCombinerInfo &DCI,
19351                                  const X86Subtarget *Subtarget) {
19352   EVT VT = N->getValueType(0);
19353   if (DCI.isBeforeLegalizeOps())
19354     return SDValue();
19355
19356   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19357   if (R.getNode())
19358     return R;
19359
19360   // Create BEXTR instructions
19361   // BEXTR is ((X >> imm) & (2**size-1))
19362   if (VT == MVT::i32 || VT == MVT::i64) {
19363     SDValue N0 = N->getOperand(0);
19364     SDValue N1 = N->getOperand(1);
19365     SDLoc DL(N);
19366
19367     // Check for BEXTR.
19368     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19369         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19370       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19371       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19372       if (MaskNode && ShiftNode) {
19373         uint64_t Mask = MaskNode->getZExtValue();
19374         uint64_t Shift = ShiftNode->getZExtValue();
19375         if (isMask_64(Mask)) {
19376           uint64_t MaskSize = CountPopulation_64(Mask);
19377           if (Shift + MaskSize <= VT.getSizeInBits())
19378             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19379                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19380         }
19381       }
19382     } // BEXTR
19383
19384     return SDValue();
19385   }
19386
19387   // Want to form ANDNP nodes:
19388   // 1) In the hopes of then easily combining them with OR and AND nodes
19389   //    to form PBLEND/PSIGN.
19390   // 2) To match ANDN packed intrinsics
19391   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19392     return SDValue();
19393
19394   SDValue N0 = N->getOperand(0);
19395   SDValue N1 = N->getOperand(1);
19396   SDLoc DL(N);
19397
19398   // Check LHS for vnot
19399   if (N0.getOpcode() == ISD::XOR &&
19400       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19401       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19402     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19403
19404   // Check RHS for vnot
19405   if (N1.getOpcode() == ISD::XOR &&
19406       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19407       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19408     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19409
19410   return SDValue();
19411 }
19412
19413 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19414                                 TargetLowering::DAGCombinerInfo &DCI,
19415                                 const X86Subtarget *Subtarget) {
19416   if (DCI.isBeforeLegalizeOps())
19417     return SDValue();
19418
19419   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19420   if (R.getNode())
19421     return R;
19422
19423   SDValue N0 = N->getOperand(0);
19424   SDValue N1 = N->getOperand(1);
19425   EVT VT = N->getValueType(0);
19426
19427   // look for psign/blend
19428   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19429     if (!Subtarget->hasSSSE3() ||
19430         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19431       return SDValue();
19432
19433     // Canonicalize pandn to RHS
19434     if (N0.getOpcode() == X86ISD::ANDNP)
19435       std::swap(N0, N1);
19436     // or (and (m, y), (pandn m, x))
19437     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19438       SDValue Mask = N1.getOperand(0);
19439       SDValue X    = N1.getOperand(1);
19440       SDValue Y;
19441       if (N0.getOperand(0) == Mask)
19442         Y = N0.getOperand(1);
19443       if (N0.getOperand(1) == Mask)
19444         Y = N0.getOperand(0);
19445
19446       // Check to see if the mask appeared in both the AND and ANDNP and
19447       if (!Y.getNode())
19448         return SDValue();
19449
19450       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19451       // Look through mask bitcast.
19452       if (Mask.getOpcode() == ISD::BITCAST)
19453         Mask = Mask.getOperand(0);
19454       if (X.getOpcode() == ISD::BITCAST)
19455         X = X.getOperand(0);
19456       if (Y.getOpcode() == ISD::BITCAST)
19457         Y = Y.getOperand(0);
19458
19459       EVT MaskVT = Mask.getValueType();
19460
19461       // Validate that the Mask operand is a vector sra node.
19462       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19463       // there is no psrai.b
19464       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19465       unsigned SraAmt = ~0;
19466       if (Mask.getOpcode() == ISD::SRA) {
19467         SDValue Amt = Mask.getOperand(1);
19468         if (isSplatVector(Amt.getNode())) {
19469           SDValue SclrAmt = Amt->getOperand(0);
19470           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19471             SraAmt = C->getZExtValue();
19472         }
19473       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19474         SDValue SraC = Mask.getOperand(1);
19475         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19476       }
19477       if ((SraAmt + 1) != EltBits)
19478         return SDValue();
19479
19480       SDLoc DL(N);
19481
19482       // Now we know we at least have a plendvb with the mask val.  See if
19483       // we can form a psignb/w/d.
19484       // psign = x.type == y.type == mask.type && y = sub(0, x);
19485       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19486           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19487           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19488         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19489                "Unsupported VT for PSIGN");
19490         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19491         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19492       }
19493       // PBLENDVB only available on SSE 4.1
19494       if (!Subtarget->hasSSE41())
19495         return SDValue();
19496
19497       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19498
19499       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19500       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19501       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19502       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19503       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19504     }
19505   }
19506
19507   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19508     return SDValue();
19509
19510   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19511   MachineFunction &MF = DAG.getMachineFunction();
19512   bool OptForSize = MF.getFunction()->getAttributes().
19513     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19514
19515   // SHLD/SHRD instructions have lower register pressure, but on some
19516   // platforms they have higher latency than the equivalent
19517   // series of shifts/or that would otherwise be generated.
19518   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19519   // have higher latencies and we are not optimizing for size.
19520   if (!OptForSize && Subtarget->isSHLDSlow())
19521     return SDValue();
19522
19523   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19524     std::swap(N0, N1);
19525   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19526     return SDValue();
19527   if (!N0.hasOneUse() || !N1.hasOneUse())
19528     return SDValue();
19529
19530   SDValue ShAmt0 = N0.getOperand(1);
19531   if (ShAmt0.getValueType() != MVT::i8)
19532     return SDValue();
19533   SDValue ShAmt1 = N1.getOperand(1);
19534   if (ShAmt1.getValueType() != MVT::i8)
19535     return SDValue();
19536   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19537     ShAmt0 = ShAmt0.getOperand(0);
19538   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19539     ShAmt1 = ShAmt1.getOperand(0);
19540
19541   SDLoc DL(N);
19542   unsigned Opc = X86ISD::SHLD;
19543   SDValue Op0 = N0.getOperand(0);
19544   SDValue Op1 = N1.getOperand(0);
19545   if (ShAmt0.getOpcode() == ISD::SUB) {
19546     Opc = X86ISD::SHRD;
19547     std::swap(Op0, Op1);
19548     std::swap(ShAmt0, ShAmt1);
19549   }
19550
19551   unsigned Bits = VT.getSizeInBits();
19552   if (ShAmt1.getOpcode() == ISD::SUB) {
19553     SDValue Sum = ShAmt1.getOperand(0);
19554     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19555       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19556       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19557         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19558       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19559         return DAG.getNode(Opc, DL, VT,
19560                            Op0, Op1,
19561                            DAG.getNode(ISD::TRUNCATE, DL,
19562                                        MVT::i8, ShAmt0));
19563     }
19564   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19565     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19566     if (ShAmt0C &&
19567         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19568       return DAG.getNode(Opc, DL, VT,
19569                          N0.getOperand(0), N1.getOperand(0),
19570                          DAG.getNode(ISD::TRUNCATE, DL,
19571                                        MVT::i8, ShAmt0));
19572   }
19573
19574   return SDValue();
19575 }
19576
19577 // Generate NEG and CMOV for integer abs.
19578 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19579   EVT VT = N->getValueType(0);
19580
19581   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19582   // 8-bit integer abs to NEG and CMOV.
19583   if (VT.isInteger() && VT.getSizeInBits() == 8)
19584     return SDValue();
19585
19586   SDValue N0 = N->getOperand(0);
19587   SDValue N1 = N->getOperand(1);
19588   SDLoc DL(N);
19589
19590   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19591   // and change it to SUB and CMOV.
19592   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19593       N0.getOpcode() == ISD::ADD &&
19594       N0.getOperand(1) == N1 &&
19595       N1.getOpcode() == ISD::SRA &&
19596       N1.getOperand(0) == N0.getOperand(0))
19597     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19598       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19599         // Generate SUB & CMOV.
19600         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19601                                   DAG.getConstant(0, VT), N0.getOperand(0));
19602
19603         SDValue Ops[] = { N0.getOperand(0), Neg,
19604                           DAG.getConstant(X86::COND_GE, MVT::i8),
19605                           SDValue(Neg.getNode(), 1) };
19606         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19607       }
19608   return SDValue();
19609 }
19610
19611 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19612 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19613                                  TargetLowering::DAGCombinerInfo &DCI,
19614                                  const X86Subtarget *Subtarget) {
19615   if (DCI.isBeforeLegalizeOps())
19616     return SDValue();
19617
19618   if (Subtarget->hasCMov()) {
19619     SDValue RV = performIntegerAbsCombine(N, DAG);
19620     if (RV.getNode())
19621       return RV;
19622   }
19623
19624   return SDValue();
19625 }
19626
19627 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19628 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19629                                   TargetLowering::DAGCombinerInfo &DCI,
19630                                   const X86Subtarget *Subtarget) {
19631   LoadSDNode *Ld = cast<LoadSDNode>(N);
19632   EVT RegVT = Ld->getValueType(0);
19633   EVT MemVT = Ld->getMemoryVT();
19634   SDLoc dl(Ld);
19635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19636   unsigned RegSz = RegVT.getSizeInBits();
19637
19638   // On Sandybridge unaligned 256bit loads are inefficient.
19639   ISD::LoadExtType Ext = Ld->getExtensionType();
19640   unsigned Alignment = Ld->getAlignment();
19641   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19642   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19643       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19644     unsigned NumElems = RegVT.getVectorNumElements();
19645     if (NumElems < 2)
19646       return SDValue();
19647
19648     SDValue Ptr = Ld->getBasePtr();
19649     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19650
19651     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19652                                   NumElems/2);
19653     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19654                                 Ld->getPointerInfo(), Ld->isVolatile(),
19655                                 Ld->isNonTemporal(), Ld->isInvariant(),
19656                                 Alignment);
19657     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19658     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19659                                 Ld->getPointerInfo(), Ld->isVolatile(),
19660                                 Ld->isNonTemporal(), Ld->isInvariant(),
19661                                 std::min(16U, Alignment));
19662     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19663                              Load1.getValue(1),
19664                              Load2.getValue(1));
19665
19666     SDValue NewVec = DAG.getUNDEF(RegVT);
19667     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19668     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19669     return DCI.CombineTo(N, NewVec, TF, true);
19670   }
19671
19672   // If this is a vector EXT Load then attempt to optimize it using a
19673   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19674   // expansion is still better than scalar code.
19675   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19676   // emit a shuffle and a arithmetic shift.
19677   // TODO: It is possible to support ZExt by zeroing the undef values
19678   // during the shuffle phase or after the shuffle.
19679   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19680       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19681     assert(MemVT != RegVT && "Cannot extend to the same type");
19682     assert(MemVT.isVector() && "Must load a vector from memory");
19683
19684     unsigned NumElems = RegVT.getVectorNumElements();
19685     unsigned MemSz = MemVT.getSizeInBits();
19686     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19687
19688     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19689       return SDValue();
19690
19691     // All sizes must be a power of two.
19692     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19693       return SDValue();
19694
19695     // Attempt to load the original value using scalar loads.
19696     // Find the largest scalar type that divides the total loaded size.
19697     MVT SclrLoadTy = MVT::i8;
19698     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19699          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19700       MVT Tp = (MVT::SimpleValueType)tp;
19701       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19702         SclrLoadTy = Tp;
19703       }
19704     }
19705
19706     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19707     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19708         (64 <= MemSz))
19709       SclrLoadTy = MVT::f64;
19710
19711     // Calculate the number of scalar loads that we need to perform
19712     // in order to load our vector from memory.
19713     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19714     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19715       return SDValue();
19716
19717     unsigned loadRegZize = RegSz;
19718     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19719       loadRegZize /= 2;
19720
19721     // Represent our vector as a sequence of elements which are the
19722     // largest scalar that we can load.
19723     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19724       loadRegZize/SclrLoadTy.getSizeInBits());
19725
19726     // Represent the data using the same element type that is stored in
19727     // memory. In practice, we ''widen'' MemVT.
19728     EVT WideVecVT =
19729           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19730                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19731
19732     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19733       "Invalid vector type");
19734
19735     // We can't shuffle using an illegal type.
19736     if (!TLI.isTypeLegal(WideVecVT))
19737       return SDValue();
19738
19739     SmallVector<SDValue, 8> Chains;
19740     SDValue Ptr = Ld->getBasePtr();
19741     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19742                                         TLI.getPointerTy());
19743     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19744
19745     for (unsigned i = 0; i < NumLoads; ++i) {
19746       // Perform a single load.
19747       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19748                                        Ptr, Ld->getPointerInfo(),
19749                                        Ld->isVolatile(), Ld->isNonTemporal(),
19750                                        Ld->isInvariant(), Ld->getAlignment());
19751       Chains.push_back(ScalarLoad.getValue(1));
19752       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19753       // another round of DAGCombining.
19754       if (i == 0)
19755         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19756       else
19757         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19758                           ScalarLoad, DAG.getIntPtrConstant(i));
19759
19760       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19761     }
19762
19763     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19764
19765     // Bitcast the loaded value to a vector of the original element type, in
19766     // the size of the target vector type.
19767     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19768     unsigned SizeRatio = RegSz/MemSz;
19769
19770     if (Ext == ISD::SEXTLOAD) {
19771       // If we have SSE4.1 we can directly emit a VSEXT node.
19772       if (Subtarget->hasSSE41()) {
19773         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19774         return DCI.CombineTo(N, Sext, TF, true);
19775       }
19776
19777       // Otherwise we'll shuffle the small elements in the high bits of the
19778       // larger type and perform an arithmetic shift. If the shift is not legal
19779       // it's better to scalarize.
19780       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19781         return SDValue();
19782
19783       // Redistribute the loaded elements into the different locations.
19784       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19785       for (unsigned i = 0; i != NumElems; ++i)
19786         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19787
19788       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19789                                            DAG.getUNDEF(WideVecVT),
19790                                            &ShuffleVec[0]);
19791
19792       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19793
19794       // Build the arithmetic shift.
19795       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19796                      MemVT.getVectorElementType().getSizeInBits();
19797       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19798                           DAG.getConstant(Amt, RegVT));
19799
19800       return DCI.CombineTo(N, Shuff, TF, true);
19801     }
19802
19803     // Redistribute the loaded elements into the different locations.
19804     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19805     for (unsigned i = 0; i != NumElems; ++i)
19806       ShuffleVec[i*SizeRatio] = i;
19807
19808     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19809                                          DAG.getUNDEF(WideVecVT),
19810                                          &ShuffleVec[0]);
19811
19812     // Bitcast to the requested type.
19813     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19814     // Replace the original load with the new sequence
19815     // and return the new chain.
19816     return DCI.CombineTo(N, Shuff, TF, true);
19817   }
19818
19819   return SDValue();
19820 }
19821
19822 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19823 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19824                                    const X86Subtarget *Subtarget) {
19825   StoreSDNode *St = cast<StoreSDNode>(N);
19826   EVT VT = St->getValue().getValueType();
19827   EVT StVT = St->getMemoryVT();
19828   SDLoc dl(St);
19829   SDValue StoredVal = St->getOperand(1);
19830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19831
19832   // If we are saving a concatenation of two XMM registers, perform two stores.
19833   // On Sandy Bridge, 256-bit memory operations are executed by two
19834   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19835   // memory  operation.
19836   unsigned Alignment = St->getAlignment();
19837   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19838   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19839       StVT == VT && !IsAligned) {
19840     unsigned NumElems = VT.getVectorNumElements();
19841     if (NumElems < 2)
19842       return SDValue();
19843
19844     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19845     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19846
19847     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19848     SDValue Ptr0 = St->getBasePtr();
19849     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19850
19851     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19852                                 St->getPointerInfo(), St->isVolatile(),
19853                                 St->isNonTemporal(), Alignment);
19854     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19855                                 St->getPointerInfo(), St->isVolatile(),
19856                                 St->isNonTemporal(),
19857                                 std::min(16U, Alignment));
19858     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19859   }
19860
19861   // Optimize trunc store (of multiple scalars) to shuffle and store.
19862   // First, pack all of the elements in one place. Next, store to memory
19863   // in fewer chunks.
19864   if (St->isTruncatingStore() && VT.isVector()) {
19865     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19866     unsigned NumElems = VT.getVectorNumElements();
19867     assert(StVT != VT && "Cannot truncate to the same type");
19868     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19869     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19870
19871     // From, To sizes and ElemCount must be pow of two
19872     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19873     // We are going to use the original vector elt for storing.
19874     // Accumulated smaller vector elements must be a multiple of the store size.
19875     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19876
19877     unsigned SizeRatio  = FromSz / ToSz;
19878
19879     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19880
19881     // Create a type on which we perform the shuffle
19882     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19883             StVT.getScalarType(), NumElems*SizeRatio);
19884
19885     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19886
19887     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19888     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19889     for (unsigned i = 0; i != NumElems; ++i)
19890       ShuffleVec[i] = i * SizeRatio;
19891
19892     // Can't shuffle using an illegal type.
19893     if (!TLI.isTypeLegal(WideVecVT))
19894       return SDValue();
19895
19896     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19897                                          DAG.getUNDEF(WideVecVT),
19898                                          &ShuffleVec[0]);
19899     // At this point all of the data is stored at the bottom of the
19900     // register. We now need to save it to mem.
19901
19902     // Find the largest store unit
19903     MVT StoreType = MVT::i8;
19904     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19905          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19906       MVT Tp = (MVT::SimpleValueType)tp;
19907       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19908         StoreType = Tp;
19909     }
19910
19911     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19912     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19913         (64 <= NumElems * ToSz))
19914       StoreType = MVT::f64;
19915
19916     // Bitcast the original vector into a vector of store-size units
19917     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19918             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19919     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19920     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19921     SmallVector<SDValue, 8> Chains;
19922     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19923                                         TLI.getPointerTy());
19924     SDValue Ptr = St->getBasePtr();
19925
19926     // Perform one or more big stores into memory.
19927     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19928       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19929                                    StoreType, ShuffWide,
19930                                    DAG.getIntPtrConstant(i));
19931       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19932                                 St->getPointerInfo(), St->isVolatile(),
19933                                 St->isNonTemporal(), St->getAlignment());
19934       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19935       Chains.push_back(Ch);
19936     }
19937
19938     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19939   }
19940
19941   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19942   // the FP state in cases where an emms may be missing.
19943   // A preferable solution to the general problem is to figure out the right
19944   // places to insert EMMS.  This qualifies as a quick hack.
19945
19946   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19947   if (VT.getSizeInBits() != 64)
19948     return SDValue();
19949
19950   const Function *F = DAG.getMachineFunction().getFunction();
19951   bool NoImplicitFloatOps = F->getAttributes().
19952     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19953   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19954                      && Subtarget->hasSSE2();
19955   if ((VT.isVector() ||
19956        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19957       isa<LoadSDNode>(St->getValue()) &&
19958       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19959       St->getChain().hasOneUse() && !St->isVolatile()) {
19960     SDNode* LdVal = St->getValue().getNode();
19961     LoadSDNode *Ld = nullptr;
19962     int TokenFactorIndex = -1;
19963     SmallVector<SDValue, 8> Ops;
19964     SDNode* ChainVal = St->getChain().getNode();
19965     // Must be a store of a load.  We currently handle two cases:  the load
19966     // is a direct child, and it's under an intervening TokenFactor.  It is
19967     // possible to dig deeper under nested TokenFactors.
19968     if (ChainVal == LdVal)
19969       Ld = cast<LoadSDNode>(St->getChain());
19970     else if (St->getValue().hasOneUse() &&
19971              ChainVal->getOpcode() == ISD::TokenFactor) {
19972       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19973         if (ChainVal->getOperand(i).getNode() == LdVal) {
19974           TokenFactorIndex = i;
19975           Ld = cast<LoadSDNode>(St->getValue());
19976         } else
19977           Ops.push_back(ChainVal->getOperand(i));
19978       }
19979     }
19980
19981     if (!Ld || !ISD::isNormalLoad(Ld))
19982       return SDValue();
19983
19984     // If this is not the MMX case, i.e. we are just turning i64 load/store
19985     // into f64 load/store, avoid the transformation if there are multiple
19986     // uses of the loaded value.
19987     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19988       return SDValue();
19989
19990     SDLoc LdDL(Ld);
19991     SDLoc StDL(N);
19992     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19993     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19994     // pair instead.
19995     if (Subtarget->is64Bit() || F64IsLegal) {
19996       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19997       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19998                                   Ld->getPointerInfo(), Ld->isVolatile(),
19999                                   Ld->isNonTemporal(), Ld->isInvariant(),
20000                                   Ld->getAlignment());
20001       SDValue NewChain = NewLd.getValue(1);
20002       if (TokenFactorIndex != -1) {
20003         Ops.push_back(NewChain);
20004         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20005       }
20006       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20007                           St->getPointerInfo(),
20008                           St->isVolatile(), St->isNonTemporal(),
20009                           St->getAlignment());
20010     }
20011
20012     // Otherwise, lower to two pairs of 32-bit loads / stores.
20013     SDValue LoAddr = Ld->getBasePtr();
20014     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20015                                  DAG.getConstant(4, MVT::i32));
20016
20017     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20018                                Ld->getPointerInfo(),
20019                                Ld->isVolatile(), Ld->isNonTemporal(),
20020                                Ld->isInvariant(), Ld->getAlignment());
20021     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20022                                Ld->getPointerInfo().getWithOffset(4),
20023                                Ld->isVolatile(), Ld->isNonTemporal(),
20024                                Ld->isInvariant(),
20025                                MinAlign(Ld->getAlignment(), 4));
20026
20027     SDValue NewChain = LoLd.getValue(1);
20028     if (TokenFactorIndex != -1) {
20029       Ops.push_back(LoLd);
20030       Ops.push_back(HiLd);
20031       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20032     }
20033
20034     LoAddr = St->getBasePtr();
20035     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20036                          DAG.getConstant(4, MVT::i32));
20037
20038     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20039                                 St->getPointerInfo(),
20040                                 St->isVolatile(), St->isNonTemporal(),
20041                                 St->getAlignment());
20042     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20043                                 St->getPointerInfo().getWithOffset(4),
20044                                 St->isVolatile(),
20045                                 St->isNonTemporal(),
20046                                 MinAlign(St->getAlignment(), 4));
20047     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20048   }
20049   return SDValue();
20050 }
20051
20052 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20053 /// and return the operands for the horizontal operation in LHS and RHS.  A
20054 /// horizontal operation performs the binary operation on successive elements
20055 /// of its first operand, then on successive elements of its second operand,
20056 /// returning the resulting values in a vector.  For example, if
20057 ///   A = < float a0, float a1, float a2, float a3 >
20058 /// and
20059 ///   B = < float b0, float b1, float b2, float b3 >
20060 /// then the result of doing a horizontal operation on A and B is
20061 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20062 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20063 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20064 /// set to A, RHS to B, and the routine returns 'true'.
20065 /// Note that the binary operation should have the property that if one of the
20066 /// operands is UNDEF then the result is UNDEF.
20067 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20068   // Look for the following pattern: if
20069   //   A = < float a0, float a1, float a2, float a3 >
20070   //   B = < float b0, float b1, float b2, float b3 >
20071   // and
20072   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20073   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20074   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20075   // which is A horizontal-op B.
20076
20077   // At least one of the operands should be a vector shuffle.
20078   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20079       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20080     return false;
20081
20082   MVT VT = LHS.getSimpleValueType();
20083
20084   assert((VT.is128BitVector() || VT.is256BitVector()) &&
20085          "Unsupported vector type for horizontal add/sub");
20086
20087   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20088   // operate independently on 128-bit lanes.
20089   unsigned NumElts = VT.getVectorNumElements();
20090   unsigned NumLanes = VT.getSizeInBits()/128;
20091   unsigned NumLaneElts = NumElts / NumLanes;
20092   assert((NumLaneElts % 2 == 0) &&
20093          "Vector type should have an even number of elements in each lane");
20094   unsigned HalfLaneElts = NumLaneElts/2;
20095
20096   // View LHS in the form
20097   //   LHS = VECTOR_SHUFFLE A, B, LMask
20098   // If LHS is not a shuffle then pretend it is the shuffle
20099   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20100   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20101   // type VT.
20102   SDValue A, B;
20103   SmallVector<int, 16> LMask(NumElts);
20104   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20105     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20106       A = LHS.getOperand(0);
20107     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20108       B = LHS.getOperand(1);
20109     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20110     std::copy(Mask.begin(), Mask.end(), LMask.begin());
20111   } else {
20112     if (LHS.getOpcode() != ISD::UNDEF)
20113       A = LHS;
20114     for (unsigned i = 0; i != NumElts; ++i)
20115       LMask[i] = i;
20116   }
20117
20118   // Likewise, view RHS in the form
20119   //   RHS = VECTOR_SHUFFLE C, D, RMask
20120   SDValue C, D;
20121   SmallVector<int, 16> RMask(NumElts);
20122   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20123     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20124       C = RHS.getOperand(0);
20125     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20126       D = RHS.getOperand(1);
20127     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20128     std::copy(Mask.begin(), Mask.end(), RMask.begin());
20129   } else {
20130     if (RHS.getOpcode() != ISD::UNDEF)
20131       C = RHS;
20132     for (unsigned i = 0; i != NumElts; ++i)
20133       RMask[i] = i;
20134   }
20135
20136   // Check that the shuffles are both shuffling the same vectors.
20137   if (!(A == C && B == D) && !(A == D && B == C))
20138     return false;
20139
20140   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20141   if (!A.getNode() && !B.getNode())
20142     return false;
20143
20144   // If A and B occur in reverse order in RHS, then "swap" them (which means
20145   // rewriting the mask).
20146   if (A != C)
20147     CommuteVectorShuffleMask(RMask, NumElts);
20148
20149   // At this point LHS and RHS are equivalent to
20150   //   LHS = VECTOR_SHUFFLE A, B, LMask
20151   //   RHS = VECTOR_SHUFFLE A, B, RMask
20152   // Check that the masks correspond to performing a horizontal operation.
20153   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20154     for (unsigned i = 0; i != NumLaneElts; ++i) {
20155       int LIdx = LMask[i+l], RIdx = RMask[i+l];
20156
20157       // Ignore any UNDEF components.
20158       if (LIdx < 0 || RIdx < 0 ||
20159           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20160           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20161         continue;
20162
20163       // Check that successive elements are being operated on.  If not, this is
20164       // not a horizontal operation.
20165       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20166       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20167       if (!(LIdx == Index && RIdx == Index + 1) &&
20168           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20169         return false;
20170     }
20171   }
20172
20173   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20174   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20175   return true;
20176 }
20177
20178 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20179 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20180                                   const X86Subtarget *Subtarget) {
20181   EVT VT = N->getValueType(0);
20182   SDValue LHS = N->getOperand(0);
20183   SDValue RHS = N->getOperand(1);
20184
20185   // Try to synthesize horizontal adds from adds of shuffles.
20186   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20187        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20188       isHorizontalBinOp(LHS, RHS, true))
20189     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20190   return SDValue();
20191 }
20192
20193 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20194 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20195                                   const X86Subtarget *Subtarget) {
20196   EVT VT = N->getValueType(0);
20197   SDValue LHS = N->getOperand(0);
20198   SDValue RHS = N->getOperand(1);
20199
20200   // Try to synthesize horizontal subs from subs of shuffles.
20201   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20202        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20203       isHorizontalBinOp(LHS, RHS, false))
20204     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20205   return SDValue();
20206 }
20207
20208 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20209 /// X86ISD::FXOR nodes.
20210 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20211   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20212   // F[X]OR(0.0, x) -> x
20213   // F[X]OR(x, 0.0) -> x
20214   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20215     if (C->getValueAPF().isPosZero())
20216       return N->getOperand(1);
20217   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20218     if (C->getValueAPF().isPosZero())
20219       return N->getOperand(0);
20220   return SDValue();
20221 }
20222
20223 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20224 /// X86ISD::FMAX nodes.
20225 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20226   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20227
20228   // Only perform optimizations if UnsafeMath is used.
20229   if (!DAG.getTarget().Options.UnsafeFPMath)
20230     return SDValue();
20231
20232   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20233   // into FMINC and FMAXC, which are Commutative operations.
20234   unsigned NewOp = 0;
20235   switch (N->getOpcode()) {
20236     default: llvm_unreachable("unknown opcode");
20237     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20238     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20239   }
20240
20241   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20242                      N->getOperand(0), N->getOperand(1));
20243 }
20244
20245 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20246 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20247   // FAND(0.0, x) -> 0.0
20248   // FAND(x, 0.0) -> 0.0
20249   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20250     if (C->getValueAPF().isPosZero())
20251       return N->getOperand(0);
20252   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20253     if (C->getValueAPF().isPosZero())
20254       return N->getOperand(1);
20255   return SDValue();
20256 }
20257
20258 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20259 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20260   // FANDN(x, 0.0) -> 0.0
20261   // FANDN(0.0, x) -> x
20262   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20263     if (C->getValueAPF().isPosZero())
20264       return N->getOperand(1);
20265   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20266     if (C->getValueAPF().isPosZero())
20267       return N->getOperand(1);
20268   return SDValue();
20269 }
20270
20271 static SDValue PerformBTCombine(SDNode *N,
20272                                 SelectionDAG &DAG,
20273                                 TargetLowering::DAGCombinerInfo &DCI) {
20274   // BT ignores high bits in the bit index operand.
20275   SDValue Op1 = N->getOperand(1);
20276   if (Op1.hasOneUse()) {
20277     unsigned BitWidth = Op1.getValueSizeInBits();
20278     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20279     APInt KnownZero, KnownOne;
20280     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20281                                           !DCI.isBeforeLegalizeOps());
20282     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20283     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20284         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20285       DCI.CommitTargetLoweringOpt(TLO);
20286   }
20287   return SDValue();
20288 }
20289
20290 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20291   SDValue Op = N->getOperand(0);
20292   if (Op.getOpcode() == ISD::BITCAST)
20293     Op = Op.getOperand(0);
20294   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20295   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20296       VT.getVectorElementType().getSizeInBits() ==
20297       OpVT.getVectorElementType().getSizeInBits()) {
20298     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20299   }
20300   return SDValue();
20301 }
20302
20303 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20304                                                const X86Subtarget *Subtarget) {
20305   EVT VT = N->getValueType(0);
20306   if (!VT.isVector())
20307     return SDValue();
20308
20309   SDValue N0 = N->getOperand(0);
20310   SDValue N1 = N->getOperand(1);
20311   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20312   SDLoc dl(N);
20313
20314   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20315   // both SSE and AVX2 since there is no sign-extended shift right
20316   // operation on a vector with 64-bit elements.
20317   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20318   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20319   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20320       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20321     SDValue N00 = N0.getOperand(0);
20322
20323     // EXTLOAD has a better solution on AVX2,
20324     // it may be replaced with X86ISD::VSEXT node.
20325     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20326       if (!ISD::isNormalLoad(N00.getNode()))
20327         return SDValue();
20328
20329     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20330         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20331                                   N00, N1);
20332       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20333     }
20334   }
20335   return SDValue();
20336 }
20337
20338 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20339                                   TargetLowering::DAGCombinerInfo &DCI,
20340                                   const X86Subtarget *Subtarget) {
20341   if (!DCI.isBeforeLegalizeOps())
20342     return SDValue();
20343
20344   if (!Subtarget->hasFp256())
20345     return SDValue();
20346
20347   EVT VT = N->getValueType(0);
20348   if (VT.isVector() && VT.getSizeInBits() == 256) {
20349     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20350     if (R.getNode())
20351       return R;
20352   }
20353
20354   return SDValue();
20355 }
20356
20357 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20358                                  const X86Subtarget* Subtarget) {
20359   SDLoc dl(N);
20360   EVT VT = N->getValueType(0);
20361
20362   // Let legalize expand this if it isn't a legal type yet.
20363   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20364     return SDValue();
20365
20366   EVT ScalarVT = VT.getScalarType();
20367   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20368       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20369     return SDValue();
20370
20371   SDValue A = N->getOperand(0);
20372   SDValue B = N->getOperand(1);
20373   SDValue C = N->getOperand(2);
20374
20375   bool NegA = (A.getOpcode() == ISD::FNEG);
20376   bool NegB = (B.getOpcode() == ISD::FNEG);
20377   bool NegC = (C.getOpcode() == ISD::FNEG);
20378
20379   // Negative multiplication when NegA xor NegB
20380   bool NegMul = (NegA != NegB);
20381   if (NegA)
20382     A = A.getOperand(0);
20383   if (NegB)
20384     B = B.getOperand(0);
20385   if (NegC)
20386     C = C.getOperand(0);
20387
20388   unsigned Opcode;
20389   if (!NegMul)
20390     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20391   else
20392     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20393
20394   return DAG.getNode(Opcode, dl, VT, A, B, C);
20395 }
20396
20397 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20398                                   TargetLowering::DAGCombinerInfo &DCI,
20399                                   const X86Subtarget *Subtarget) {
20400   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20401   //           (and (i32 x86isd::setcc_carry), 1)
20402   // This eliminates the zext. This transformation is necessary because
20403   // ISD::SETCC is always legalized to i8.
20404   SDLoc dl(N);
20405   SDValue N0 = N->getOperand(0);
20406   EVT VT = N->getValueType(0);
20407
20408   if (N0.getOpcode() == ISD::AND &&
20409       N0.hasOneUse() &&
20410       N0.getOperand(0).hasOneUse()) {
20411     SDValue N00 = N0.getOperand(0);
20412     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20413       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20414       if (!C || C->getZExtValue() != 1)
20415         return SDValue();
20416       return DAG.getNode(ISD::AND, dl, VT,
20417                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20418                                      N00.getOperand(0), N00.getOperand(1)),
20419                          DAG.getConstant(1, VT));
20420     }
20421   }
20422
20423   if (N0.getOpcode() == ISD::TRUNCATE &&
20424       N0.hasOneUse() &&
20425       N0.getOperand(0).hasOneUse()) {
20426     SDValue N00 = N0.getOperand(0);
20427     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20428       return DAG.getNode(ISD::AND, dl, VT,
20429                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20430                                      N00.getOperand(0), N00.getOperand(1)),
20431                          DAG.getConstant(1, VT));
20432     }
20433   }
20434   if (VT.is256BitVector()) {
20435     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20436     if (R.getNode())
20437       return R;
20438   }
20439
20440   return SDValue();
20441 }
20442
20443 // Optimize x == -y --> x+y == 0
20444 //          x != -y --> x+y != 0
20445 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20446                                       const X86Subtarget* Subtarget) {
20447   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20448   SDValue LHS = N->getOperand(0);
20449   SDValue RHS = N->getOperand(1);
20450   EVT VT = N->getValueType(0);
20451   SDLoc DL(N);
20452
20453   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20454     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20455       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20456         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20457                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20458         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20459                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20460       }
20461   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20462     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20463       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20464         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20465                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20466         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20467                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20468       }
20469
20470   if (VT.getScalarType() == MVT::i1) {
20471     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20472       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20473     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20474     if (!IsSEXT0 && !IsVZero0)
20475       return SDValue();
20476     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20477       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20478     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20479
20480     if (!IsSEXT1 && !IsVZero1)
20481       return SDValue();
20482
20483     if (IsSEXT0 && IsVZero1) {
20484       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20485       if (CC == ISD::SETEQ)
20486         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20487       return LHS.getOperand(0);
20488     }
20489     if (IsSEXT1 && IsVZero0) {
20490       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20491       if (CC == ISD::SETEQ)
20492         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20493       return RHS.getOperand(0);
20494     }
20495   }
20496
20497   return SDValue();
20498 }
20499
20500 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20501                                       const X86Subtarget *Subtarget) {
20502   SDLoc dl(N);
20503   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20504   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20505          "X86insertps is only defined for v4x32");
20506
20507   SDValue Ld = N->getOperand(1);
20508   if (MayFoldLoad(Ld)) {
20509     // Extract the countS bits from the immediate so we can get the proper
20510     // address when narrowing the vector load to a specific element.
20511     // When the second source op is a memory address, interps doesn't use
20512     // countS and just gets an f32 from that address.
20513     unsigned DestIndex =
20514         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20515     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20516   } else
20517     return SDValue();
20518
20519   // Create this as a scalar to vector to match the instruction pattern.
20520   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20521   // countS bits are ignored when loading from memory on insertps, which
20522   // means we don't need to explicitly set them to 0.
20523   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20524                      LoadScalarToVector, N->getOperand(2));
20525 }
20526
20527 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20528 // as "sbb reg,reg", since it can be extended without zext and produces
20529 // an all-ones bit which is more useful than 0/1 in some cases.
20530 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20531                                MVT VT) {
20532   if (VT == MVT::i8)
20533     return DAG.getNode(ISD::AND, DL, VT,
20534                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20535                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20536                        DAG.getConstant(1, VT));
20537   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20538   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20539                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20540                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20541 }
20542
20543 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20544 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20545                                    TargetLowering::DAGCombinerInfo &DCI,
20546                                    const X86Subtarget *Subtarget) {
20547   SDLoc DL(N);
20548   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20549   SDValue EFLAGS = N->getOperand(1);
20550
20551   if (CC == X86::COND_A) {
20552     // Try to convert COND_A into COND_B in an attempt to facilitate
20553     // materializing "setb reg".
20554     //
20555     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20556     // cannot take an immediate as its first operand.
20557     //
20558     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20559         EFLAGS.getValueType().isInteger() &&
20560         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20561       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20562                                    EFLAGS.getNode()->getVTList(),
20563                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20564       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20565       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20566     }
20567   }
20568
20569   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20570   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20571   // cases.
20572   if (CC == X86::COND_B)
20573     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20574
20575   SDValue Flags;
20576
20577   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20578   if (Flags.getNode()) {
20579     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20580     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20581   }
20582
20583   return SDValue();
20584 }
20585
20586 // Optimize branch condition evaluation.
20587 //
20588 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20589                                     TargetLowering::DAGCombinerInfo &DCI,
20590                                     const X86Subtarget *Subtarget) {
20591   SDLoc DL(N);
20592   SDValue Chain = N->getOperand(0);
20593   SDValue Dest = N->getOperand(1);
20594   SDValue EFLAGS = N->getOperand(3);
20595   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20596
20597   SDValue Flags;
20598
20599   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20600   if (Flags.getNode()) {
20601     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20602     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20603                        Flags);
20604   }
20605
20606   return SDValue();
20607 }
20608
20609 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20610                                         const X86TargetLowering *XTLI) {
20611   SDValue Op0 = N->getOperand(0);
20612   EVT InVT = Op0->getValueType(0);
20613
20614   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20615   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20616     SDLoc dl(N);
20617     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20618     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20619     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20620   }
20621
20622   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20623   // a 32-bit target where SSE doesn't support i64->FP operations.
20624   if (Op0.getOpcode() == ISD::LOAD) {
20625     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20626     EVT VT = Ld->getValueType(0);
20627     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20628         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20629         !XTLI->getSubtarget()->is64Bit() &&
20630         VT == MVT::i64) {
20631       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20632                                           Ld->getChain(), Op0, DAG);
20633       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20634       return FILDChain;
20635     }
20636   }
20637   return SDValue();
20638 }
20639
20640 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20641 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20642                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20643   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20644   // the result is either zero or one (depending on the input carry bit).
20645   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20646   if (X86::isZeroNode(N->getOperand(0)) &&
20647       X86::isZeroNode(N->getOperand(1)) &&
20648       // We don't have a good way to replace an EFLAGS use, so only do this when
20649       // dead right now.
20650       SDValue(N, 1).use_empty()) {
20651     SDLoc DL(N);
20652     EVT VT = N->getValueType(0);
20653     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20654     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20655                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20656                                            DAG.getConstant(X86::COND_B,MVT::i8),
20657                                            N->getOperand(2)),
20658                                DAG.getConstant(1, VT));
20659     return DCI.CombineTo(N, Res1, CarryOut);
20660   }
20661
20662   return SDValue();
20663 }
20664
20665 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20666 //      (add Y, (setne X, 0)) -> sbb -1, Y
20667 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20668 //      (sub (setne X, 0), Y) -> adc -1, Y
20669 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20670   SDLoc DL(N);
20671
20672   // Look through ZExts.
20673   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20674   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20675     return SDValue();
20676
20677   SDValue SetCC = Ext.getOperand(0);
20678   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20679     return SDValue();
20680
20681   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20682   if (CC != X86::COND_E && CC != X86::COND_NE)
20683     return SDValue();
20684
20685   SDValue Cmp = SetCC.getOperand(1);
20686   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20687       !X86::isZeroNode(Cmp.getOperand(1)) ||
20688       !Cmp.getOperand(0).getValueType().isInteger())
20689     return SDValue();
20690
20691   SDValue CmpOp0 = Cmp.getOperand(0);
20692   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20693                                DAG.getConstant(1, CmpOp0.getValueType()));
20694
20695   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20696   if (CC == X86::COND_NE)
20697     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20698                        DL, OtherVal.getValueType(), OtherVal,
20699                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20700   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20701                      DL, OtherVal.getValueType(), OtherVal,
20702                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20703 }
20704
20705 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20706 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20707                                  const X86Subtarget *Subtarget) {
20708   EVT VT = N->getValueType(0);
20709   SDValue Op0 = N->getOperand(0);
20710   SDValue Op1 = N->getOperand(1);
20711
20712   // Try to synthesize horizontal adds from adds of shuffles.
20713   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20714        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20715       isHorizontalBinOp(Op0, Op1, true))
20716     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20717
20718   return OptimizeConditionalInDecrement(N, DAG);
20719 }
20720
20721 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20722                                  const X86Subtarget *Subtarget) {
20723   SDValue Op0 = N->getOperand(0);
20724   SDValue Op1 = N->getOperand(1);
20725
20726   // X86 can't encode an immediate LHS of a sub. See if we can push the
20727   // negation into a preceding instruction.
20728   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20729     // If the RHS of the sub is a XOR with one use and a constant, invert the
20730     // immediate. Then add one to the LHS of the sub so we can turn
20731     // X-Y -> X+~Y+1, saving one register.
20732     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20733         isa<ConstantSDNode>(Op1.getOperand(1))) {
20734       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20735       EVT VT = Op0.getValueType();
20736       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20737                                    Op1.getOperand(0),
20738                                    DAG.getConstant(~XorC, VT));
20739       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20740                          DAG.getConstant(C->getAPIntValue()+1, VT));
20741     }
20742   }
20743
20744   // Try to synthesize horizontal adds from adds of shuffles.
20745   EVT VT = N->getValueType(0);
20746   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20747        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20748       isHorizontalBinOp(Op0, Op1, true))
20749     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20750
20751   return OptimizeConditionalInDecrement(N, DAG);
20752 }
20753
20754 /// performVZEXTCombine - Performs build vector combines
20755 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20756                                         TargetLowering::DAGCombinerInfo &DCI,
20757                                         const X86Subtarget *Subtarget) {
20758   // (vzext (bitcast (vzext (x)) -> (vzext x)
20759   SDValue In = N->getOperand(0);
20760   while (In.getOpcode() == ISD::BITCAST)
20761     In = In.getOperand(0);
20762
20763   if (In.getOpcode() != X86ISD::VZEXT)
20764     return SDValue();
20765
20766   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20767                      In.getOperand(0));
20768 }
20769
20770 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20771                                              DAGCombinerInfo &DCI) const {
20772   SelectionDAG &DAG = DCI.DAG;
20773   switch (N->getOpcode()) {
20774   default: break;
20775   case ISD::EXTRACT_VECTOR_ELT:
20776     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20777   case ISD::VSELECT:
20778   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20779   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20780   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20781   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20782   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20783   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20784   case ISD::SHL:
20785   case ISD::SRA:
20786   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20787   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20788   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20789   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20790   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20791   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20792   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20793   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20794   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20795   case X86ISD::FXOR:
20796   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20797   case X86ISD::FMIN:
20798   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20799   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20800   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20801   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20802   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20803   case ISD::ANY_EXTEND:
20804   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20805   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20806   case ISD::SIGN_EXTEND_INREG:
20807     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20808   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20809   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20810   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20811   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20812   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20813   case X86ISD::SHUFP:       // Handle all target specific shuffles
20814   case X86ISD::PALIGNR:
20815   case X86ISD::UNPCKH:
20816   case X86ISD::UNPCKL:
20817   case X86ISD::MOVHLPS:
20818   case X86ISD::MOVLHPS:
20819   case X86ISD::PSHUFD:
20820   case X86ISD::PSHUFHW:
20821   case X86ISD::PSHUFLW:
20822   case X86ISD::MOVSS:
20823   case X86ISD::MOVSD:
20824   case X86ISD::VPERMILP:
20825   case X86ISD::VPERM2X128:
20826   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20827   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20828   case ISD::INTRINSIC_WO_CHAIN:
20829     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20830   case X86ISD::INSERTPS:
20831     return PerformINSERTPSCombine(N, DAG, Subtarget);
20832   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
20833   }
20834
20835   return SDValue();
20836 }
20837
20838 /// isTypeDesirableForOp - Return true if the target has native support for
20839 /// the specified value type and it is 'desirable' to use the type for the
20840 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20841 /// instruction encodings are longer and some i16 instructions are slow.
20842 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20843   if (!isTypeLegal(VT))
20844     return false;
20845   if (VT != MVT::i16)
20846     return true;
20847
20848   switch (Opc) {
20849   default:
20850     return true;
20851   case ISD::LOAD:
20852   case ISD::SIGN_EXTEND:
20853   case ISD::ZERO_EXTEND:
20854   case ISD::ANY_EXTEND:
20855   case ISD::SHL:
20856   case ISD::SRL:
20857   case ISD::SUB:
20858   case ISD::ADD:
20859   case ISD::MUL:
20860   case ISD::AND:
20861   case ISD::OR:
20862   case ISD::XOR:
20863     return false;
20864   }
20865 }
20866
20867 /// IsDesirableToPromoteOp - This method query the target whether it is
20868 /// beneficial for dag combiner to promote the specified node. If true, it
20869 /// should return the desired promotion type by reference.
20870 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20871   EVT VT = Op.getValueType();
20872   if (VT != MVT::i16)
20873     return false;
20874
20875   bool Promote = false;
20876   bool Commute = false;
20877   switch (Op.getOpcode()) {
20878   default: break;
20879   case ISD::LOAD: {
20880     LoadSDNode *LD = cast<LoadSDNode>(Op);
20881     // If the non-extending load has a single use and it's not live out, then it
20882     // might be folded.
20883     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20884                                                      Op.hasOneUse()*/) {
20885       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20886              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20887         // The only case where we'd want to promote LOAD (rather then it being
20888         // promoted as an operand is when it's only use is liveout.
20889         if (UI->getOpcode() != ISD::CopyToReg)
20890           return false;
20891       }
20892     }
20893     Promote = true;
20894     break;
20895   }
20896   case ISD::SIGN_EXTEND:
20897   case ISD::ZERO_EXTEND:
20898   case ISD::ANY_EXTEND:
20899     Promote = true;
20900     break;
20901   case ISD::SHL:
20902   case ISD::SRL: {
20903     SDValue N0 = Op.getOperand(0);
20904     // Look out for (store (shl (load), x)).
20905     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20906       return false;
20907     Promote = true;
20908     break;
20909   }
20910   case ISD::ADD:
20911   case ISD::MUL:
20912   case ISD::AND:
20913   case ISD::OR:
20914   case ISD::XOR:
20915     Commute = true;
20916     // fallthrough
20917   case ISD::SUB: {
20918     SDValue N0 = Op.getOperand(0);
20919     SDValue N1 = Op.getOperand(1);
20920     if (!Commute && MayFoldLoad(N1))
20921       return false;
20922     // Avoid disabling potential load folding opportunities.
20923     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20924       return false;
20925     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20926       return false;
20927     Promote = true;
20928   }
20929   }
20930
20931   PVT = MVT::i32;
20932   return Promote;
20933 }
20934
20935 //===----------------------------------------------------------------------===//
20936 //                           X86 Inline Assembly Support
20937 //===----------------------------------------------------------------------===//
20938
20939 namespace {
20940   // Helper to match a string separated by whitespace.
20941   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20942     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20943
20944     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20945       StringRef piece(*args[i]);
20946       if (!s.startswith(piece)) // Check if the piece matches.
20947         return false;
20948
20949       s = s.substr(piece.size());
20950       StringRef::size_type pos = s.find_first_not_of(" \t");
20951       if (pos == 0) // We matched a prefix.
20952         return false;
20953
20954       s = s.substr(pos);
20955     }
20956
20957     return s.empty();
20958   }
20959   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20960 }
20961
20962 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20963
20964   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20965     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20966         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20967         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20968
20969       if (AsmPieces.size() == 3)
20970         return true;
20971       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20972         return true;
20973     }
20974   }
20975   return false;
20976 }
20977
20978 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20979   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20980
20981   std::string AsmStr = IA->getAsmString();
20982
20983   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20984   if (!Ty || Ty->getBitWidth() % 16 != 0)
20985     return false;
20986
20987   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20988   SmallVector<StringRef, 4> AsmPieces;
20989   SplitString(AsmStr, AsmPieces, ";\n");
20990
20991   switch (AsmPieces.size()) {
20992   default: return false;
20993   case 1:
20994     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20995     // we will turn this bswap into something that will be lowered to logical
20996     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20997     // lower so don't worry about this.
20998     // bswap $0
20999     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21000         matchAsm(AsmPieces[0], "bswapl", "$0") ||
21001         matchAsm(AsmPieces[0], "bswapq", "$0") ||
21002         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21003         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21004         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21005       // No need to check constraints, nothing other than the equivalent of
21006       // "=r,0" would be valid here.
21007       return IntrinsicLowering::LowerToByteSwap(CI);
21008     }
21009
21010     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
21011     if (CI->getType()->isIntegerTy(16) &&
21012         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21013         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21014          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21015       AsmPieces.clear();
21016       const std::string &ConstraintsStr = IA->getConstraintString();
21017       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21018       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21019       if (clobbersFlagRegisters(AsmPieces))
21020         return IntrinsicLowering::LowerToByteSwap(CI);
21021     }
21022     break;
21023   case 3:
21024     if (CI->getType()->isIntegerTy(32) &&
21025         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21026         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21027         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21028         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21029       AsmPieces.clear();
21030       const std::string &ConstraintsStr = IA->getConstraintString();
21031       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21032       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21033       if (clobbersFlagRegisters(AsmPieces))
21034         return IntrinsicLowering::LowerToByteSwap(CI);
21035     }
21036
21037     if (CI->getType()->isIntegerTy(64)) {
21038       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21039       if (Constraints.size() >= 2 &&
21040           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21041           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21042         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
21043         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21044             matchAsm(AsmPieces[1], "bswap", "%edx") &&
21045             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21046           return IntrinsicLowering::LowerToByteSwap(CI);
21047       }
21048     }
21049     break;
21050   }
21051   return false;
21052 }
21053
21054 /// getConstraintType - Given a constraint letter, return the type of
21055 /// constraint it is for this target.
21056 X86TargetLowering::ConstraintType
21057 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21058   if (Constraint.size() == 1) {
21059     switch (Constraint[0]) {
21060     case 'R':
21061     case 'q':
21062     case 'Q':
21063     case 'f':
21064     case 't':
21065     case 'u':
21066     case 'y':
21067     case 'x':
21068     case 'Y':
21069     case 'l':
21070       return C_RegisterClass;
21071     case 'a':
21072     case 'b':
21073     case 'c':
21074     case 'd':
21075     case 'S':
21076     case 'D':
21077     case 'A':
21078       return C_Register;
21079     case 'I':
21080     case 'J':
21081     case 'K':
21082     case 'L':
21083     case 'M':
21084     case 'N':
21085     case 'G':
21086     case 'C':
21087     case 'e':
21088     case 'Z':
21089       return C_Other;
21090     default:
21091       break;
21092     }
21093   }
21094   return TargetLowering::getConstraintType(Constraint);
21095 }
21096
21097 /// Examine constraint type and operand type and determine a weight value.
21098 /// This object must already have been set up with the operand type
21099 /// and the current alternative constraint selected.
21100 TargetLowering::ConstraintWeight
21101   X86TargetLowering::getSingleConstraintMatchWeight(
21102     AsmOperandInfo &info, const char *constraint) const {
21103   ConstraintWeight weight = CW_Invalid;
21104   Value *CallOperandVal = info.CallOperandVal;
21105     // If we don't have a value, we can't do a match,
21106     // but allow it at the lowest weight.
21107   if (!CallOperandVal)
21108     return CW_Default;
21109   Type *type = CallOperandVal->getType();
21110   // Look at the constraint type.
21111   switch (*constraint) {
21112   default:
21113     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21114   case 'R':
21115   case 'q':
21116   case 'Q':
21117   case 'a':
21118   case 'b':
21119   case 'c':
21120   case 'd':
21121   case 'S':
21122   case 'D':
21123   case 'A':
21124     if (CallOperandVal->getType()->isIntegerTy())
21125       weight = CW_SpecificReg;
21126     break;
21127   case 'f':
21128   case 't':
21129   case 'u':
21130     if (type->isFloatingPointTy())
21131       weight = CW_SpecificReg;
21132     break;
21133   case 'y':
21134     if (type->isX86_MMXTy() && Subtarget->hasMMX())
21135       weight = CW_SpecificReg;
21136     break;
21137   case 'x':
21138   case 'Y':
21139     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21140         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21141       weight = CW_Register;
21142     break;
21143   case 'I':
21144     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21145       if (C->getZExtValue() <= 31)
21146         weight = CW_Constant;
21147     }
21148     break;
21149   case 'J':
21150     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21151       if (C->getZExtValue() <= 63)
21152         weight = CW_Constant;
21153     }
21154     break;
21155   case 'K':
21156     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21157       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21158         weight = CW_Constant;
21159     }
21160     break;
21161   case 'L':
21162     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21163       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21164         weight = CW_Constant;
21165     }
21166     break;
21167   case 'M':
21168     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21169       if (C->getZExtValue() <= 3)
21170         weight = CW_Constant;
21171     }
21172     break;
21173   case 'N':
21174     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21175       if (C->getZExtValue() <= 0xff)
21176         weight = CW_Constant;
21177     }
21178     break;
21179   case 'G':
21180   case 'C':
21181     if (dyn_cast<ConstantFP>(CallOperandVal)) {
21182       weight = CW_Constant;
21183     }
21184     break;
21185   case 'e':
21186     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21187       if ((C->getSExtValue() >= -0x80000000LL) &&
21188           (C->getSExtValue() <= 0x7fffffffLL))
21189         weight = CW_Constant;
21190     }
21191     break;
21192   case 'Z':
21193     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21194       if (C->getZExtValue() <= 0xffffffff)
21195         weight = CW_Constant;
21196     }
21197     break;
21198   }
21199   return weight;
21200 }
21201
21202 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21203 /// with another that has more specific requirements based on the type of the
21204 /// corresponding operand.
21205 const char *X86TargetLowering::
21206 LowerXConstraint(EVT ConstraintVT) const {
21207   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21208   // 'f' like normal targets.
21209   if (ConstraintVT.isFloatingPoint()) {
21210     if (Subtarget->hasSSE2())
21211       return "Y";
21212     if (Subtarget->hasSSE1())
21213       return "x";
21214   }
21215
21216   return TargetLowering::LowerXConstraint(ConstraintVT);
21217 }
21218
21219 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21220 /// vector.  If it is invalid, don't add anything to Ops.
21221 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21222                                                      std::string &Constraint,
21223                                                      std::vector<SDValue>&Ops,
21224                                                      SelectionDAG &DAG) const {
21225   SDValue Result;
21226
21227   // Only support length 1 constraints for now.
21228   if (Constraint.length() > 1) return;
21229
21230   char ConstraintLetter = Constraint[0];
21231   switch (ConstraintLetter) {
21232   default: break;
21233   case 'I':
21234     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21235       if (C->getZExtValue() <= 31) {
21236         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21237         break;
21238       }
21239     }
21240     return;
21241   case 'J':
21242     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21243       if (C->getZExtValue() <= 63) {
21244         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21245         break;
21246       }
21247     }
21248     return;
21249   case 'K':
21250     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21251       if (isInt<8>(C->getSExtValue())) {
21252         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21253         break;
21254       }
21255     }
21256     return;
21257   case 'N':
21258     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21259       if (C->getZExtValue() <= 255) {
21260         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21261         break;
21262       }
21263     }
21264     return;
21265   case 'e': {
21266     // 32-bit signed value
21267     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21268       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21269                                            C->getSExtValue())) {
21270         // Widen to 64 bits here to get it sign extended.
21271         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21272         break;
21273       }
21274     // FIXME gcc accepts some relocatable values here too, but only in certain
21275     // memory models; it's complicated.
21276     }
21277     return;
21278   }
21279   case 'Z': {
21280     // 32-bit unsigned value
21281     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21282       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21283                                            C->getZExtValue())) {
21284         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21285         break;
21286       }
21287     }
21288     // FIXME gcc accepts some relocatable values here too, but only in certain
21289     // memory models; it's complicated.
21290     return;
21291   }
21292   case 'i': {
21293     // Literal immediates are always ok.
21294     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21295       // Widen to 64 bits here to get it sign extended.
21296       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21297       break;
21298     }
21299
21300     // In any sort of PIC mode addresses need to be computed at runtime by
21301     // adding in a register or some sort of table lookup.  These can't
21302     // be used as immediates.
21303     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21304       return;
21305
21306     // If we are in non-pic codegen mode, we allow the address of a global (with
21307     // an optional displacement) to be used with 'i'.
21308     GlobalAddressSDNode *GA = nullptr;
21309     int64_t Offset = 0;
21310
21311     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21312     while (1) {
21313       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21314         Offset += GA->getOffset();
21315         break;
21316       } else if (Op.getOpcode() == ISD::ADD) {
21317         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21318           Offset += C->getZExtValue();
21319           Op = Op.getOperand(0);
21320           continue;
21321         }
21322       } else if (Op.getOpcode() == ISD::SUB) {
21323         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21324           Offset += -C->getZExtValue();
21325           Op = Op.getOperand(0);
21326           continue;
21327         }
21328       }
21329
21330       // Otherwise, this isn't something we can handle, reject it.
21331       return;
21332     }
21333
21334     const GlobalValue *GV = GA->getGlobal();
21335     // If we require an extra load to get this address, as in PIC mode, we
21336     // can't accept it.
21337     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21338                                                         getTargetMachine())))
21339       return;
21340
21341     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21342                                         GA->getValueType(0), Offset);
21343     break;
21344   }
21345   }
21346
21347   if (Result.getNode()) {
21348     Ops.push_back(Result);
21349     return;
21350   }
21351   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21352 }
21353
21354 std::pair<unsigned, const TargetRegisterClass*>
21355 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21356                                                 MVT VT) const {
21357   // First, see if this is a constraint that directly corresponds to an LLVM
21358   // register class.
21359   if (Constraint.size() == 1) {
21360     // GCC Constraint Letters
21361     switch (Constraint[0]) {
21362     default: break;
21363       // TODO: Slight differences here in allocation order and leaving
21364       // RIP in the class. Do they matter any more here than they do
21365       // in the normal allocation?
21366     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21367       if (Subtarget->is64Bit()) {
21368         if (VT == MVT::i32 || VT == MVT::f32)
21369           return std::make_pair(0U, &X86::GR32RegClass);
21370         if (VT == MVT::i16)
21371           return std::make_pair(0U, &X86::GR16RegClass);
21372         if (VT == MVT::i8 || VT == MVT::i1)
21373           return std::make_pair(0U, &X86::GR8RegClass);
21374         if (VT == MVT::i64 || VT == MVT::f64)
21375           return std::make_pair(0U, &X86::GR64RegClass);
21376         break;
21377       }
21378       // 32-bit fallthrough
21379     case 'Q':   // Q_REGS
21380       if (VT == MVT::i32 || VT == MVT::f32)
21381         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21382       if (VT == MVT::i16)
21383         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21384       if (VT == MVT::i8 || VT == MVT::i1)
21385         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21386       if (VT == MVT::i64)
21387         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21388       break;
21389     case 'r':   // GENERAL_REGS
21390     case 'l':   // INDEX_REGS
21391       if (VT == MVT::i8 || VT == MVT::i1)
21392         return std::make_pair(0U, &X86::GR8RegClass);
21393       if (VT == MVT::i16)
21394         return std::make_pair(0U, &X86::GR16RegClass);
21395       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21396         return std::make_pair(0U, &X86::GR32RegClass);
21397       return std::make_pair(0U, &X86::GR64RegClass);
21398     case 'R':   // LEGACY_REGS
21399       if (VT == MVT::i8 || VT == MVT::i1)
21400         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21401       if (VT == MVT::i16)
21402         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21403       if (VT == MVT::i32 || !Subtarget->is64Bit())
21404         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21405       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21406     case 'f':  // FP Stack registers.
21407       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21408       // value to the correct fpstack register class.
21409       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21410         return std::make_pair(0U, &X86::RFP32RegClass);
21411       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21412         return std::make_pair(0U, &X86::RFP64RegClass);
21413       return std::make_pair(0U, &X86::RFP80RegClass);
21414     case 'y':   // MMX_REGS if MMX allowed.
21415       if (!Subtarget->hasMMX()) break;
21416       return std::make_pair(0U, &X86::VR64RegClass);
21417     case 'Y':   // SSE_REGS if SSE2 allowed
21418       if (!Subtarget->hasSSE2()) break;
21419       // FALL THROUGH.
21420     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21421       if (!Subtarget->hasSSE1()) break;
21422
21423       switch (VT.SimpleTy) {
21424       default: break;
21425       // Scalar SSE types.
21426       case MVT::f32:
21427       case MVT::i32:
21428         return std::make_pair(0U, &X86::FR32RegClass);
21429       case MVT::f64:
21430       case MVT::i64:
21431         return std::make_pair(0U, &X86::FR64RegClass);
21432       // Vector types.
21433       case MVT::v16i8:
21434       case MVT::v8i16:
21435       case MVT::v4i32:
21436       case MVT::v2i64:
21437       case MVT::v4f32:
21438       case MVT::v2f64:
21439         return std::make_pair(0U, &X86::VR128RegClass);
21440       // AVX types.
21441       case MVT::v32i8:
21442       case MVT::v16i16:
21443       case MVT::v8i32:
21444       case MVT::v4i64:
21445       case MVT::v8f32:
21446       case MVT::v4f64:
21447         return std::make_pair(0U, &X86::VR256RegClass);
21448       case MVT::v8f64:
21449       case MVT::v16f32:
21450       case MVT::v16i32:
21451       case MVT::v8i64:
21452         return std::make_pair(0U, &X86::VR512RegClass);
21453       }
21454       break;
21455     }
21456   }
21457
21458   // Use the default implementation in TargetLowering to convert the register
21459   // constraint into a member of a register class.
21460   std::pair<unsigned, const TargetRegisterClass*> Res;
21461   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21462
21463   // Not found as a standard register?
21464   if (!Res.second) {
21465     // Map st(0) -> st(7) -> ST0
21466     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21467         tolower(Constraint[1]) == 's' &&
21468         tolower(Constraint[2]) == 't' &&
21469         Constraint[3] == '(' &&
21470         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21471         Constraint[5] == ')' &&
21472         Constraint[6] == '}') {
21473
21474       Res.first = X86::ST0+Constraint[4]-'0';
21475       Res.second = &X86::RFP80RegClass;
21476       return Res;
21477     }
21478
21479     // GCC allows "st(0)" to be called just plain "st".
21480     if (StringRef("{st}").equals_lower(Constraint)) {
21481       Res.first = X86::ST0;
21482       Res.second = &X86::RFP80RegClass;
21483       return Res;
21484     }
21485
21486     // flags -> EFLAGS
21487     if (StringRef("{flags}").equals_lower(Constraint)) {
21488       Res.first = X86::EFLAGS;
21489       Res.second = &X86::CCRRegClass;
21490       return Res;
21491     }
21492
21493     // 'A' means EAX + EDX.
21494     if (Constraint == "A") {
21495       Res.first = X86::EAX;
21496       Res.second = &X86::GR32_ADRegClass;
21497       return Res;
21498     }
21499     return Res;
21500   }
21501
21502   // Otherwise, check to see if this is a register class of the wrong value
21503   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21504   // turn into {ax},{dx}.
21505   if (Res.second->hasType(VT))
21506     return Res;   // Correct type already, nothing to do.
21507
21508   // All of the single-register GCC register classes map their values onto
21509   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21510   // really want an 8-bit or 32-bit register, map to the appropriate register
21511   // class and return the appropriate register.
21512   if (Res.second == &X86::GR16RegClass) {
21513     if (VT == MVT::i8 || VT == MVT::i1) {
21514       unsigned DestReg = 0;
21515       switch (Res.first) {
21516       default: break;
21517       case X86::AX: DestReg = X86::AL; break;
21518       case X86::DX: DestReg = X86::DL; break;
21519       case X86::CX: DestReg = X86::CL; break;
21520       case X86::BX: DestReg = X86::BL; break;
21521       }
21522       if (DestReg) {
21523         Res.first = DestReg;
21524         Res.second = &X86::GR8RegClass;
21525       }
21526     } else if (VT == MVT::i32 || VT == MVT::f32) {
21527       unsigned DestReg = 0;
21528       switch (Res.first) {
21529       default: break;
21530       case X86::AX: DestReg = X86::EAX; break;
21531       case X86::DX: DestReg = X86::EDX; break;
21532       case X86::CX: DestReg = X86::ECX; break;
21533       case X86::BX: DestReg = X86::EBX; break;
21534       case X86::SI: DestReg = X86::ESI; break;
21535       case X86::DI: DestReg = X86::EDI; break;
21536       case X86::BP: DestReg = X86::EBP; break;
21537       case X86::SP: DestReg = X86::ESP; break;
21538       }
21539       if (DestReg) {
21540         Res.first = DestReg;
21541         Res.second = &X86::GR32RegClass;
21542       }
21543     } else if (VT == MVT::i64 || VT == MVT::f64) {
21544       unsigned DestReg = 0;
21545       switch (Res.first) {
21546       default: break;
21547       case X86::AX: DestReg = X86::RAX; break;
21548       case X86::DX: DestReg = X86::RDX; break;
21549       case X86::CX: DestReg = X86::RCX; break;
21550       case X86::BX: DestReg = X86::RBX; break;
21551       case X86::SI: DestReg = X86::RSI; break;
21552       case X86::DI: DestReg = X86::RDI; break;
21553       case X86::BP: DestReg = X86::RBP; break;
21554       case X86::SP: DestReg = X86::RSP; break;
21555       }
21556       if (DestReg) {
21557         Res.first = DestReg;
21558         Res.second = &X86::GR64RegClass;
21559       }
21560     }
21561   } else if (Res.second == &X86::FR32RegClass ||
21562              Res.second == &X86::FR64RegClass ||
21563              Res.second == &X86::VR128RegClass ||
21564              Res.second == &X86::VR256RegClass ||
21565              Res.second == &X86::FR32XRegClass ||
21566              Res.second == &X86::FR64XRegClass ||
21567              Res.second == &X86::VR128XRegClass ||
21568              Res.second == &X86::VR256XRegClass ||
21569              Res.second == &X86::VR512RegClass) {
21570     // Handle references to XMM physical registers that got mapped into the
21571     // wrong class.  This can happen with constraints like {xmm0} where the
21572     // target independent register mapper will just pick the first match it can
21573     // find, ignoring the required type.
21574
21575     if (VT == MVT::f32 || VT == MVT::i32)
21576       Res.second = &X86::FR32RegClass;
21577     else if (VT == MVT::f64 || VT == MVT::i64)
21578       Res.second = &X86::FR64RegClass;
21579     else if (X86::VR128RegClass.hasType(VT))
21580       Res.second = &X86::VR128RegClass;
21581     else if (X86::VR256RegClass.hasType(VT))
21582       Res.second = &X86::VR256RegClass;
21583     else if (X86::VR512RegClass.hasType(VT))
21584       Res.second = &X86::VR512RegClass;
21585   }
21586
21587   return Res;
21588 }
21589
21590 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21591                                             Type *Ty) const {
21592   // Scaling factors are not free at all.
21593   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21594   // will take 2 allocations in the out of order engine instead of 1
21595   // for plain addressing mode, i.e. inst (reg1).
21596   // E.g.,
21597   // vaddps (%rsi,%drx), %ymm0, %ymm1
21598   // Requires two allocations (one for the load, one for the computation)
21599   // whereas:
21600   // vaddps (%rsi), %ymm0, %ymm1
21601   // Requires just 1 allocation, i.e., freeing allocations for other operations
21602   // and having less micro operations to execute.
21603   //
21604   // For some X86 architectures, this is even worse because for instance for
21605   // stores, the complex addressing mode forces the instruction to use the
21606   // "load" ports instead of the dedicated "store" port.
21607   // E.g., on Haswell:
21608   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21609   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21610   if (isLegalAddressingMode(AM, Ty))
21611     // Scale represents reg2 * scale, thus account for 1
21612     // as soon as we use a second register.
21613     return AM.Scale != 0;
21614   return -1;
21615 }
21616
21617 bool X86TargetLowering::isTargetFTOL() const {
21618   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
21619 }