Pass the value type to TLI::getRegisterByName
[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(X86TargetMachine &TM) {
182   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
183   bool is64Bit = Subtarget->is64Bit();
184
185   if (Subtarget->isTargetMacho()) {
186     if (is64Bit)
187       return new X86_64MachoTargetObjectFile();
188     return new TargetLoweringObjectFileMachO();
189   }
190
191   if (Subtarget->isTargetLinux())
192     return new X86LinuxTargetObjectFile();
193   if (Subtarget->isTargetELF())
194     return new TargetLoweringObjectFileELF();
195   if (Subtarget->isTargetKnownWindowsMSVC())
196     return new X86WindowsTargetObjectFile();
197   if (Subtarget->isTargetCOFF())
198     return new TargetLoweringObjectFileCOFF();
199   llvm_unreachable("unknown subtarget type");
200 }
201
202 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
203   : TargetLowering(TM, createTLOF(TM)) {
204   Subtarget = &TM.getSubtarget<X86Subtarget>();
205   X86ScalarSSEf64 = Subtarget->hasSSE2();
206   X86ScalarSSEf32 = Subtarget->hasSSE1();
207   TD = getDataLayout();
208
209   resetOperationActions();
210 }
211
212 void X86TargetLowering::resetOperationActions() {
213   const TargetMachine &TM = getTargetMachine();
214   static bool FirstTimeThrough = true;
215
216   // If none of the target options have changed, then we don't need to reset the
217   // operation actions.
218   if (!FirstTimeThrough && TO == TM.Options) return;
219
220   if (!FirstTimeThrough) {
221     // Reinitialize the actions.
222     initActions();
223     FirstTimeThrough = false;
224   }
225
226   TO = TM.Options;
227
228   // Set up the TargetLowering object.
229   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
230
231   // X86 is weird, it always uses i8 for shift amounts and setcc results.
232   setBooleanContents(ZeroOrOneBooleanContent);
233   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
234   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235
236   // For 64-bit since we have so many registers use the ILP scheduler, for
237   // 32-bit code use the register pressure specific scheduling.
238   // For Atom, always use ILP scheduling.
239   if (Subtarget->isAtom())
240     setSchedulingPreference(Sched::ILP);
241   else if (Subtarget->is64Bit())
242     setSchedulingPreference(Sched::ILP);
243   else
244     setSchedulingPreference(Sched::RegPressure);
245   const X86RegisterInfo *RegInfo =
246     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
247   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
248
249   // Bypass expensive divides on Atom when compiling with O2
250   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
251     addBypassSlowDiv(32, 8);
252     if (Subtarget->is64Bit())
253       addBypassSlowDiv(64, 16);
254   }
255
256   if (Subtarget->isTargetKnownWindowsMSVC()) {
257     // Setup Windows compiler runtime calls.
258     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
259     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
260     setLibcallName(RTLIB::SREM_I64, "_allrem");
261     setLibcallName(RTLIB::UREM_I64, "_aullrem");
262     setLibcallName(RTLIB::MUL_I64, "_allmul");
263     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
266     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
267     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
268
269     // The _ftol2 runtime function has an unusual calling conv, which
270     // is modeled by a special pseudo-instruction.
271     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
273     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
274     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
275   }
276
277   if (Subtarget->isTargetDarwin()) {
278     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
279     setUseUnderscoreSetJmp(false);
280     setUseUnderscoreLongJmp(false);
281   } else if (Subtarget->isTargetWindowsGNU()) {
282     // MS runtime is weird: it exports _setjmp, but longjmp!
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(false);
285   } else {
286     setUseUnderscoreSetJmp(true);
287     setUseUnderscoreLongJmp(true);
288   }
289
290   // Set up the register classes.
291   addRegisterClass(MVT::i8, &X86::GR8RegClass);
292   addRegisterClass(MVT::i16, &X86::GR16RegClass);
293   addRegisterClass(MVT::i32, &X86::GR32RegClass);
294   if (Subtarget->is64Bit())
295     addRegisterClass(MVT::i64, &X86::GR64RegClass);
296
297   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
298
299   // We don't accept any truncstore of integer registers.
300   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
301   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
304   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
305   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
306
307   // SETOEQ and SETUNE require checking two conditions.
308   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
313   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
314
315   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
316   // operation.
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
319   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
320
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
323     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
324   } else if (!TM.Options.UseSoftFloat) {
325     // We have an algorithm for SSE2->double, and we turn this into a
326     // 64-bit FILD followed by conditional FADD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
328     // We have an algorithm for SSE2, and we turn this into a 64-bit
329     // FILD for other targets.
330     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
331   }
332
333   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
334   // this operation.
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
336   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
337
338   if (!TM.Options.UseSoftFloat) {
339     // SSE has no i16 to fp conversion, only i32
340     if (X86ScalarSSEf32) {
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
342       // f32 and f64 cases are Legal, f80 case is not
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     } else {
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
346       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
347     }
348   } else {
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
350     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
351   }
352
353   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
354   // are Legal, f80 is custom lowered.
355   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
356   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
357
358   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
359   // this operation.
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
361   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
362
363   if (X86ScalarSSEf32) {
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
365     // f32 and f64 cases are Legal, f80 case is not
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   } else {
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
369     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
370   }
371
372   // Handle FP_TO_UINT by promoting the destination to a larger signed
373   // conversion.
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
376   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
377
378   if (Subtarget->is64Bit()) {
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
380     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
381   } else if (!TM.Options.UseSoftFloat) {
382     // Since AVX is a superset of SSE3, only check for SSE here.
383     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
384       // Expand FP_TO_UINT into a select.
385       // FIXME: We would like to use a Custom expander here eventually to do
386       // the optimal thing for SSE vs. the default expansion in the legalizer.
387       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
388     else
389       // With SSE3 we can use fisttpll to convert to a signed i64; without
390       // SSE, we're stuck with a fistpll.
391       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
392   }
393
394   if (isTargetFTOL()) {
395     // Use the _ftol2 runtime function, which has a pseudo-instruction
396     // to handle its weird calling convention.
397     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
398   }
399
400   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
401   if (!X86ScalarSSEf64) {
402     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
403     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
404     if (Subtarget->is64Bit()) {
405       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
406       // Without SSE, i64->f64 goes through memory.
407       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
408     }
409   }
410
411   // Scalar integer divide and remainder are lowered to use operations that
412   // produce two results, to match the available instructions. This exposes
413   // the two-result form to trivial CSE, which is able to combine x/y and x%y
414   // into a single instruction.
415   //
416   // Scalar integer multiply-high is also lowered to use two-result
417   // operations, to match the available instructions. However, plain multiply
418   // (low) operations are left as Legal, as there are single-result
419   // instructions for this in x86. Using the two-result multiply instructions
420   // when both high and low results are needed must be arranged by dagcombine.
421   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
422     MVT VT = IntVTs[i];
423     setOperationAction(ISD::MULHS, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::SDIV, VT, Expand);
426     setOperationAction(ISD::UDIV, VT, Expand);
427     setOperationAction(ISD::SREM, VT, Expand);
428     setOperationAction(ISD::UREM, VT, Expand);
429
430     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
431     setOperationAction(ISD::ADDC, VT, Custom);
432     setOperationAction(ISD::ADDE, VT, Custom);
433     setOperationAction(ISD::SUBC, VT, Custom);
434     setOperationAction(ISD::SUBE, VT, Custom);
435   }
436
437   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
438   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
439   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
445   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
447   if (Subtarget->is64Bit())
448     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
450   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
451   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
452   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
454   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
455   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
456   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
457
458   // Promote the i8 variants and force them on up to i32 which has a shorter
459   // encoding.
460   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
461   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
462   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
463   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
464   if (Subtarget->hasBMI()) {
465     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
466     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
467     if (Subtarget->is64Bit())
468       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
469   } else {
470     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
471     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
472     if (Subtarget->is64Bit())
473       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
474   }
475
476   if (Subtarget->hasLZCNT()) {
477     // When promoting the i8 variants, force them to i32 for a shorter
478     // encoding.
479     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
480     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
482     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
483     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
492     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
493     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
494     if (Subtarget->is64Bit()) {
495       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
496       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
497     }
498   }
499
500   if (Subtarget->hasPOPCNT()) {
501     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
502   } else {
503     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
504     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
505     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
506     if (Subtarget->is64Bit())
507       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
508   }
509
510   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
511
512   if (!Subtarget->hasMOVBE())
513     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
514
515   // These should be promoted to a larger select which is supported.
516   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
517   // X86 wants to expand cmov itself.
518   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
519   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
522   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
523   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
525   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
528   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
530   if (Subtarget->is64Bit()) {
531     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
532     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
533   }
534   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
535   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537   // support continuation, user-level threading, and etc.. As a result, no
538   // other SjLj exception interfaces are implemented and please don't build
539   // your own exception handling based on them.
540   // LLVM/Clang supports zero-cost DWARF exception handling.
541   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
542   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
543
544   // Darwin ABI issue.
545   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
546   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
547   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
548   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
549   if (Subtarget->is64Bit())
550     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
551   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
552   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
553   if (Subtarget->is64Bit()) {
554     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
555     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
556     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
557     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
558     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
559   }
560   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
561   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
562   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
563   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
566     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
567     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
568   }
569
570   if (Subtarget->hasSSE1())
571     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
572
573   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
574
575   // Expand certain atomics
576   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
577     MVT VT = IntVTs[i];
578     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
580     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
581   }
582
583   if (!Subtarget->is64Bit()) {
584     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
594     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
595     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
596   }
597
598   if (Subtarget->hasCmpxchg16b()) {
599     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
600   }
601
602   // FIXME - use subtarget debug flags
603   if (!Subtarget->isTargetDarwin() &&
604       !Subtarget->isTargetELF() &&
605       !Subtarget->isTargetCygMing()) {
606     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
607   }
608
609   if (Subtarget->is64Bit()) {
610     setExceptionPointerRegister(X86::RAX);
611     setExceptionSelectorRegister(X86::RDX);
612   } else {
613     setExceptionPointerRegister(X86::EAX);
614     setExceptionSelectorRegister(X86::EDX);
615   }
616   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
617   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
618
619   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
620   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
621
622   setOperationAction(ISD::TRAP, MVT::Other, Legal);
623   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
624
625   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
626   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
627   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
628   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
629     // TargetInfo::X86_64ABIBuiltinVaList
630     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
631     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
632   } else {
633     // TargetInfo::CharPtrBuiltinVaList
634     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
635     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
636   }
637
638   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
639   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
640
641   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642                      MVT::i64 : MVT::i32, Custom);
643
644   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645     // f32 and f64 use SSE.
646     // Set up the FP register classes.
647     addRegisterClass(MVT::f32, &X86::FR32RegClass);
648     addRegisterClass(MVT::f64, &X86::FR64RegClass);
649
650     // Use ANDPD to simulate FABS.
651     setOperationAction(ISD::FABS , MVT::f64, Custom);
652     setOperationAction(ISD::FABS , MVT::f32, Custom);
653
654     // Use XORP to simulate FNEG.
655     setOperationAction(ISD::FNEG , MVT::f64, Custom);
656     setOperationAction(ISD::FNEG , MVT::f32, Custom);
657
658     // Use ANDPD and ORPD to simulate FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661
662     // Lower this to FGETSIGNx86 plus an AND.
663     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665
666     // We don't support sin/cos/fmod
667     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Expand FP immediates into loads from the stack, except for the special
675     // cases we handle.
676     addLegalFPImmediate(APFloat(+0.0)); // xorpd
677     addLegalFPImmediate(APFloat(+0.0f)); // xorps
678   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679     // Use SSE for f32, x87 for f64.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f32, &X86::FR32RegClass);
682     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683
684     // Use ANDPS to simulate FABS.
685     setOperationAction(ISD::FABS , MVT::f32, Custom);
686
687     // Use XORP to simulate FNEG.
688     setOperationAction(ISD::FNEG , MVT::f32, Custom);
689
690     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
691
692     // Use ANDPS and ORPS to simulate FCOPYSIGN.
693     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695
696     // We don't support sin/cos/fmod
697     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
698     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700
701     // Special cases we handle for FP constants.
702     addLegalFPImmediate(APFloat(+0.0f)); // xorps
703     addLegalFPImmediate(APFloat(+0.0)); // FLD0
704     addLegalFPImmediate(APFloat(+1.0)); // FLD1
705     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
711       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712     }
713   } else if (!TM.Options.UseSoftFloat) {
714     // f32 and f64 in x87.
715     // Set up the FP register classes.
716     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718
719     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
720     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723
724     if (!TM.Options.UnsafeFPMath) {
725       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
726       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731     }
732     addLegalFPImmediate(APFloat(+0.0)); // FLD0
733     addLegalFPImmediate(APFloat(+1.0)); // FLD1
734     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740   }
741
742   // We don't support FMA.
743   setOperationAction(ISD::FMA, MVT::f64, Expand);
744   setOperationAction(ISD::FMA, MVT::f32, Expand);
745
746   // Long double always uses X87.
747   if (!TM.Options.UseSoftFloat) {
748     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
750     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751     {
752       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753       addLegalFPImmediate(TmpFlt);  // FLD0
754       TmpFlt.changeSign();
755       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
756
757       bool ignored;
758       APFloat TmpFlt2(+1.0);
759       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760                       &ignored);
761       addLegalFPImmediate(TmpFlt2);  // FLD1
762       TmpFlt2.changeSign();
763       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
764     }
765
766     if (!TM.Options.UnsafeFPMath) {
767       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
768       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
769       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770     }
771
772     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
774     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
776     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777     setOperationAction(ISD::FMA, MVT::f80, Expand);
778   }
779
780   // Always use a library call for pow.
781   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
784
785   setOperationAction(ISD::FLOG, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790
791   // First set operation action for all vector types to either promote
792   // (for widening) or expand (for scalarization). Then we will selectively
793   // turn on ones that can be effectively codegen'd.
794   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796     MVT VT = (MVT::SimpleValueType)i;
797     setOperationAction(ISD::ADD , VT, Expand);
798     setOperationAction(ISD::SUB , VT, Expand);
799     setOperationAction(ISD::FADD, VT, Expand);
800     setOperationAction(ISD::FNEG, VT, Expand);
801     setOperationAction(ISD::FSUB, VT, Expand);
802     setOperationAction(ISD::MUL , VT, Expand);
803     setOperationAction(ISD::FMUL, VT, Expand);
804     setOperationAction(ISD::SDIV, VT, Expand);
805     setOperationAction(ISD::UDIV, VT, Expand);
806     setOperationAction(ISD::FDIV, VT, Expand);
807     setOperationAction(ISD::SREM, VT, Expand);
808     setOperationAction(ISD::UREM, VT, Expand);
809     setOperationAction(ISD::LOAD, VT, Expand);
810     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::FABS, VT, Expand);
816     setOperationAction(ISD::FSIN, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FCOS, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FREM, VT, Expand);
821     setOperationAction(ISD::FMA,  VT, Expand);
822     setOperationAction(ISD::FPOWI, VT, Expand);
823     setOperationAction(ISD::FSQRT, VT, Expand);
824     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825     setOperationAction(ISD::FFLOOR, VT, Expand);
826     setOperationAction(ISD::FCEIL, VT, Expand);
827     setOperationAction(ISD::FTRUNC, VT, Expand);
828     setOperationAction(ISD::FRINT, VT, Expand);
829     setOperationAction(ISD::FNEARBYINT, VT, Expand);
830     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::MULHS, VT, Expand);
832     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
833     setOperationAction(ISD::MULHU, VT, Expand);
834     setOperationAction(ISD::SDIVREM, VT, Expand);
835     setOperationAction(ISD::UDIVREM, VT, Expand);
836     setOperationAction(ISD::FPOW, VT, Expand);
837     setOperationAction(ISD::CTPOP, VT, Expand);
838     setOperationAction(ISD::CTTZ, VT, Expand);
839     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::CTLZ, VT, Expand);
841     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
842     setOperationAction(ISD::SHL, VT, Expand);
843     setOperationAction(ISD::SRA, VT, Expand);
844     setOperationAction(ISD::SRL, VT, Expand);
845     setOperationAction(ISD::ROTL, VT, Expand);
846     setOperationAction(ISD::ROTR, VT, Expand);
847     setOperationAction(ISD::BSWAP, VT, Expand);
848     setOperationAction(ISD::SETCC, VT, Expand);
849     setOperationAction(ISD::FLOG, VT, Expand);
850     setOperationAction(ISD::FLOG2, VT, Expand);
851     setOperationAction(ISD::FLOG10, VT, Expand);
852     setOperationAction(ISD::FEXP, VT, Expand);
853     setOperationAction(ISD::FEXP2, VT, Expand);
854     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
855     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
856     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
857     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
859     setOperationAction(ISD::TRUNCATE, VT, Expand);
860     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
861     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
862     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
863     setOperationAction(ISD::VSELECT, VT, Expand);
864     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
865              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
866       setTruncStoreAction(VT,
867                           (MVT::SimpleValueType)InnerVT, Expand);
868     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
869     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
870     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
871   }
872
873   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
874   // with -msoft-float, disable use of MMX as well.
875   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
876     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
877     // No operations on x86mmx supported, everything uses intrinsics.
878   }
879
880   // MMX-sized vectors (other than x86mmx) are expected to be expanded
881   // into smaller operations.
882   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
883   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
884   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
885   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
886   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
887   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
888   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
889   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
890   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
891   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
892   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
893   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
894   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
895   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
896   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
897   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
900   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
901   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
902   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
904   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
905   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
906   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
909   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
910   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
911
912   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
913     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
914
915     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
918     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
919     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
920     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
921     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
922     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
923     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
924     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
925     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
926     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
927   }
928
929   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
930     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
931
932     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
933     // registers cannot be used even for integer operations.
934     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
935     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
936     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
937     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
938
939     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
940     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
941     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
942     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
943     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
944     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
945     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
946     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
947     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
948     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
949     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
950     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
951     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
952     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
953     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
954     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
956     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
957     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
958     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
959     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
960     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
961
962     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
963     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
964     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
965     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
966
967     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
968     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
970     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
971     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
972
973     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
974     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
975       MVT VT = (MVT::SimpleValueType)i;
976       // Do not attempt to custom lower non-power-of-2 vectors
977       if (!isPowerOf2_32(VT.getVectorNumElements()))
978         continue;
979       // Do not attempt to custom lower non-128-bit vectors
980       if (!VT.is128BitVector())
981         continue;
982       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
983       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
984       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
985     }
986
987     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
988     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
989     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
990     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
993
994     if (Subtarget->is64Bit()) {
995       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
996       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
997     }
998
999     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1000     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001       MVT VT = (MVT::SimpleValueType)i;
1002
1003       // Do not attempt to promote non-128-bit vectors
1004       if (!VT.is128BitVector())
1005         continue;
1006
1007       setOperationAction(ISD::AND,    VT, Promote);
1008       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1009       setOperationAction(ISD::OR,     VT, Promote);
1010       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1011       setOperationAction(ISD::XOR,    VT, Promote);
1012       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1013       setOperationAction(ISD::LOAD,   VT, Promote);
1014       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1015       setOperationAction(ISD::SELECT, VT, Promote);
1016       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1017     }
1018
1019     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1020
1021     // Custom lower v2i64 and v2f64 selects.
1022     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1023     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1024     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1025     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1026
1027     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1028     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1029
1030     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1031     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1032     // As there is no 64-bit GPR available, we need build a special custom
1033     // sequence to convert from v2i32 to v2f32.
1034     if (!Subtarget->is64Bit())
1035       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1036
1037     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1038     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1039
1040     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1041
1042     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1043   }
1044
1045   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1046     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1047     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1048     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1049     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1050     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1051     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1052     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1053     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1054     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1055     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1056
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1062     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1063     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1064     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1065     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1066     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1067
1068     // FIXME: Do we need to handle scalar-to-vector here?
1069     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1070
1071     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1072     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1073     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1074     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1075     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1076
1077     // i8 and i16 vectors are custom , because the source register and source
1078     // source memory operand types are not the same width.  f32 vectors are
1079     // custom since the immediate controlling the insert encodes additional
1080     // information.
1081     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1082     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1083     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1084     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1085
1086     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1087     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1088     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1089     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1090
1091     // FIXME: these should be Legal but thats only for the case where
1092     // the index is constant.  For now custom expand to deal with that.
1093     if (Subtarget->is64Bit()) {
1094       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1095       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1096     }
1097   }
1098
1099   if (Subtarget->hasSSE2()) {
1100     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1101     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1102
1103     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1104     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1105
1106     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1107     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1108
1109     // In the customized shift lowering, the legal cases in AVX2 will be
1110     // recognized.
1111     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1112     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1113
1114     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1115     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1116
1117     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1118   }
1119
1120   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1121     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1122     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1123     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1124     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1125     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1126     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1127
1128     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1130     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1131
1132     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1133     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1134     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1135     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1136     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1137     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1138     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1139     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1140     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1141     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1142     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1143     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1144
1145     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1146     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1147     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1148     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1149     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1150     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1151     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1152     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1153     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1154     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1155     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1156     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1157
1158     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1159     // even though v8i16 is a legal type.
1160     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1161     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1162     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1163
1164     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1165     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1166     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1167
1168     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1169     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1170
1171     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1172
1173     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1174     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1175
1176     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1177     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1178
1179     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1180     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1181
1182     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1183     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1184     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1185     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1186
1187     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1188     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1189     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1190
1191     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1192     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1193     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1194     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1195
1196     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1197     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1198     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1199     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1200     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1201     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1202     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1203     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1204     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1205     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1206     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1207     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1208
1209     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1210       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1211       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1212       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1213       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1214       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1215       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1216     }
1217
1218     if (Subtarget->hasInt256()) {
1219       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1220       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1221       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1222       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1223
1224       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1225       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1226       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1227       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1228
1229       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1230       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1231       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1232       // Don't lower v32i8 because there is no 128-bit byte mul
1233
1234       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1235       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1236       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1237       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1238
1239       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1240     } else {
1241       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1242       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1243       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1244       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1245
1246       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1247       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1248       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1249       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1250
1251       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1252       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1253       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1254       // Don't lower v32i8 because there is no 128-bit byte mul
1255     }
1256
1257     // In the customized shift lowering, the legal cases in AVX2 will be
1258     // recognized.
1259     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1260     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1261
1262     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1263     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1264
1265     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1266
1267     // Custom lower several nodes for 256-bit types.
1268     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1269              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1270       MVT VT = (MVT::SimpleValueType)i;
1271
1272       // Extract subvector is special because the value type
1273       // (result) is 128-bit but the source is 256-bit wide.
1274       if (VT.is128BitVector())
1275         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1276
1277       // Do not attempt to custom lower other non-256-bit vectors
1278       if (!VT.is256BitVector())
1279         continue;
1280
1281       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1282       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1283       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1284       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1285       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1286       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1287       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1288     }
1289
1290     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1291     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1292       MVT VT = (MVT::SimpleValueType)i;
1293
1294       // Do not attempt to promote non-256-bit vectors
1295       if (!VT.is256BitVector())
1296         continue;
1297
1298       setOperationAction(ISD::AND,    VT, Promote);
1299       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1300       setOperationAction(ISD::OR,     VT, Promote);
1301       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1302       setOperationAction(ISD::XOR,    VT, Promote);
1303       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1304       setOperationAction(ISD::LOAD,   VT, Promote);
1305       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1306       setOperationAction(ISD::SELECT, VT, Promote);
1307       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1308     }
1309   }
1310
1311   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1312     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1313     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1314     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1315     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1316
1317     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1318     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1319     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1320
1321     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1322     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1323     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1324     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1325     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1326     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1327     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1329     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1330     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1331     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1332
1333     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1334     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1335     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1336     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1337     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1338     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1339
1340     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1342     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1343     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1344     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1346     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1347     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1348
1349     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1350     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1352     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1353     if (Subtarget->is64Bit()) {
1354       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1355       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1356       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1357       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1358     }
1359     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1360     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1361     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1362     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1363     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1365     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1366     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1367     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1368     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1369
1370     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1371     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1372     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1373     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1374     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1375     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1376     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1377     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1378     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1379     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1380     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1381     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1382     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1383
1384     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1390
1391     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1392     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1393
1394     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1395
1396     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1397     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1399     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1400     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1401     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1402     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1403     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1404     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1405
1406     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1407     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1408
1409     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1410     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1411
1412     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1413
1414     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1415     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1416
1417     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1418     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1419
1420     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1421     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1422
1423     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1424     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1425     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1426     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1427     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1428     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1429
1430     // Custom lower several nodes.
1431     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1432              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1433       MVT VT = (MVT::SimpleValueType)i;
1434
1435       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1436       // Extract subvector is special because the value type
1437       // (result) is 256/128-bit but the source is 512-bit wide.
1438       if (VT.is128BitVector() || VT.is256BitVector())
1439         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1440
1441       if (VT.getVectorElementType() == MVT::i1)
1442         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1443
1444       // Do not attempt to custom lower other non-512-bit vectors
1445       if (!VT.is512BitVector())
1446         continue;
1447
1448       if ( EltSize >= 32) {
1449         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1450         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1451         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1452         setOperationAction(ISD::VSELECT,             VT, Legal);
1453         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1454         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1455         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1456       }
1457     }
1458     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1459       MVT VT = (MVT::SimpleValueType)i;
1460
1461       // Do not attempt to promote non-256-bit vectors
1462       if (!VT.is512BitVector())
1463         continue;
1464
1465       setOperationAction(ISD::SELECT, VT, Promote);
1466       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1467     }
1468   }// has  AVX-512
1469
1470   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1471   // of this type with custom code.
1472   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1473            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1474     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1475                        Custom);
1476   }
1477
1478   // We want to custom lower some of our intrinsics.
1479   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1480   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1481   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1482   if (!Subtarget->is64Bit())
1483     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1484
1485   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1486   // handle type legalization for these operations here.
1487   //
1488   // FIXME: We really should do custom legalization for addition and
1489   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1490   // than generic legalization for 64-bit multiplication-with-overflow, though.
1491   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1492     // Add/Sub/Mul with overflow operations are custom lowered.
1493     MVT VT = IntVTs[i];
1494     setOperationAction(ISD::SADDO, VT, Custom);
1495     setOperationAction(ISD::UADDO, VT, Custom);
1496     setOperationAction(ISD::SSUBO, VT, Custom);
1497     setOperationAction(ISD::USUBO, VT, Custom);
1498     setOperationAction(ISD::SMULO, VT, Custom);
1499     setOperationAction(ISD::UMULO, VT, Custom);
1500   }
1501
1502   // There are no 8-bit 3-address imul/mul instructions
1503   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1504   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1505
1506   if (!Subtarget->is64Bit()) {
1507     // These libcalls are not available in 32-bit.
1508     setLibcallName(RTLIB::SHL_I128, nullptr);
1509     setLibcallName(RTLIB::SRL_I128, nullptr);
1510     setLibcallName(RTLIB::SRA_I128, nullptr);
1511   }
1512
1513   // Combine sin / cos into one node or libcall if possible.
1514   if (Subtarget->hasSinCos()) {
1515     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1516     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1517     if (Subtarget->isTargetDarwin()) {
1518       // For MacOSX, we don't want to the normal expansion of a libcall to
1519       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1520       // traffic.
1521       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1522       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1523     }
1524   }
1525
1526   if (Subtarget->isTargetWin64()) {
1527     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1528     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1529     setOperationAction(ISD::SREM, MVT::i128, Custom);
1530     setOperationAction(ISD::UREM, MVT::i128, Custom);
1531     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1532     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1533   }
1534
1535   // We have target-specific dag combine patterns for the following nodes:
1536   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1537   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1538   setTargetDAGCombine(ISD::VSELECT);
1539   setTargetDAGCombine(ISD::SELECT);
1540   setTargetDAGCombine(ISD::SHL);
1541   setTargetDAGCombine(ISD::SRA);
1542   setTargetDAGCombine(ISD::SRL);
1543   setTargetDAGCombine(ISD::OR);
1544   setTargetDAGCombine(ISD::AND);
1545   setTargetDAGCombine(ISD::ADD);
1546   setTargetDAGCombine(ISD::FADD);
1547   setTargetDAGCombine(ISD::FSUB);
1548   setTargetDAGCombine(ISD::FMA);
1549   setTargetDAGCombine(ISD::SUB);
1550   setTargetDAGCombine(ISD::LOAD);
1551   setTargetDAGCombine(ISD::STORE);
1552   setTargetDAGCombine(ISD::ZERO_EXTEND);
1553   setTargetDAGCombine(ISD::ANY_EXTEND);
1554   setTargetDAGCombine(ISD::SIGN_EXTEND);
1555   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1556   setTargetDAGCombine(ISD::TRUNCATE);
1557   setTargetDAGCombine(ISD::SINT_TO_FP);
1558   setTargetDAGCombine(ISD::SETCC);
1559   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1560   if (Subtarget->is64Bit())
1561     setTargetDAGCombine(ISD::MUL);
1562   setTargetDAGCombine(ISD::XOR);
1563
1564   computeRegisterProperties();
1565
1566   // On Darwin, -Os means optimize for size without hurting performance,
1567   // do not reduce the limit.
1568   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1569   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1570   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1571   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1572   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1573   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1574   setPrefLoopAlignment(4); // 2^4 bytes.
1575
1576   // Predictable cmov don't hurt on atom because it's in-order.
1577   PredictableSelectIsExpensive = !Subtarget->isAtom();
1578
1579   setPrefFunctionAlignment(4); // 2^4 bytes.
1580 }
1581
1582 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1583   if (!VT.isVector())
1584     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1585
1586   if (Subtarget->hasAVX512())
1587     switch(VT.getVectorNumElements()) {
1588     case  8: return MVT::v8i1;
1589     case 16: return MVT::v16i1;
1590   }
1591
1592   return VT.changeVectorElementTypeToInteger();
1593 }
1594
1595 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1596 /// the desired ByVal argument alignment.
1597 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1598   if (MaxAlign == 16)
1599     return;
1600   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1601     if (VTy->getBitWidth() == 128)
1602       MaxAlign = 16;
1603   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1604     unsigned EltAlign = 0;
1605     getMaxByValAlign(ATy->getElementType(), EltAlign);
1606     if (EltAlign > MaxAlign)
1607       MaxAlign = EltAlign;
1608   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1609     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1610       unsigned EltAlign = 0;
1611       getMaxByValAlign(STy->getElementType(i), EltAlign);
1612       if (EltAlign > MaxAlign)
1613         MaxAlign = EltAlign;
1614       if (MaxAlign == 16)
1615         break;
1616     }
1617   }
1618 }
1619
1620 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1621 /// function arguments in the caller parameter area. For X86, aggregates
1622 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1623 /// are at 4-byte boundaries.
1624 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1625   if (Subtarget->is64Bit()) {
1626     // Max of 8 and alignment of type.
1627     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1628     if (TyAlign > 8)
1629       return TyAlign;
1630     return 8;
1631   }
1632
1633   unsigned Align = 4;
1634   if (Subtarget->hasSSE1())
1635     getMaxByValAlign(Ty, Align);
1636   return Align;
1637 }
1638
1639 /// getOptimalMemOpType - Returns the target specific optimal type for load
1640 /// and store operations as a result of memset, memcpy, and memmove
1641 /// lowering. If DstAlign is zero that means it's safe to destination
1642 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1643 /// means there isn't a need to check it against alignment requirement,
1644 /// probably because the source does not need to be loaded. If 'IsMemset' is
1645 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1646 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1647 /// source is constant so it does not need to be loaded.
1648 /// It returns EVT::Other if the type should be determined using generic
1649 /// target-independent logic.
1650 EVT
1651 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1652                                        unsigned DstAlign, unsigned SrcAlign,
1653                                        bool IsMemset, bool ZeroMemset,
1654                                        bool MemcpyStrSrc,
1655                                        MachineFunction &MF) const {
1656   const Function *F = MF.getFunction();
1657   if ((!IsMemset || ZeroMemset) &&
1658       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1659                                        Attribute::NoImplicitFloat)) {
1660     if (Size >= 16 &&
1661         (Subtarget->isUnalignedMemAccessFast() ||
1662          ((DstAlign == 0 || DstAlign >= 16) &&
1663           (SrcAlign == 0 || SrcAlign >= 16)))) {
1664       if (Size >= 32) {
1665         if (Subtarget->hasInt256())
1666           return MVT::v8i32;
1667         if (Subtarget->hasFp256())
1668           return MVT::v8f32;
1669       }
1670       if (Subtarget->hasSSE2())
1671         return MVT::v4i32;
1672       if (Subtarget->hasSSE1())
1673         return MVT::v4f32;
1674     } else if (!MemcpyStrSrc && Size >= 8 &&
1675                !Subtarget->is64Bit() &&
1676                Subtarget->hasSSE2()) {
1677       // Do not use f64 to lower memcpy if source is string constant. It's
1678       // better to use i32 to avoid the loads.
1679       return MVT::f64;
1680     }
1681   }
1682   if (Subtarget->is64Bit() && Size >= 8)
1683     return MVT::i64;
1684   return MVT::i32;
1685 }
1686
1687 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1688   if (VT == MVT::f32)
1689     return X86ScalarSSEf32;
1690   else if (VT == MVT::f64)
1691     return X86ScalarSSEf64;
1692   return true;
1693 }
1694
1695 bool
1696 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1697                                                  unsigned,
1698                                                  bool *Fast) const {
1699   if (Fast)
1700     *Fast = Subtarget->isUnalignedMemAccessFast();
1701   return true;
1702 }
1703
1704 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1705 /// current function.  The returned value is a member of the
1706 /// MachineJumpTableInfo::JTEntryKind enum.
1707 unsigned X86TargetLowering::getJumpTableEncoding() const {
1708   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1709   // symbol.
1710   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1711       Subtarget->isPICStyleGOT())
1712     return MachineJumpTableInfo::EK_Custom32;
1713
1714   // Otherwise, use the normal jump table encoding heuristics.
1715   return TargetLowering::getJumpTableEncoding();
1716 }
1717
1718 const MCExpr *
1719 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1720                                              const MachineBasicBlock *MBB,
1721                                              unsigned uid,MCContext &Ctx) const{
1722   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1723          Subtarget->isPICStyleGOT());
1724   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1725   // entries.
1726   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1727                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1728 }
1729
1730 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1731 /// jumptable.
1732 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1733                                                     SelectionDAG &DAG) const {
1734   if (!Subtarget->is64Bit())
1735     // This doesn't have SDLoc associated with it, but is not really the
1736     // same as a Register.
1737     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1738   return Table;
1739 }
1740
1741 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1742 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1743 /// MCExpr.
1744 const MCExpr *X86TargetLowering::
1745 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1746                              MCContext &Ctx) const {
1747   // X86-64 uses RIP relative addressing based on the jump table label.
1748   if (Subtarget->isPICStyleRIPRel())
1749     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1750
1751   // Otherwise, the reference is relative to the PIC base.
1752   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1753 }
1754
1755 // FIXME: Why this routine is here? Move to RegInfo!
1756 std::pair<const TargetRegisterClass*, uint8_t>
1757 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1758   const TargetRegisterClass *RRC = nullptr;
1759   uint8_t Cost = 1;
1760   switch (VT.SimpleTy) {
1761   default:
1762     return TargetLowering::findRepresentativeClass(VT);
1763   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1764     RRC = Subtarget->is64Bit() ?
1765       (const TargetRegisterClass*)&X86::GR64RegClass :
1766       (const TargetRegisterClass*)&X86::GR32RegClass;
1767     break;
1768   case MVT::x86mmx:
1769     RRC = &X86::VR64RegClass;
1770     break;
1771   case MVT::f32: case MVT::f64:
1772   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1773   case MVT::v4f32: case MVT::v2f64:
1774   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1775   case MVT::v4f64:
1776     RRC = &X86::VR128RegClass;
1777     break;
1778   }
1779   return std::make_pair(RRC, Cost);
1780 }
1781
1782 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1783                                                unsigned &Offset) const {
1784   if (!Subtarget->isTargetLinux())
1785     return false;
1786
1787   if (Subtarget->is64Bit()) {
1788     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1789     Offset = 0x28;
1790     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1791       AddressSpace = 256;
1792     else
1793       AddressSpace = 257;
1794   } else {
1795     // %gs:0x14 on i386
1796     Offset = 0x14;
1797     AddressSpace = 256;
1798   }
1799   return true;
1800 }
1801
1802 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1803                                             unsigned DestAS) const {
1804   assert(SrcAS != DestAS && "Expected different address spaces!");
1805
1806   return SrcAS < 256 && DestAS < 256;
1807 }
1808
1809 //===----------------------------------------------------------------------===//
1810 //               Return Value Calling Convention Implementation
1811 //===----------------------------------------------------------------------===//
1812
1813 #include "X86GenCallingConv.inc"
1814
1815 bool
1816 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1817                                   MachineFunction &MF, bool isVarArg,
1818                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1819                         LLVMContext &Context) const {
1820   SmallVector<CCValAssign, 16> RVLocs;
1821   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1822                  RVLocs, Context);
1823   return CCInfo.CheckReturn(Outs, RetCC_X86);
1824 }
1825
1826 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1827   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1828   return ScratchRegs;
1829 }
1830
1831 SDValue
1832 X86TargetLowering::LowerReturn(SDValue Chain,
1833                                CallingConv::ID CallConv, bool isVarArg,
1834                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1835                                const SmallVectorImpl<SDValue> &OutVals,
1836                                SDLoc dl, SelectionDAG &DAG) const {
1837   MachineFunction &MF = DAG.getMachineFunction();
1838   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1839
1840   SmallVector<CCValAssign, 16> RVLocs;
1841   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1842                  RVLocs, *DAG.getContext());
1843   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1844
1845   SDValue Flag;
1846   SmallVector<SDValue, 6> RetOps;
1847   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1848   // Operand #1 = Bytes To Pop
1849   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1850                    MVT::i16));
1851
1852   // Copy the result values into the output registers.
1853   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1854     CCValAssign &VA = RVLocs[i];
1855     assert(VA.isRegLoc() && "Can only return in registers!");
1856     SDValue ValToCopy = OutVals[i];
1857     EVT ValVT = ValToCopy.getValueType();
1858
1859     // Promote values to the appropriate types
1860     if (VA.getLocInfo() == CCValAssign::SExt)
1861       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1862     else if (VA.getLocInfo() == CCValAssign::ZExt)
1863       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1864     else if (VA.getLocInfo() == CCValAssign::AExt)
1865       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1866     else if (VA.getLocInfo() == CCValAssign::BCvt)
1867       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1868
1869     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1870            "Unexpected FP-extend for return value.");  
1871
1872     // If this is x86-64, and we disabled SSE, we can't return FP values,
1873     // or SSE or MMX vectors.
1874     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1875          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1876           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1877       report_fatal_error("SSE register return with SSE disabled");
1878     }
1879     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1880     // llvm-gcc has never done it right and no one has noticed, so this
1881     // should be OK for now.
1882     if (ValVT == MVT::f64 &&
1883         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1884       report_fatal_error("SSE2 register return with SSE2 disabled");
1885
1886     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1887     // the RET instruction and handled by the FP Stackifier.
1888     if (VA.getLocReg() == X86::ST0 ||
1889         VA.getLocReg() == X86::ST1) {
1890       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1891       // change the value to the FP stack register class.
1892       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1893         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1894       RetOps.push_back(ValToCopy);
1895       // Don't emit a copytoreg.
1896       continue;
1897     }
1898
1899     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1900     // which is returned in RAX / RDX.
1901     if (Subtarget->is64Bit()) {
1902       if (ValVT == MVT::x86mmx) {
1903         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1904           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1905           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1906                                   ValToCopy);
1907           // If we don't have SSE2 available, convert to v4f32 so the generated
1908           // register is legal.
1909           if (!Subtarget->hasSSE2())
1910             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1911         }
1912       }
1913     }
1914
1915     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1916     Flag = Chain.getValue(1);
1917     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1918   }
1919
1920   // The x86-64 ABIs require that for returning structs by value we copy
1921   // the sret argument into %rax/%eax (depending on ABI) for the return.
1922   // Win32 requires us to put the sret argument to %eax as well.
1923   // We saved the argument into a virtual register in the entry block,
1924   // so now we copy the value out and into %rax/%eax.
1925   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1926       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1927     MachineFunction &MF = DAG.getMachineFunction();
1928     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1929     unsigned Reg = FuncInfo->getSRetReturnReg();
1930     assert(Reg &&
1931            "SRetReturnReg should have been set in LowerFormalArguments().");
1932     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1933
1934     unsigned RetValReg
1935         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1936           X86::RAX : X86::EAX;
1937     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1938     Flag = Chain.getValue(1);
1939
1940     // RAX/EAX now acts like a return value.
1941     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1942   }
1943
1944   RetOps[0] = Chain;  // Update chain.
1945
1946   // Add the flag if we have it.
1947   if (Flag.getNode())
1948     RetOps.push_back(Flag);
1949
1950   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1951 }
1952
1953 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1954   if (N->getNumValues() != 1)
1955     return false;
1956   if (!N->hasNUsesOfValue(1, 0))
1957     return false;
1958
1959   SDValue TCChain = Chain;
1960   SDNode *Copy = *N->use_begin();
1961   if (Copy->getOpcode() == ISD::CopyToReg) {
1962     // If the copy has a glue operand, we conservatively assume it isn't safe to
1963     // perform a tail call.
1964     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1965       return false;
1966     TCChain = Copy->getOperand(0);
1967   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1968     return false;
1969
1970   bool HasRet = false;
1971   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1972        UI != UE; ++UI) {
1973     if (UI->getOpcode() != X86ISD::RET_FLAG)
1974       return false;
1975     HasRet = true;
1976   }
1977
1978   if (!HasRet)
1979     return false;
1980
1981   Chain = TCChain;
1982   return true;
1983 }
1984
1985 MVT
1986 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1987                                             ISD::NodeType ExtendKind) const {
1988   MVT ReturnMVT;
1989   // TODO: Is this also valid on 32-bit?
1990   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1991     ReturnMVT = MVT::i8;
1992   else
1993     ReturnMVT = MVT::i32;
1994
1995   MVT MinVT = getRegisterType(ReturnMVT);
1996   return VT.bitsLT(MinVT) ? MinVT : VT;
1997 }
1998
1999 /// LowerCallResult - Lower the result values of a call into the
2000 /// appropriate copies out of appropriate physical registers.
2001 ///
2002 SDValue
2003 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2004                                    CallingConv::ID CallConv, bool isVarArg,
2005                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2006                                    SDLoc dl, SelectionDAG &DAG,
2007                                    SmallVectorImpl<SDValue> &InVals) const {
2008
2009   // Assign locations to each value returned by this call.
2010   SmallVector<CCValAssign, 16> RVLocs;
2011   bool Is64Bit = Subtarget->is64Bit();
2012   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2013                  getTargetMachine(), RVLocs, *DAG.getContext());
2014   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2015
2016   // Copy all of the result registers out of their specified physreg.
2017   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2018     CCValAssign &VA = RVLocs[i];
2019     EVT CopyVT = VA.getValVT();
2020
2021     // If this is x86-64, and we disabled SSE, we can't return FP values
2022     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2023         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2024       report_fatal_error("SSE register return with SSE disabled");
2025     }
2026
2027     SDValue Val;
2028
2029     // If this is a call to a function that returns an fp value on the floating
2030     // point stack, we must guarantee the value is popped from the stack, so
2031     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2032     // if the return value is not used. We use the FpPOP_RETVAL instruction
2033     // instead.
2034     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2035       // If we prefer to use the value in xmm registers, copy it out as f80 and
2036       // use a truncate to move it from fp stack reg to xmm reg.
2037       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2038       SDValue Ops[] = { Chain, InFlag };
2039       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2040                                          MVT::Other, MVT::Glue, Ops), 1);
2041       Val = Chain.getValue(0);
2042
2043       // Round the f80 to the right size, which also moves it to the appropriate
2044       // xmm register.
2045       if (CopyVT != VA.getValVT())
2046         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2047                           // This truncation won't change the value.
2048                           DAG.getIntPtrConstant(1));
2049     } else {
2050       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2051                                  CopyVT, InFlag).getValue(1);
2052       Val = Chain.getValue(0);
2053     }
2054     InFlag = Chain.getValue(2);
2055     InVals.push_back(Val);
2056   }
2057
2058   return Chain;
2059 }
2060
2061 //===----------------------------------------------------------------------===//
2062 //                C & StdCall & Fast Calling Convention implementation
2063 //===----------------------------------------------------------------------===//
2064 //  StdCall calling convention seems to be standard for many Windows' API
2065 //  routines and around. It differs from C calling convention just a little:
2066 //  callee should clean up the stack, not caller. Symbols should be also
2067 //  decorated in some fancy way :) It doesn't support any vector arguments.
2068 //  For info on fast calling convention see Fast Calling Convention (tail call)
2069 //  implementation LowerX86_32FastCCCallTo.
2070
2071 /// CallIsStructReturn - Determines whether a call uses struct return
2072 /// semantics.
2073 enum StructReturnType {
2074   NotStructReturn,
2075   RegStructReturn,
2076   StackStructReturn
2077 };
2078 static StructReturnType
2079 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2080   if (Outs.empty())
2081     return NotStructReturn;
2082
2083   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2084   if (!Flags.isSRet())
2085     return NotStructReturn;
2086   if (Flags.isInReg())
2087     return RegStructReturn;
2088   return StackStructReturn;
2089 }
2090
2091 /// ArgsAreStructReturn - Determines whether a function uses struct
2092 /// return semantics.
2093 static StructReturnType
2094 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2095   if (Ins.empty())
2096     return NotStructReturn;
2097
2098   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2099   if (!Flags.isSRet())
2100     return NotStructReturn;
2101   if (Flags.isInReg())
2102     return RegStructReturn;
2103   return StackStructReturn;
2104 }
2105
2106 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2107 /// by "Src" to address "Dst" with size and alignment information specified by
2108 /// the specific parameter attribute. The copy will be passed as a byval
2109 /// function parameter.
2110 static SDValue
2111 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2112                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2113                           SDLoc dl) {
2114   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2115
2116   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2117                        /*isVolatile*/false, /*AlwaysInline=*/true,
2118                        MachinePointerInfo(), MachinePointerInfo());
2119 }
2120
2121 /// IsTailCallConvention - Return true if the calling convention is one that
2122 /// supports tail call optimization.
2123 static bool IsTailCallConvention(CallingConv::ID CC) {
2124   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2125           CC == CallingConv::HiPE);
2126 }
2127
2128 /// \brief Return true if the calling convention is a C calling convention.
2129 static bool IsCCallConvention(CallingConv::ID CC) {
2130   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2131           CC == CallingConv::X86_64_SysV);
2132 }
2133
2134 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2135   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2136     return false;
2137
2138   CallSite CS(CI);
2139   CallingConv::ID CalleeCC = CS.getCallingConv();
2140   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2141     return false;
2142
2143   return true;
2144 }
2145
2146 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2147 /// a tailcall target by changing its ABI.
2148 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2149                                    bool GuaranteedTailCallOpt) {
2150   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2151 }
2152
2153 SDValue
2154 X86TargetLowering::LowerMemArgument(SDValue Chain,
2155                                     CallingConv::ID CallConv,
2156                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2157                                     SDLoc dl, SelectionDAG &DAG,
2158                                     const CCValAssign &VA,
2159                                     MachineFrameInfo *MFI,
2160                                     unsigned i) const {
2161   // Create the nodes corresponding to a load from this parameter slot.
2162   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2163   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2164                               getTargetMachine().Options.GuaranteedTailCallOpt);
2165   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2166   EVT ValVT;
2167
2168   // If value is passed by pointer we have address passed instead of the value
2169   // itself.
2170   if (VA.getLocInfo() == CCValAssign::Indirect)
2171     ValVT = VA.getLocVT();
2172   else
2173     ValVT = VA.getValVT();
2174
2175   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2176   // changed with more analysis.
2177   // In case of tail call optimization mark all arguments mutable. Since they
2178   // could be overwritten by lowering of arguments in case of a tail call.
2179   if (Flags.isByVal()) {
2180     unsigned Bytes = Flags.getByValSize();
2181     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2182     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2183     return DAG.getFrameIndex(FI, getPointerTy());
2184   } else {
2185     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2186                                     VA.getLocMemOffset(), isImmutable);
2187     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2188     return DAG.getLoad(ValVT, dl, Chain, FIN,
2189                        MachinePointerInfo::getFixedStack(FI),
2190                        false, false, false, 0);
2191   }
2192 }
2193
2194 SDValue
2195 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2196                                         CallingConv::ID CallConv,
2197                                         bool isVarArg,
2198                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2199                                         SDLoc dl,
2200                                         SelectionDAG &DAG,
2201                                         SmallVectorImpl<SDValue> &InVals)
2202                                           const {
2203   MachineFunction &MF = DAG.getMachineFunction();
2204   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2205
2206   const Function* Fn = MF.getFunction();
2207   if (Fn->hasExternalLinkage() &&
2208       Subtarget->isTargetCygMing() &&
2209       Fn->getName() == "main")
2210     FuncInfo->setForceFramePointer(true);
2211
2212   MachineFrameInfo *MFI = MF.getFrameInfo();
2213   bool Is64Bit = Subtarget->is64Bit();
2214   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2215
2216   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2217          "Var args not supported with calling convention fastcc, ghc or hipe");
2218
2219   // Assign locations to all of the incoming arguments.
2220   SmallVector<CCValAssign, 16> ArgLocs;
2221   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2222                  ArgLocs, *DAG.getContext());
2223
2224   // Allocate shadow area for Win64
2225   if (IsWin64)
2226     CCInfo.AllocateStack(32, 8);
2227
2228   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2229
2230   unsigned LastVal = ~0U;
2231   SDValue ArgValue;
2232   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2233     CCValAssign &VA = ArgLocs[i];
2234     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2235     // places.
2236     assert(VA.getValNo() != LastVal &&
2237            "Don't support value assigned to multiple locs yet");
2238     (void)LastVal;
2239     LastVal = VA.getValNo();
2240
2241     if (VA.isRegLoc()) {
2242       EVT RegVT = VA.getLocVT();
2243       const TargetRegisterClass *RC;
2244       if (RegVT == MVT::i32)
2245         RC = &X86::GR32RegClass;
2246       else if (Is64Bit && RegVT == MVT::i64)
2247         RC = &X86::GR64RegClass;
2248       else if (RegVT == MVT::f32)
2249         RC = &X86::FR32RegClass;
2250       else if (RegVT == MVT::f64)
2251         RC = &X86::FR64RegClass;
2252       else if (RegVT.is512BitVector())
2253         RC = &X86::VR512RegClass;
2254       else if (RegVT.is256BitVector())
2255         RC = &X86::VR256RegClass;
2256       else if (RegVT.is128BitVector())
2257         RC = &X86::VR128RegClass;
2258       else if (RegVT == MVT::x86mmx)
2259         RC = &X86::VR64RegClass;
2260       else if (RegVT == MVT::i1)
2261         RC = &X86::VK1RegClass;
2262       else if (RegVT == MVT::v8i1)
2263         RC = &X86::VK8RegClass;
2264       else if (RegVT == MVT::v16i1)
2265         RC = &X86::VK16RegClass;
2266       else
2267         llvm_unreachable("Unknown argument type!");
2268
2269       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2270       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2271
2272       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2273       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2274       // right size.
2275       if (VA.getLocInfo() == CCValAssign::SExt)
2276         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2277                                DAG.getValueType(VA.getValVT()));
2278       else if (VA.getLocInfo() == CCValAssign::ZExt)
2279         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2280                                DAG.getValueType(VA.getValVT()));
2281       else if (VA.getLocInfo() == CCValAssign::BCvt)
2282         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2283
2284       if (VA.isExtInLoc()) {
2285         // Handle MMX values passed in XMM regs.
2286         if (RegVT.isVector())
2287           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2288         else
2289           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2290       }
2291     } else {
2292       assert(VA.isMemLoc());
2293       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2294     }
2295
2296     // If value is passed via pointer - do a load.
2297     if (VA.getLocInfo() == CCValAssign::Indirect)
2298       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2299                              MachinePointerInfo(), false, false, false, 0);
2300
2301     InVals.push_back(ArgValue);
2302
2303     // The x86-64 ABIs require that for returning structs by value we copy
2304     // the sret argument into %rax/%eax (depending on ABI) for the return.
2305     // Win32 requires us to put the sret argument to %eax as well.
2306     // Save the argument into a virtual register so that we can access it
2307     // from the return points.
2308     if (Ins[i].Flags.isSRet() &&
2309         (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2310       unsigned Reg = FuncInfo->getSRetReturnReg();
2311       if (!Reg) {
2312         MVT PtrTy = getPointerTy();
2313         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2314         FuncInfo->setSRetReturnReg(Reg);
2315       }
2316       SDValue Copy =
2317           DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals.back());
2318       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2319     }
2320   }
2321
2322   unsigned StackSize = CCInfo.getNextStackOffset();
2323   // Align stack specially for tail calls.
2324   if (FuncIsMadeTailCallSafe(CallConv,
2325                              MF.getTarget().Options.GuaranteedTailCallOpt))
2326     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2327
2328   // If the function takes variable number of arguments, make a frame index for
2329   // the start of the first vararg value... for expansion of llvm.va_start.
2330   if (isVarArg) {
2331     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2332                     CallConv != CallingConv::X86_ThisCall)) {
2333       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2334     }
2335     if (Is64Bit) {
2336       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2337
2338       // FIXME: We should really autogenerate these arrays
2339       static const MCPhysReg GPR64ArgRegsWin64[] = {
2340         X86::RCX, X86::RDX, X86::R8,  X86::R9
2341       };
2342       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2343         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2344       };
2345       static const MCPhysReg XMMArgRegs64Bit[] = {
2346         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2347         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2348       };
2349       const MCPhysReg *GPR64ArgRegs;
2350       unsigned NumXMMRegs = 0;
2351
2352       if (IsWin64) {
2353         // The XMM registers which might contain var arg parameters are shadowed
2354         // in their paired GPR.  So we only need to save the GPR to their home
2355         // slots.
2356         TotalNumIntRegs = 4;
2357         GPR64ArgRegs = GPR64ArgRegsWin64;
2358       } else {
2359         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2360         GPR64ArgRegs = GPR64ArgRegs64Bit;
2361
2362         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2363                                                 TotalNumXMMRegs);
2364       }
2365       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2366                                                        TotalNumIntRegs);
2367
2368       bool NoImplicitFloatOps = Fn->getAttributes().
2369         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2370       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2371              "SSE register cannot be used when SSE is disabled!");
2372       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2373                NoImplicitFloatOps) &&
2374              "SSE register cannot be used when SSE is disabled!");
2375       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2376           !Subtarget->hasSSE1())
2377         // Kernel mode asks for SSE to be disabled, so don't push them
2378         // on the stack.
2379         TotalNumXMMRegs = 0;
2380
2381       if (IsWin64) {
2382         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2383         // Get to the caller-allocated home save location.  Add 8 to account
2384         // for the return address.
2385         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2386         FuncInfo->setRegSaveFrameIndex(
2387           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2388         // Fixup to set vararg frame on shadow area (4 x i64).
2389         if (NumIntRegs < 4)
2390           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2391       } else {
2392         // For X86-64, if there are vararg parameters that are passed via
2393         // registers, then we must store them to their spots on the stack so
2394         // they may be loaded by deferencing the result of va_next.
2395         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2396         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2397         FuncInfo->setRegSaveFrameIndex(
2398           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2399                                false));
2400       }
2401
2402       // Store the integer parameter registers.
2403       SmallVector<SDValue, 8> MemOps;
2404       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2405                                         getPointerTy());
2406       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2407       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2408         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2409                                   DAG.getIntPtrConstant(Offset));
2410         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2411                                      &X86::GR64RegClass);
2412         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2413         SDValue Store =
2414           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2415                        MachinePointerInfo::getFixedStack(
2416                          FuncInfo->getRegSaveFrameIndex(), Offset),
2417                        false, false, 0);
2418         MemOps.push_back(Store);
2419         Offset += 8;
2420       }
2421
2422       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2423         // Now store the XMM (fp + vector) parameter registers.
2424         SmallVector<SDValue, 11> SaveXMMOps;
2425         SaveXMMOps.push_back(Chain);
2426
2427         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2428         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2429         SaveXMMOps.push_back(ALVal);
2430
2431         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2432                                FuncInfo->getRegSaveFrameIndex()));
2433         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2434                                FuncInfo->getVarArgsFPOffset()));
2435
2436         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2437           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2438                                        &X86::VR128RegClass);
2439           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2440           SaveXMMOps.push_back(Val);
2441         }
2442         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2443                                      MVT::Other, SaveXMMOps));
2444       }
2445
2446       if (!MemOps.empty())
2447         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2448     }
2449   }
2450
2451   // Some CCs need callee pop.
2452   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2453                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2454     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2455   } else {
2456     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2457     // If this is an sret function, the return should pop the hidden pointer.
2458     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2459         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2460         argsAreStructReturn(Ins) == StackStructReturn)
2461       FuncInfo->setBytesToPopOnReturn(4);
2462   }
2463
2464   if (!Is64Bit) {
2465     // RegSaveFrameIndex is X86-64 only.
2466     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2467     if (CallConv == CallingConv::X86_FastCall ||
2468         CallConv == CallingConv::X86_ThisCall)
2469       // fastcc functions can't have varargs.
2470       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2471   }
2472
2473   FuncInfo->setArgumentStackSize(StackSize);
2474
2475   return Chain;
2476 }
2477
2478 SDValue
2479 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2480                                     SDValue StackPtr, SDValue Arg,
2481                                     SDLoc dl, SelectionDAG &DAG,
2482                                     const CCValAssign &VA,
2483                                     ISD::ArgFlagsTy Flags) const {
2484   unsigned LocMemOffset = VA.getLocMemOffset();
2485   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2486   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2487   if (Flags.isByVal())
2488     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2489
2490   return DAG.getStore(Chain, dl, Arg, PtrOff,
2491                       MachinePointerInfo::getStack(LocMemOffset),
2492                       false, false, 0);
2493 }
2494
2495 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2496 /// optimization is performed and it is required.
2497 SDValue
2498 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2499                                            SDValue &OutRetAddr, SDValue Chain,
2500                                            bool IsTailCall, bool Is64Bit,
2501                                            int FPDiff, SDLoc dl) const {
2502   // Adjust the Return address stack slot.
2503   EVT VT = getPointerTy();
2504   OutRetAddr = getReturnAddressFrameIndex(DAG);
2505
2506   // Load the "old" Return address.
2507   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2508                            false, false, false, 0);
2509   return SDValue(OutRetAddr.getNode(), 1);
2510 }
2511
2512 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2513 /// optimization is performed and it is required (FPDiff!=0).
2514 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2515                                         SDValue Chain, SDValue RetAddrFrIdx,
2516                                         EVT PtrVT, unsigned SlotSize,
2517                                         int FPDiff, SDLoc dl) {
2518   // Store the return address to the appropriate stack slot.
2519   if (!FPDiff) return Chain;
2520   // Calculate the new stack slot for the return address.
2521   int NewReturnAddrFI =
2522     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2523                                          false);
2524   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2525   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2526                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2527                        false, false, 0);
2528   return Chain;
2529 }
2530
2531 SDValue
2532 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2533                              SmallVectorImpl<SDValue> &InVals) const {
2534   SelectionDAG &DAG                     = CLI.DAG;
2535   SDLoc &dl                             = CLI.DL;
2536   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2537   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2538   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2539   SDValue Chain                         = CLI.Chain;
2540   SDValue Callee                        = CLI.Callee;
2541   CallingConv::ID CallConv              = CLI.CallConv;
2542   bool &isTailCall                      = CLI.IsTailCall;
2543   bool isVarArg                         = CLI.IsVarArg;
2544
2545   MachineFunction &MF = DAG.getMachineFunction();
2546   bool Is64Bit        = Subtarget->is64Bit();
2547   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2548   StructReturnType SR = callIsStructReturn(Outs);
2549   bool IsSibcall      = false;
2550
2551   if (MF.getTarget().Options.DisableTailCalls)
2552     isTailCall = false;
2553
2554   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2555   if (IsMustTail) {
2556     // Force this to be a tail call.  The verifier rules are enough to ensure
2557     // that we can lower this successfully without moving the return address
2558     // around.
2559     isTailCall = true;
2560   } else if (isTailCall) {
2561     // Check if it's really possible to do a tail call.
2562     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2563                     isVarArg, SR != NotStructReturn,
2564                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2565                     Outs, OutVals, Ins, DAG);
2566
2567     // Sibcalls are automatically detected tailcalls which do not require
2568     // ABI changes.
2569     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2570       IsSibcall = true;
2571
2572     if (isTailCall)
2573       ++NumTailCalls;
2574   }
2575
2576   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2577          "Var args not supported with calling convention fastcc, ghc or hipe");
2578
2579   // Analyze operands of the call, assigning locations to each operand.
2580   SmallVector<CCValAssign, 16> ArgLocs;
2581   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2582                  ArgLocs, *DAG.getContext());
2583
2584   // Allocate shadow area for Win64
2585   if (IsWin64)
2586     CCInfo.AllocateStack(32, 8);
2587
2588   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2589
2590   // Get a count of how many bytes are to be pushed on the stack.
2591   unsigned NumBytes = CCInfo.getNextStackOffset();
2592   if (IsSibcall)
2593     // This is a sibcall. The memory operands are available in caller's
2594     // own caller's stack.
2595     NumBytes = 0;
2596   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2597            IsTailCallConvention(CallConv))
2598     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2599
2600   int FPDiff = 0;
2601   if (isTailCall && !IsSibcall && !IsMustTail) {
2602     // Lower arguments at fp - stackoffset + fpdiff.
2603     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2604     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2605
2606     FPDiff = NumBytesCallerPushed - NumBytes;
2607
2608     // Set the delta of movement of the returnaddr stackslot.
2609     // But only set if delta is greater than previous delta.
2610     if (FPDiff < X86Info->getTCReturnAddrDelta())
2611       X86Info->setTCReturnAddrDelta(FPDiff);
2612   }
2613
2614   unsigned NumBytesToPush = NumBytes;
2615   unsigned NumBytesToPop = NumBytes;
2616
2617   // If we have an inalloca argument, all stack space has already been allocated
2618   // for us and be right at the top of the stack.  We don't support multiple
2619   // arguments passed in memory when using inalloca.
2620   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2621     NumBytesToPush = 0;
2622     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2623            "an inalloca argument must be the only memory argument");
2624   }
2625
2626   if (!IsSibcall)
2627     Chain = DAG.getCALLSEQ_START(
2628         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2629
2630   SDValue RetAddrFrIdx;
2631   // Load return address for tail calls.
2632   if (isTailCall && FPDiff)
2633     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2634                                     Is64Bit, FPDiff, dl);
2635
2636   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2637   SmallVector<SDValue, 8> MemOpChains;
2638   SDValue StackPtr;
2639
2640   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2641   // of tail call optimization arguments are handle later.
2642   const X86RegisterInfo *RegInfo =
2643     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2644   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2645     // Skip inalloca arguments, they have already been written.
2646     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2647     if (Flags.isInAlloca())
2648       continue;
2649
2650     CCValAssign &VA = ArgLocs[i];
2651     EVT RegVT = VA.getLocVT();
2652     SDValue Arg = OutVals[i];
2653     bool isByVal = Flags.isByVal();
2654
2655     // Promote the value if needed.
2656     switch (VA.getLocInfo()) {
2657     default: llvm_unreachable("Unknown loc info!");
2658     case CCValAssign::Full: break;
2659     case CCValAssign::SExt:
2660       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2661       break;
2662     case CCValAssign::ZExt:
2663       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2664       break;
2665     case CCValAssign::AExt:
2666       if (RegVT.is128BitVector()) {
2667         // Special case: passing MMX values in XMM registers.
2668         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2669         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2670         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2671       } else
2672         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2673       break;
2674     case CCValAssign::BCvt:
2675       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2676       break;
2677     case CCValAssign::Indirect: {
2678       // Store the argument.
2679       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2680       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2681       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2682                            MachinePointerInfo::getFixedStack(FI),
2683                            false, false, 0);
2684       Arg = SpillSlot;
2685       break;
2686     }
2687     }
2688
2689     if (VA.isRegLoc()) {
2690       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2691       if (isVarArg && IsWin64) {
2692         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2693         // shadow reg if callee is a varargs function.
2694         unsigned ShadowReg = 0;
2695         switch (VA.getLocReg()) {
2696         case X86::XMM0: ShadowReg = X86::RCX; break;
2697         case X86::XMM1: ShadowReg = X86::RDX; break;
2698         case X86::XMM2: ShadowReg = X86::R8; break;
2699         case X86::XMM3: ShadowReg = X86::R9; break;
2700         }
2701         if (ShadowReg)
2702           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2703       }
2704     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2705       assert(VA.isMemLoc());
2706       if (!StackPtr.getNode())
2707         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2708                                       getPointerTy());
2709       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2710                                              dl, DAG, VA, Flags));
2711     }
2712   }
2713
2714   if (!MemOpChains.empty())
2715     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2716
2717   if (Subtarget->isPICStyleGOT()) {
2718     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2719     // GOT pointer.
2720     if (!isTailCall) {
2721       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2722                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2723     } else {
2724       // If we are tail calling and generating PIC/GOT style code load the
2725       // address of the callee into ECX. The value in ecx is used as target of
2726       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2727       // for tail calls on PIC/GOT architectures. Normally we would just put the
2728       // address of GOT into ebx and then call target@PLT. But for tail calls
2729       // ebx would be restored (since ebx is callee saved) before jumping to the
2730       // target@PLT.
2731
2732       // Note: The actual moving to ECX is done further down.
2733       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2734       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2735           !G->getGlobal()->hasProtectedVisibility())
2736         Callee = LowerGlobalAddress(Callee, DAG);
2737       else if (isa<ExternalSymbolSDNode>(Callee))
2738         Callee = LowerExternalSymbol(Callee, DAG);
2739     }
2740   }
2741
2742   if (Is64Bit && isVarArg && !IsWin64) {
2743     // From AMD64 ABI document:
2744     // For calls that may call functions that use varargs or stdargs
2745     // (prototype-less calls or calls to functions containing ellipsis (...) in
2746     // the declaration) %al is used as hidden argument to specify the number
2747     // of SSE registers used. The contents of %al do not need to match exactly
2748     // the number of registers, but must be an ubound on the number of SSE
2749     // registers used and is in the range 0 - 8 inclusive.
2750
2751     // Count the number of XMM registers allocated.
2752     static const MCPhysReg XMMArgRegs[] = {
2753       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2754       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2755     };
2756     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2757     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2758            && "SSE registers cannot be used when SSE is disabled");
2759
2760     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2761                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2762   }
2763
2764   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2765   // don't need this because the eligibility check rejects calls that require
2766   // shuffling arguments passed in memory.
2767   if (!IsSibcall && isTailCall) {
2768     // Force all the incoming stack arguments to be loaded from the stack
2769     // before any new outgoing arguments are stored to the stack, because the
2770     // outgoing stack slots may alias the incoming argument stack slots, and
2771     // the alias isn't otherwise explicit. This is slightly more conservative
2772     // than necessary, because it means that each store effectively depends
2773     // on every argument instead of just those arguments it would clobber.
2774     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2775
2776     SmallVector<SDValue, 8> MemOpChains2;
2777     SDValue FIN;
2778     int FI = 0;
2779     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2780       CCValAssign &VA = ArgLocs[i];
2781       if (VA.isRegLoc())
2782         continue;
2783       assert(VA.isMemLoc());
2784       SDValue Arg = OutVals[i];
2785       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2786       // Skip inalloca arguments.  They don't require any work.
2787       if (Flags.isInAlloca())
2788         continue;
2789       // Create frame index.
2790       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2791       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2792       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2793       FIN = DAG.getFrameIndex(FI, getPointerTy());
2794
2795       if (Flags.isByVal()) {
2796         // Copy relative to framepointer.
2797         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2798         if (!StackPtr.getNode())
2799           StackPtr = DAG.getCopyFromReg(Chain, dl,
2800                                         RegInfo->getStackRegister(),
2801                                         getPointerTy());
2802         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2803
2804         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2805                                                          ArgChain,
2806                                                          Flags, DAG, dl));
2807       } else {
2808         // Store relative to framepointer.
2809         MemOpChains2.push_back(
2810           DAG.getStore(ArgChain, dl, Arg, FIN,
2811                        MachinePointerInfo::getFixedStack(FI),
2812                        false, false, 0));
2813       }
2814     }
2815
2816     if (!MemOpChains2.empty())
2817       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2818
2819     // Store the return address to the appropriate stack slot.
2820     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2821                                      getPointerTy(), RegInfo->getSlotSize(),
2822                                      FPDiff, dl);
2823   }
2824
2825   // Build a sequence of copy-to-reg nodes chained together with token chain
2826   // and flag operands which copy the outgoing args into registers.
2827   SDValue InFlag;
2828   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2829     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2830                              RegsToPass[i].second, InFlag);
2831     InFlag = Chain.getValue(1);
2832   }
2833
2834   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2835     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2836     // In the 64-bit large code model, we have to make all calls
2837     // through a register, since the call instruction's 32-bit
2838     // pc-relative offset may not be large enough to hold the whole
2839     // address.
2840   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2841     // If the callee is a GlobalAddress node (quite common, every direct call
2842     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2843     // it.
2844
2845     // We should use extra load for direct calls to dllimported functions in
2846     // non-JIT mode.
2847     const GlobalValue *GV = G->getGlobal();
2848     if (!GV->hasDLLImportStorageClass()) {
2849       unsigned char OpFlags = 0;
2850       bool ExtraLoad = false;
2851       unsigned WrapperKind = ISD::DELETED_NODE;
2852
2853       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2854       // external symbols most go through the PLT in PIC mode.  If the symbol
2855       // has hidden or protected visibility, or if it is static or local, then
2856       // we don't need to use the PLT - we can directly call it.
2857       if (Subtarget->isTargetELF() &&
2858           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2859           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2860         OpFlags = X86II::MO_PLT;
2861       } else if (Subtarget->isPICStyleStubAny() &&
2862                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2863                  (!Subtarget->getTargetTriple().isMacOSX() ||
2864                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2865         // PC-relative references to external symbols should go through $stub,
2866         // unless we're building with the leopard linker or later, which
2867         // automatically synthesizes these stubs.
2868         OpFlags = X86II::MO_DARWIN_STUB;
2869       } else if (Subtarget->isPICStyleRIPRel() &&
2870                  isa<Function>(GV) &&
2871                  cast<Function>(GV)->getAttributes().
2872                    hasAttribute(AttributeSet::FunctionIndex,
2873                                 Attribute::NonLazyBind)) {
2874         // If the function is marked as non-lazy, generate an indirect call
2875         // which loads from the GOT directly. This avoids runtime overhead
2876         // at the cost of eager binding (and one extra byte of encoding).
2877         OpFlags = X86II::MO_GOTPCREL;
2878         WrapperKind = X86ISD::WrapperRIP;
2879         ExtraLoad = true;
2880       }
2881
2882       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2883                                           G->getOffset(), OpFlags);
2884
2885       // Add a wrapper if needed.
2886       if (WrapperKind != ISD::DELETED_NODE)
2887         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2888       // Add extra indirection if needed.
2889       if (ExtraLoad)
2890         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2891                              MachinePointerInfo::getGOT(),
2892                              false, false, false, 0);
2893     }
2894   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2895     unsigned char OpFlags = 0;
2896
2897     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2898     // external symbols should go through the PLT.
2899     if (Subtarget->isTargetELF() &&
2900         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2901       OpFlags = X86II::MO_PLT;
2902     } else if (Subtarget->isPICStyleStubAny() &&
2903                (!Subtarget->getTargetTriple().isMacOSX() ||
2904                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2905       // PC-relative references to external symbols should go through $stub,
2906       // unless we're building with the leopard linker or later, which
2907       // automatically synthesizes these stubs.
2908       OpFlags = X86II::MO_DARWIN_STUB;
2909     }
2910
2911     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2912                                          OpFlags);
2913   }
2914
2915   // Returns a chain & a flag for retval copy to use.
2916   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2917   SmallVector<SDValue, 8> Ops;
2918
2919   if (!IsSibcall && isTailCall) {
2920     Chain = DAG.getCALLSEQ_END(Chain,
2921                                DAG.getIntPtrConstant(NumBytesToPop, true),
2922                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2923     InFlag = Chain.getValue(1);
2924   }
2925
2926   Ops.push_back(Chain);
2927   Ops.push_back(Callee);
2928
2929   if (isTailCall)
2930     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2931
2932   // Add argument registers to the end of the list so that they are known live
2933   // into the call.
2934   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2935     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2936                                   RegsToPass[i].second.getValueType()));
2937
2938   // Add a register mask operand representing the call-preserved registers.
2939   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2940   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2941   assert(Mask && "Missing call preserved mask for calling convention");
2942   Ops.push_back(DAG.getRegisterMask(Mask));
2943
2944   if (InFlag.getNode())
2945     Ops.push_back(InFlag);
2946
2947   if (isTailCall) {
2948     // We used to do:
2949     //// If this is the first return lowered for this function, add the regs
2950     //// to the liveout set for the function.
2951     // This isn't right, although it's probably harmless on x86; liveouts
2952     // should be computed from returns not tail calls.  Consider a void
2953     // function making a tail call to a function returning int.
2954     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2955   }
2956
2957   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2958   InFlag = Chain.getValue(1);
2959
2960   // Create the CALLSEQ_END node.
2961   unsigned NumBytesForCalleeToPop;
2962   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2963                        getTargetMachine().Options.GuaranteedTailCallOpt))
2964     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2965   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2966            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2967            SR == StackStructReturn)
2968     // If this is a call to a struct-return function, the callee
2969     // pops the hidden struct pointer, so we have to push it back.
2970     // This is common for Darwin/X86, Linux & Mingw32 targets.
2971     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2972     NumBytesForCalleeToPop = 4;
2973   else
2974     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2975
2976   // Returns a flag for retval copy to use.
2977   if (!IsSibcall) {
2978     Chain = DAG.getCALLSEQ_END(Chain,
2979                                DAG.getIntPtrConstant(NumBytesToPop, true),
2980                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2981                                                      true),
2982                                InFlag, dl);
2983     InFlag = Chain.getValue(1);
2984   }
2985
2986   // Handle result values, copying them out of physregs into vregs that we
2987   // return.
2988   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2989                          Ins, dl, DAG, InVals);
2990 }
2991
2992 //===----------------------------------------------------------------------===//
2993 //                Fast Calling Convention (tail call) implementation
2994 //===----------------------------------------------------------------------===//
2995
2996 //  Like std call, callee cleans arguments, convention except that ECX is
2997 //  reserved for storing the tail called function address. Only 2 registers are
2998 //  free for argument passing (inreg). Tail call optimization is performed
2999 //  provided:
3000 //                * tailcallopt is enabled
3001 //                * caller/callee are fastcc
3002 //  On X86_64 architecture with GOT-style position independent code only local
3003 //  (within module) calls are supported at the moment.
3004 //  To keep the stack aligned according to platform abi the function
3005 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3006 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3007 //  If a tail called function callee has more arguments than the caller the
3008 //  caller needs to make sure that there is room to move the RETADDR to. This is
3009 //  achieved by reserving an area the size of the argument delta right after the
3010 //  original REtADDR, but before the saved framepointer or the spilled registers
3011 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3012 //  stack layout:
3013 //    arg1
3014 //    arg2
3015 //    RETADDR
3016 //    [ new RETADDR
3017 //      move area ]
3018 //    (possible EBP)
3019 //    ESI
3020 //    EDI
3021 //    local1 ..
3022
3023 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3024 /// for a 16 byte align requirement.
3025 unsigned
3026 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3027                                                SelectionDAG& DAG) const {
3028   MachineFunction &MF = DAG.getMachineFunction();
3029   const TargetMachine &TM = MF.getTarget();
3030   const X86RegisterInfo *RegInfo =
3031     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3032   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3033   unsigned StackAlignment = TFI.getStackAlignment();
3034   uint64_t AlignMask = StackAlignment - 1;
3035   int64_t Offset = StackSize;
3036   unsigned SlotSize = RegInfo->getSlotSize();
3037   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3038     // Number smaller than 12 so just add the difference.
3039     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3040   } else {
3041     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3042     Offset = ((~AlignMask) & Offset) + StackAlignment +
3043       (StackAlignment-SlotSize);
3044   }
3045   return Offset;
3046 }
3047
3048 /// MatchingStackOffset - Return true if the given stack call argument is
3049 /// already available in the same position (relatively) of the caller's
3050 /// incoming argument stack.
3051 static
3052 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3053                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3054                          const X86InstrInfo *TII) {
3055   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3056   int FI = INT_MAX;
3057   if (Arg.getOpcode() == ISD::CopyFromReg) {
3058     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3059     if (!TargetRegisterInfo::isVirtualRegister(VR))
3060       return false;
3061     MachineInstr *Def = MRI->getVRegDef(VR);
3062     if (!Def)
3063       return false;
3064     if (!Flags.isByVal()) {
3065       if (!TII->isLoadFromStackSlot(Def, FI))
3066         return false;
3067     } else {
3068       unsigned Opcode = Def->getOpcode();
3069       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3070           Def->getOperand(1).isFI()) {
3071         FI = Def->getOperand(1).getIndex();
3072         Bytes = Flags.getByValSize();
3073       } else
3074         return false;
3075     }
3076   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3077     if (Flags.isByVal())
3078       // ByVal argument is passed in as a pointer but it's now being
3079       // dereferenced. e.g.
3080       // define @foo(%struct.X* %A) {
3081       //   tail call @bar(%struct.X* byval %A)
3082       // }
3083       return false;
3084     SDValue Ptr = Ld->getBasePtr();
3085     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3086     if (!FINode)
3087       return false;
3088     FI = FINode->getIndex();
3089   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3090     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3091     FI = FINode->getIndex();
3092     Bytes = Flags.getByValSize();
3093   } else
3094     return false;
3095
3096   assert(FI != INT_MAX);
3097   if (!MFI->isFixedObjectIndex(FI))
3098     return false;
3099   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3100 }
3101
3102 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3103 /// for tail call optimization. Targets which want to do tail call
3104 /// optimization should implement this function.
3105 bool
3106 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3107                                                      CallingConv::ID CalleeCC,
3108                                                      bool isVarArg,
3109                                                      bool isCalleeStructRet,
3110                                                      bool isCallerStructRet,
3111                                                      Type *RetTy,
3112                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3113                                     const SmallVectorImpl<SDValue> &OutVals,
3114                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3115                                                      SelectionDAG &DAG) const {
3116   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3117     return false;
3118
3119   // If -tailcallopt is specified, make fastcc functions tail-callable.
3120   const MachineFunction &MF = DAG.getMachineFunction();
3121   const Function *CallerF = MF.getFunction();
3122
3123   // If the function return type is x86_fp80 and the callee return type is not,
3124   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3125   // perform a tailcall optimization here.
3126   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3127     return false;
3128
3129   CallingConv::ID CallerCC = CallerF->getCallingConv();
3130   bool CCMatch = CallerCC == CalleeCC;
3131   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3132   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3133
3134   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3135     if (IsTailCallConvention(CalleeCC) && CCMatch)
3136       return true;
3137     return false;
3138   }
3139
3140   // Look for obvious safe cases to perform tail call optimization that do not
3141   // require ABI changes. This is what gcc calls sibcall.
3142
3143   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3144   // emit a special epilogue.
3145   const X86RegisterInfo *RegInfo =
3146     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3147   if (RegInfo->needsStackRealignment(MF))
3148     return false;
3149
3150   // Also avoid sibcall optimization if either caller or callee uses struct
3151   // return semantics.
3152   if (isCalleeStructRet || isCallerStructRet)
3153     return false;
3154
3155   // An stdcall/thiscall caller is expected to clean up its arguments; the
3156   // callee isn't going to do that.
3157   // FIXME: this is more restrictive than needed. We could produce a tailcall
3158   // when the stack adjustment matches. For example, with a thiscall that takes
3159   // only one argument.
3160   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3161                    CallerCC == CallingConv::X86_ThisCall))
3162     return false;
3163
3164   // Do not sibcall optimize vararg calls unless all arguments are passed via
3165   // registers.
3166   if (isVarArg && !Outs.empty()) {
3167
3168     // Optimizing for varargs on Win64 is unlikely to be safe without
3169     // additional testing.
3170     if (IsCalleeWin64 || IsCallerWin64)
3171       return false;
3172
3173     SmallVector<CCValAssign, 16> ArgLocs;
3174     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3175                    getTargetMachine(), ArgLocs, *DAG.getContext());
3176
3177     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3178     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3179       if (!ArgLocs[i].isRegLoc())
3180         return false;
3181   }
3182
3183   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3184   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3185   // this into a sibcall.
3186   bool Unused = false;
3187   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3188     if (!Ins[i].Used) {
3189       Unused = true;
3190       break;
3191     }
3192   }
3193   if (Unused) {
3194     SmallVector<CCValAssign, 16> RVLocs;
3195     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3196                    getTargetMachine(), RVLocs, *DAG.getContext());
3197     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3198     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3199       CCValAssign &VA = RVLocs[i];
3200       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3201         return false;
3202     }
3203   }
3204
3205   // If the calling conventions do not match, then we'd better make sure the
3206   // results are returned in the same way as what the caller expects.
3207   if (!CCMatch) {
3208     SmallVector<CCValAssign, 16> RVLocs1;
3209     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3210                     getTargetMachine(), RVLocs1, *DAG.getContext());
3211     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3212
3213     SmallVector<CCValAssign, 16> RVLocs2;
3214     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3215                     getTargetMachine(), RVLocs2, *DAG.getContext());
3216     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3217
3218     if (RVLocs1.size() != RVLocs2.size())
3219       return false;
3220     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3221       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3222         return false;
3223       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3224         return false;
3225       if (RVLocs1[i].isRegLoc()) {
3226         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3227           return false;
3228       } else {
3229         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3230           return false;
3231       }
3232     }
3233   }
3234
3235   // If the callee takes no arguments then go on to check the results of the
3236   // call.
3237   if (!Outs.empty()) {
3238     // Check if stack adjustment is needed. For now, do not do this if any
3239     // argument is passed on the stack.
3240     SmallVector<CCValAssign, 16> ArgLocs;
3241     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3242                    getTargetMachine(), ArgLocs, *DAG.getContext());
3243
3244     // Allocate shadow area for Win64
3245     if (IsCalleeWin64)
3246       CCInfo.AllocateStack(32, 8);
3247
3248     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3249     if (CCInfo.getNextStackOffset()) {
3250       MachineFunction &MF = DAG.getMachineFunction();
3251       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3252         return false;
3253
3254       // Check if the arguments are already laid out in the right way as
3255       // the caller's fixed stack objects.
3256       MachineFrameInfo *MFI = MF.getFrameInfo();
3257       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3258       const X86InstrInfo *TII =
3259         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3260       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3261         CCValAssign &VA = ArgLocs[i];
3262         SDValue Arg = OutVals[i];
3263         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3264         if (VA.getLocInfo() == CCValAssign::Indirect)
3265           return false;
3266         if (!VA.isRegLoc()) {
3267           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3268                                    MFI, MRI, TII))
3269             return false;
3270         }
3271       }
3272     }
3273
3274     // If the tailcall address may be in a register, then make sure it's
3275     // possible to register allocate for it. In 32-bit, the call address can
3276     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3277     // callee-saved registers are restored. These happen to be the same
3278     // registers used to pass 'inreg' arguments so watch out for those.
3279     if (!Subtarget->is64Bit() &&
3280         ((!isa<GlobalAddressSDNode>(Callee) &&
3281           !isa<ExternalSymbolSDNode>(Callee)) ||
3282          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3283       unsigned NumInRegs = 0;
3284       // In PIC we need an extra register to formulate the address computation
3285       // for the callee.
3286       unsigned MaxInRegs =
3287           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3288
3289       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3290         CCValAssign &VA = ArgLocs[i];
3291         if (!VA.isRegLoc())
3292           continue;
3293         unsigned Reg = VA.getLocReg();
3294         switch (Reg) {
3295         default: break;
3296         case X86::EAX: case X86::EDX: case X86::ECX:
3297           if (++NumInRegs == MaxInRegs)
3298             return false;
3299           break;
3300         }
3301       }
3302     }
3303   }
3304
3305   return true;
3306 }
3307
3308 FastISel *
3309 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3310                                   const TargetLibraryInfo *libInfo) const {
3311   return X86::createFastISel(funcInfo, libInfo);
3312 }
3313
3314 //===----------------------------------------------------------------------===//
3315 //                           Other Lowering Hooks
3316 //===----------------------------------------------------------------------===//
3317
3318 static bool MayFoldLoad(SDValue Op) {
3319   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3320 }
3321
3322 static bool MayFoldIntoStore(SDValue Op) {
3323   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3324 }
3325
3326 static bool isTargetShuffle(unsigned Opcode) {
3327   switch(Opcode) {
3328   default: return false;
3329   case X86ISD::PSHUFD:
3330   case X86ISD::PSHUFHW:
3331   case X86ISD::PSHUFLW:
3332   case X86ISD::SHUFP:
3333   case X86ISD::PALIGNR:
3334   case X86ISD::MOVLHPS:
3335   case X86ISD::MOVLHPD:
3336   case X86ISD::MOVHLPS:
3337   case X86ISD::MOVLPS:
3338   case X86ISD::MOVLPD:
3339   case X86ISD::MOVSHDUP:
3340   case X86ISD::MOVSLDUP:
3341   case X86ISD::MOVDDUP:
3342   case X86ISD::MOVSS:
3343   case X86ISD::MOVSD:
3344   case X86ISD::UNPCKL:
3345   case X86ISD::UNPCKH:
3346   case X86ISD::VPERMILP:
3347   case X86ISD::VPERM2X128:
3348   case X86ISD::VPERMI:
3349     return true;
3350   }
3351 }
3352
3353 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3354                                     SDValue V1, SelectionDAG &DAG) {
3355   switch(Opc) {
3356   default: llvm_unreachable("Unknown x86 shuffle node");
3357   case X86ISD::MOVSHDUP:
3358   case X86ISD::MOVSLDUP:
3359   case X86ISD::MOVDDUP:
3360     return DAG.getNode(Opc, dl, VT, V1);
3361   }
3362 }
3363
3364 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3365                                     SDValue V1, unsigned TargetMask,
3366                                     SelectionDAG &DAG) {
3367   switch(Opc) {
3368   default: llvm_unreachable("Unknown x86 shuffle node");
3369   case X86ISD::PSHUFD:
3370   case X86ISD::PSHUFHW:
3371   case X86ISD::PSHUFLW:
3372   case X86ISD::VPERMILP:
3373   case X86ISD::VPERMI:
3374     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3375   }
3376 }
3377
3378 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3379                                     SDValue V1, SDValue V2, unsigned TargetMask,
3380                                     SelectionDAG &DAG) {
3381   switch(Opc) {
3382   default: llvm_unreachable("Unknown x86 shuffle node");
3383   case X86ISD::PALIGNR:
3384   case X86ISD::SHUFP:
3385   case X86ISD::VPERM2X128:
3386     return DAG.getNode(Opc, dl, VT, V1, V2,
3387                        DAG.getConstant(TargetMask, MVT::i8));
3388   }
3389 }
3390
3391 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3392                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3393   switch(Opc) {
3394   default: llvm_unreachable("Unknown x86 shuffle node");
3395   case X86ISD::MOVLHPS:
3396   case X86ISD::MOVLHPD:
3397   case X86ISD::MOVHLPS:
3398   case X86ISD::MOVLPS:
3399   case X86ISD::MOVLPD:
3400   case X86ISD::MOVSS:
3401   case X86ISD::MOVSD:
3402   case X86ISD::UNPCKL:
3403   case X86ISD::UNPCKH:
3404     return DAG.getNode(Opc, dl, VT, V1, V2);
3405   }
3406 }
3407
3408 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3409   MachineFunction &MF = DAG.getMachineFunction();
3410   const X86RegisterInfo *RegInfo =
3411     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3412   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3413   int ReturnAddrIndex = FuncInfo->getRAIndex();
3414
3415   if (ReturnAddrIndex == 0) {
3416     // Set up a frame object for the return address.
3417     unsigned SlotSize = RegInfo->getSlotSize();
3418     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3419                                                            -(int64_t)SlotSize,
3420                                                            false);
3421     FuncInfo->setRAIndex(ReturnAddrIndex);
3422   }
3423
3424   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3425 }
3426
3427 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3428                                        bool hasSymbolicDisplacement) {
3429   // Offset should fit into 32 bit immediate field.
3430   if (!isInt<32>(Offset))
3431     return false;
3432
3433   // If we don't have a symbolic displacement - we don't have any extra
3434   // restrictions.
3435   if (!hasSymbolicDisplacement)
3436     return true;
3437
3438   // FIXME: Some tweaks might be needed for medium code model.
3439   if (M != CodeModel::Small && M != CodeModel::Kernel)
3440     return false;
3441
3442   // For small code model we assume that latest object is 16MB before end of 31
3443   // bits boundary. We may also accept pretty large negative constants knowing
3444   // that all objects are in the positive half of address space.
3445   if (M == CodeModel::Small && Offset < 16*1024*1024)
3446     return true;
3447
3448   // For kernel code model we know that all object resist in the negative half
3449   // of 32bits address space. We may not accept negative offsets, since they may
3450   // be just off and we may accept pretty large positive ones.
3451   if (M == CodeModel::Kernel && Offset > 0)
3452     return true;
3453
3454   return false;
3455 }
3456
3457 /// isCalleePop - Determines whether the callee is required to pop its
3458 /// own arguments. Callee pop is necessary to support tail calls.
3459 bool X86::isCalleePop(CallingConv::ID CallingConv,
3460                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3461   if (IsVarArg)
3462     return false;
3463
3464   switch (CallingConv) {
3465   default:
3466     return false;
3467   case CallingConv::X86_StdCall:
3468     return !is64Bit;
3469   case CallingConv::X86_FastCall:
3470     return !is64Bit;
3471   case CallingConv::X86_ThisCall:
3472     return !is64Bit;
3473   case CallingConv::Fast:
3474     return TailCallOpt;
3475   case CallingConv::GHC:
3476     return TailCallOpt;
3477   case CallingConv::HiPE:
3478     return TailCallOpt;
3479   }
3480 }
3481
3482 /// \brief Return true if the condition is an unsigned comparison operation.
3483 static bool isX86CCUnsigned(unsigned X86CC) {
3484   switch (X86CC) {
3485   default: llvm_unreachable("Invalid integer condition!");
3486   case X86::COND_E:     return true;
3487   case X86::COND_G:     return false;
3488   case X86::COND_GE:    return false;
3489   case X86::COND_L:     return false;
3490   case X86::COND_LE:    return false;
3491   case X86::COND_NE:    return true;
3492   case X86::COND_B:     return true;
3493   case X86::COND_A:     return true;
3494   case X86::COND_BE:    return true;
3495   case X86::COND_AE:    return true;
3496   }
3497   llvm_unreachable("covered switch fell through?!");
3498 }
3499
3500 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3501 /// specific condition code, returning the condition code and the LHS/RHS of the
3502 /// comparison to make.
3503 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3504                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3505   if (!isFP) {
3506     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3507       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3508         // X > -1   -> X == 0, jump !sign.
3509         RHS = DAG.getConstant(0, RHS.getValueType());
3510         return X86::COND_NS;
3511       }
3512       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3513         // X < 0   -> X == 0, jump on sign.
3514         return X86::COND_S;
3515       }
3516       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3517         // X < 1   -> X <= 0
3518         RHS = DAG.getConstant(0, RHS.getValueType());
3519         return X86::COND_LE;
3520       }
3521     }
3522
3523     switch (SetCCOpcode) {
3524     default: llvm_unreachable("Invalid integer condition!");
3525     case ISD::SETEQ:  return X86::COND_E;
3526     case ISD::SETGT:  return X86::COND_G;
3527     case ISD::SETGE:  return X86::COND_GE;
3528     case ISD::SETLT:  return X86::COND_L;
3529     case ISD::SETLE:  return X86::COND_LE;
3530     case ISD::SETNE:  return X86::COND_NE;
3531     case ISD::SETULT: return X86::COND_B;
3532     case ISD::SETUGT: return X86::COND_A;
3533     case ISD::SETULE: return X86::COND_BE;
3534     case ISD::SETUGE: return X86::COND_AE;
3535     }
3536   }
3537
3538   // First determine if it is required or is profitable to flip the operands.
3539
3540   // If LHS is a foldable load, but RHS is not, flip the condition.
3541   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3542       !ISD::isNON_EXTLoad(RHS.getNode())) {
3543     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3544     std::swap(LHS, RHS);
3545   }
3546
3547   switch (SetCCOpcode) {
3548   default: break;
3549   case ISD::SETOLT:
3550   case ISD::SETOLE:
3551   case ISD::SETUGT:
3552   case ISD::SETUGE:
3553     std::swap(LHS, RHS);
3554     break;
3555   }
3556
3557   // On a floating point condition, the flags are set as follows:
3558   // ZF  PF  CF   op
3559   //  0 | 0 | 0 | X > Y
3560   //  0 | 0 | 1 | X < Y
3561   //  1 | 0 | 0 | X == Y
3562   //  1 | 1 | 1 | unordered
3563   switch (SetCCOpcode) {
3564   default: llvm_unreachable("Condcode should be pre-legalized away");
3565   case ISD::SETUEQ:
3566   case ISD::SETEQ:   return X86::COND_E;
3567   case ISD::SETOLT:              // flipped
3568   case ISD::SETOGT:
3569   case ISD::SETGT:   return X86::COND_A;
3570   case ISD::SETOLE:              // flipped
3571   case ISD::SETOGE:
3572   case ISD::SETGE:   return X86::COND_AE;
3573   case ISD::SETUGT:              // flipped
3574   case ISD::SETULT:
3575   case ISD::SETLT:   return X86::COND_B;
3576   case ISD::SETUGE:              // flipped
3577   case ISD::SETULE:
3578   case ISD::SETLE:   return X86::COND_BE;
3579   case ISD::SETONE:
3580   case ISD::SETNE:   return X86::COND_NE;
3581   case ISD::SETUO:   return X86::COND_P;
3582   case ISD::SETO:    return X86::COND_NP;
3583   case ISD::SETOEQ:
3584   case ISD::SETUNE:  return X86::COND_INVALID;
3585   }
3586 }
3587
3588 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3589 /// code. Current x86 isa includes the following FP cmov instructions:
3590 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3591 static bool hasFPCMov(unsigned X86CC) {
3592   switch (X86CC) {
3593   default:
3594     return false;
3595   case X86::COND_B:
3596   case X86::COND_BE:
3597   case X86::COND_E:
3598   case X86::COND_P:
3599   case X86::COND_A:
3600   case X86::COND_AE:
3601   case X86::COND_NE:
3602   case X86::COND_NP:
3603     return true;
3604   }
3605 }
3606
3607 /// isFPImmLegal - Returns true if the target can instruction select the
3608 /// specified FP immediate natively. If false, the legalizer will
3609 /// materialize the FP immediate as a load from a constant pool.
3610 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3611   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3612     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3613       return true;
3614   }
3615   return false;
3616 }
3617
3618 /// \brief Returns true if it is beneficial to convert a load of a constant
3619 /// to just the constant itself.
3620 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3621                                                           Type *Ty) const {
3622   assert(Ty->isIntegerTy());
3623
3624   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3625   if (BitSize == 0 || BitSize > 64)
3626     return false;
3627   return true;
3628 }
3629
3630 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3631 /// the specified range (L, H].
3632 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3633   return (Val < 0) || (Val >= Low && Val < Hi);
3634 }
3635
3636 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3637 /// specified value.
3638 static bool isUndefOrEqual(int Val, int CmpVal) {
3639   return (Val < 0 || Val == CmpVal);
3640 }
3641
3642 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3643 /// from position Pos and ending in Pos+Size, falls within the specified
3644 /// sequential range (L, L+Pos]. or is undef.
3645 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3646                                        unsigned Pos, unsigned Size, int Low) {
3647   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3648     if (!isUndefOrEqual(Mask[i], Low))
3649       return false;
3650   return true;
3651 }
3652
3653 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3654 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3655 /// the second operand.
3656 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3657   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3658     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3659   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3660     return (Mask[0] < 2 && Mask[1] < 2);
3661   return false;
3662 }
3663
3664 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3665 /// is suitable for input to PSHUFHW.
3666 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3667   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3668     return false;
3669
3670   // Lower quadword copied in order or undef.
3671   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3672     return false;
3673
3674   // Upper quadword shuffled.
3675   for (unsigned i = 4; i != 8; ++i)
3676     if (!isUndefOrInRange(Mask[i], 4, 8))
3677       return false;
3678
3679   if (VT == MVT::v16i16) {
3680     // Lower quadword copied in order or undef.
3681     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3682       return false;
3683
3684     // Upper quadword shuffled.
3685     for (unsigned i = 12; i != 16; ++i)
3686       if (!isUndefOrInRange(Mask[i], 12, 16))
3687         return false;
3688   }
3689
3690   return true;
3691 }
3692
3693 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3694 /// is suitable for input to PSHUFLW.
3695 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3696   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3697     return false;
3698
3699   // Upper quadword copied in order.
3700   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3701     return false;
3702
3703   // Lower quadword shuffled.
3704   for (unsigned i = 0; i != 4; ++i)
3705     if (!isUndefOrInRange(Mask[i], 0, 4))
3706       return false;
3707
3708   if (VT == MVT::v16i16) {
3709     // Upper quadword copied in order.
3710     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3711       return false;
3712
3713     // Lower quadword shuffled.
3714     for (unsigned i = 8; i != 12; ++i)
3715       if (!isUndefOrInRange(Mask[i], 8, 12))
3716         return false;
3717   }
3718
3719   return true;
3720 }
3721
3722 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3723 /// is suitable for input to PALIGNR.
3724 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3725                           const X86Subtarget *Subtarget) {
3726   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3727       (VT.is256BitVector() && !Subtarget->hasInt256()))
3728     return false;
3729
3730   unsigned NumElts = VT.getVectorNumElements();
3731   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3732   unsigned NumLaneElts = NumElts/NumLanes;
3733
3734   // Do not handle 64-bit element shuffles with palignr.
3735   if (NumLaneElts == 2)
3736     return false;
3737
3738   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3739     unsigned i;
3740     for (i = 0; i != NumLaneElts; ++i) {
3741       if (Mask[i+l] >= 0)
3742         break;
3743     }
3744
3745     // Lane is all undef, go to next lane
3746     if (i == NumLaneElts)
3747       continue;
3748
3749     int Start = Mask[i+l];
3750
3751     // Make sure its in this lane in one of the sources
3752     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3753         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3754       return false;
3755
3756     // If not lane 0, then we must match lane 0
3757     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3758       return false;
3759
3760     // Correct second source to be contiguous with first source
3761     if (Start >= (int)NumElts)
3762       Start -= NumElts - NumLaneElts;
3763
3764     // Make sure we're shifting in the right direction.
3765     if (Start <= (int)(i+l))
3766       return false;
3767
3768     Start -= i;
3769
3770     // Check the rest of the elements to see if they are consecutive.
3771     for (++i; i != NumLaneElts; ++i) {
3772       int Idx = Mask[i+l];
3773
3774       // Make sure its in this lane
3775       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3776           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3777         return false;
3778
3779       // If not lane 0, then we must match lane 0
3780       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3781         return false;
3782
3783       if (Idx >= (int)NumElts)
3784         Idx -= NumElts - NumLaneElts;
3785
3786       if (!isUndefOrEqual(Idx, Start+i))
3787         return false;
3788
3789     }
3790   }
3791
3792   return true;
3793 }
3794
3795 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3796 /// the two vector operands have swapped position.
3797 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3798                                      unsigned NumElems) {
3799   for (unsigned i = 0; i != NumElems; ++i) {
3800     int idx = Mask[i];
3801     if (idx < 0)
3802       continue;
3803     else if (idx < (int)NumElems)
3804       Mask[i] = idx + NumElems;
3805     else
3806       Mask[i] = idx - NumElems;
3807   }
3808 }
3809
3810 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3811 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3812 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3813 /// reverse of what x86 shuffles want.
3814 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3815
3816   unsigned NumElems = VT.getVectorNumElements();
3817   unsigned NumLanes = VT.getSizeInBits()/128;
3818   unsigned NumLaneElems = NumElems/NumLanes;
3819
3820   if (NumLaneElems != 2 && NumLaneElems != 4)
3821     return false;
3822
3823   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3824   bool symetricMaskRequired =
3825     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3826
3827   // VSHUFPSY divides the resulting vector into 4 chunks.
3828   // The sources are also splitted into 4 chunks, and each destination
3829   // chunk must come from a different source chunk.
3830   //
3831   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3832   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3833   //
3834   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3835   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3836   //
3837   // VSHUFPDY divides the resulting vector into 4 chunks.
3838   // The sources are also splitted into 4 chunks, and each destination
3839   // chunk must come from a different source chunk.
3840   //
3841   //  SRC1 =>      X3       X2       X1       X0
3842   //  SRC2 =>      Y3       Y2       Y1       Y0
3843   //
3844   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3845   //
3846   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3847   unsigned HalfLaneElems = NumLaneElems/2;
3848   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3849     for (unsigned i = 0; i != NumLaneElems; ++i) {
3850       int Idx = Mask[i+l];
3851       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3852       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3853         return false;
3854       // For VSHUFPSY, the mask of the second half must be the same as the
3855       // first but with the appropriate offsets. This works in the same way as
3856       // VPERMILPS works with masks.
3857       if (!symetricMaskRequired || Idx < 0)
3858         continue;
3859       if (MaskVal[i] < 0) {
3860         MaskVal[i] = Idx - l;
3861         continue;
3862       }
3863       if ((signed)(Idx - l) != MaskVal[i])
3864         return false;
3865     }
3866   }
3867
3868   return true;
3869 }
3870
3871 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3873 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3874   if (!VT.is128BitVector())
3875     return false;
3876
3877   unsigned NumElems = VT.getVectorNumElements();
3878
3879   if (NumElems != 4)
3880     return false;
3881
3882   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3883   return isUndefOrEqual(Mask[0], 6) &&
3884          isUndefOrEqual(Mask[1], 7) &&
3885          isUndefOrEqual(Mask[2], 2) &&
3886          isUndefOrEqual(Mask[3], 3);
3887 }
3888
3889 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3890 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3891 /// <2, 3, 2, 3>
3892 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3893   if (!VT.is128BitVector())
3894     return false;
3895
3896   unsigned NumElems = VT.getVectorNumElements();
3897
3898   if (NumElems != 4)
3899     return false;
3900
3901   return isUndefOrEqual(Mask[0], 2) &&
3902          isUndefOrEqual(Mask[1], 3) &&
3903          isUndefOrEqual(Mask[2], 2) &&
3904          isUndefOrEqual(Mask[3], 3);
3905 }
3906
3907 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3909 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3910   if (!VT.is128BitVector())
3911     return false;
3912
3913   unsigned NumElems = VT.getVectorNumElements();
3914
3915   if (NumElems != 2 && NumElems != 4)
3916     return false;
3917
3918   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3919     if (!isUndefOrEqual(Mask[i], i + NumElems))
3920       return false;
3921
3922   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3923     if (!isUndefOrEqual(Mask[i], i))
3924       return false;
3925
3926   return true;
3927 }
3928
3929 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3930 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3931 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3932   if (!VT.is128BitVector())
3933     return false;
3934
3935   unsigned NumElems = VT.getVectorNumElements();
3936
3937   if (NumElems != 2 && NumElems != 4)
3938     return false;
3939
3940   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3941     if (!isUndefOrEqual(Mask[i], i))
3942       return false;
3943
3944   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3945     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3946       return false;
3947
3948   return true;
3949 }
3950
3951 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3952 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3953 /// i. e: If all but one element come from the same vector.
3954 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3955   // TODO: Deal with AVX's VINSERTPS
3956   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3957     return false;
3958
3959   unsigned CorrectPosV1 = 0;
3960   unsigned CorrectPosV2 = 0;
3961   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3962     if (Mask[i] == i)
3963       ++CorrectPosV1;
3964     else if (Mask[i] == i + 4)
3965       ++CorrectPosV2;
3966
3967   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3968     // We have 3 elements from one vector, and one from another.
3969     return true;
3970
3971   return false;
3972 }
3973
3974 //
3975 // Some special combinations that can be optimized.
3976 //
3977 static
3978 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3979                                SelectionDAG &DAG) {
3980   MVT VT = SVOp->getSimpleValueType(0);
3981   SDLoc dl(SVOp);
3982
3983   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3984     return SDValue();
3985
3986   ArrayRef<int> Mask = SVOp->getMask();
3987
3988   // These are the special masks that may be optimized.
3989   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3990   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3991   bool MatchEvenMask = true;
3992   bool MatchOddMask  = true;
3993   for (int i=0; i<8; ++i) {
3994     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3995       MatchEvenMask = false;
3996     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3997       MatchOddMask = false;
3998   }
3999
4000   if (!MatchEvenMask && !MatchOddMask)
4001     return SDValue();
4002
4003   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4004
4005   SDValue Op0 = SVOp->getOperand(0);
4006   SDValue Op1 = SVOp->getOperand(1);
4007
4008   if (MatchEvenMask) {
4009     // Shift the second operand right to 32 bits.
4010     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4011     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4012   } else {
4013     // Shift the first operand left to 32 bits.
4014     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4015     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4016   }
4017   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4018   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4019 }
4020
4021 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4022 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4023 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4024                          bool HasInt256, bool V2IsSplat = false) {
4025
4026   assert(VT.getSizeInBits() >= 128 &&
4027          "Unsupported vector type for unpckl");
4028
4029   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4030   unsigned NumLanes;
4031   unsigned NumOf256BitLanes;
4032   unsigned NumElts = VT.getVectorNumElements();
4033   if (VT.is256BitVector()) {
4034     if (NumElts != 4 && NumElts != 8 &&
4035         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4036     return false;
4037     NumLanes = 2;
4038     NumOf256BitLanes = 1;
4039   } else if (VT.is512BitVector()) {
4040     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4041            "Unsupported vector type for unpckh");
4042     NumLanes = 2;
4043     NumOf256BitLanes = 2;
4044   } else {
4045     NumLanes = 1;
4046     NumOf256BitLanes = 1;
4047   }
4048
4049   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4050   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4051
4052   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4053     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4054       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4055         int BitI  = Mask[l256*NumEltsInStride+l+i];
4056         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4057         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4058           return false;
4059         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4060           return false;
4061         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4062           return false;
4063       }
4064     }
4065   }
4066   return true;
4067 }
4068
4069 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4070 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4071 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4072                          bool HasInt256, bool V2IsSplat = false) {
4073   assert(VT.getSizeInBits() >= 128 &&
4074          "Unsupported vector type for unpckh");
4075
4076   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4077   unsigned NumLanes;
4078   unsigned NumOf256BitLanes;
4079   unsigned NumElts = VT.getVectorNumElements();
4080   if (VT.is256BitVector()) {
4081     if (NumElts != 4 && NumElts != 8 &&
4082         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4083     return false;
4084     NumLanes = 2;
4085     NumOf256BitLanes = 1;
4086   } else if (VT.is512BitVector()) {
4087     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4088            "Unsupported vector type for unpckh");
4089     NumLanes = 2;
4090     NumOf256BitLanes = 2;
4091   } else {
4092     NumLanes = 1;
4093     NumOf256BitLanes = 1;
4094   }
4095
4096   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4097   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4098
4099   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4100     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4101       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4102         int BitI  = Mask[l256*NumEltsInStride+l+i];
4103         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4104         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4105           return false;
4106         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4107           return false;
4108         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4109           return false;
4110       }
4111     }
4112   }
4113   return true;
4114 }
4115
4116 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4117 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4118 /// <0, 0, 1, 1>
4119 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4120   unsigned NumElts = VT.getVectorNumElements();
4121   bool Is256BitVec = VT.is256BitVector();
4122
4123   if (VT.is512BitVector())
4124     return false;
4125   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4126          "Unsupported vector type for unpckh");
4127
4128   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4129       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4130     return false;
4131
4132   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4133   // FIXME: Need a better way to get rid of this, there's no latency difference
4134   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4135   // the former later. We should also remove the "_undef" special mask.
4136   if (NumElts == 4 && Is256BitVec)
4137     return false;
4138
4139   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4140   // independently on 128-bit lanes.
4141   unsigned NumLanes = VT.getSizeInBits()/128;
4142   unsigned NumLaneElts = NumElts/NumLanes;
4143
4144   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4145     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4146       int BitI  = Mask[l+i];
4147       int BitI1 = Mask[l+i+1];
4148
4149       if (!isUndefOrEqual(BitI, j))
4150         return false;
4151       if (!isUndefOrEqual(BitI1, j))
4152         return false;
4153     }
4154   }
4155
4156   return true;
4157 }
4158
4159 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4160 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4161 /// <2, 2, 3, 3>
4162 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4163   unsigned NumElts = VT.getVectorNumElements();
4164
4165   if (VT.is512BitVector())
4166     return false;
4167
4168   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4169          "Unsupported vector type for unpckh");
4170
4171   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4172       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4173     return false;
4174
4175   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4176   // independently on 128-bit lanes.
4177   unsigned NumLanes = VT.getSizeInBits()/128;
4178   unsigned NumLaneElts = NumElts/NumLanes;
4179
4180   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4181     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4182       int BitI  = Mask[l+i];
4183       int BitI1 = Mask[l+i+1];
4184       if (!isUndefOrEqual(BitI, j))
4185         return false;
4186       if (!isUndefOrEqual(BitI1, j))
4187         return false;
4188     }
4189   }
4190   return true;
4191 }
4192
4193 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4194 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4195 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4196   if (!VT.is512BitVector())
4197     return false;
4198
4199   unsigned NumElts = VT.getVectorNumElements();
4200   unsigned HalfSize = NumElts/2;
4201   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4202     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4203       *Imm = 1;
4204       return true;
4205     }
4206   }
4207   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4208     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4209       *Imm = 0;
4210       return true;
4211     }
4212   }
4213   return false;
4214 }
4215
4216 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4217 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4218 /// MOVSD, and MOVD, i.e. setting the lowest element.
4219 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4220   if (VT.getVectorElementType().getSizeInBits() < 32)
4221     return false;
4222   if (!VT.is128BitVector())
4223     return false;
4224
4225   unsigned NumElts = VT.getVectorNumElements();
4226
4227   if (!isUndefOrEqual(Mask[0], NumElts))
4228     return false;
4229
4230   for (unsigned i = 1; i != NumElts; ++i)
4231     if (!isUndefOrEqual(Mask[i], i))
4232       return false;
4233
4234   return true;
4235 }
4236
4237 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4238 /// as permutations between 128-bit chunks or halves. As an example: this
4239 /// shuffle bellow:
4240 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4241 /// The first half comes from the second half of V1 and the second half from the
4242 /// the second half of V2.
4243 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4244   if (!HasFp256 || !VT.is256BitVector())
4245     return false;
4246
4247   // The shuffle result is divided into half A and half B. In total the two
4248   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4249   // B must come from C, D, E or F.
4250   unsigned HalfSize = VT.getVectorNumElements()/2;
4251   bool MatchA = false, MatchB = false;
4252
4253   // Check if A comes from one of C, D, E, F.
4254   for (unsigned Half = 0; Half != 4; ++Half) {
4255     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4256       MatchA = true;
4257       break;
4258     }
4259   }
4260
4261   // Check if B comes from one of C, D, E, F.
4262   for (unsigned Half = 0; Half != 4; ++Half) {
4263     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4264       MatchB = true;
4265       break;
4266     }
4267   }
4268
4269   return MatchA && MatchB;
4270 }
4271
4272 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4273 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4274 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4275   MVT VT = SVOp->getSimpleValueType(0);
4276
4277   unsigned HalfSize = VT.getVectorNumElements()/2;
4278
4279   unsigned FstHalf = 0, SndHalf = 0;
4280   for (unsigned i = 0; i < HalfSize; ++i) {
4281     if (SVOp->getMaskElt(i) > 0) {
4282       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4283       break;
4284     }
4285   }
4286   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4287     if (SVOp->getMaskElt(i) > 0) {
4288       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4289       break;
4290     }
4291   }
4292
4293   return (FstHalf | (SndHalf << 4));
4294 }
4295
4296 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4297 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4298   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4299   if (EltSize < 32)
4300     return false;
4301
4302   unsigned NumElts = VT.getVectorNumElements();
4303   Imm8 = 0;
4304   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4305     for (unsigned i = 0; i != NumElts; ++i) {
4306       if (Mask[i] < 0)
4307         continue;
4308       Imm8 |= Mask[i] << (i*2);
4309     }
4310     return true;
4311   }
4312
4313   unsigned LaneSize = 4;
4314   SmallVector<int, 4> MaskVal(LaneSize, -1);
4315
4316   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4317     for (unsigned i = 0; i != LaneSize; ++i) {
4318       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4319         return false;
4320       if (Mask[i+l] < 0)
4321         continue;
4322       if (MaskVal[i] < 0) {
4323         MaskVal[i] = Mask[i+l] - l;
4324         Imm8 |= MaskVal[i] << (i*2);
4325         continue;
4326       }
4327       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4328         return false;
4329     }
4330   }
4331   return true;
4332 }
4333
4334 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4335 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4336 /// Note that VPERMIL mask matching is different depending whether theunderlying
4337 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4338 /// to the same elements of the low, but to the higher half of the source.
4339 /// In VPERMILPD the two lanes could be shuffled independently of each other
4340 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4341 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4342   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4343   if (VT.getSizeInBits() < 256 || EltSize < 32)
4344     return false;
4345   bool symetricMaskRequired = (EltSize == 32);
4346   unsigned NumElts = VT.getVectorNumElements();
4347
4348   unsigned NumLanes = VT.getSizeInBits()/128;
4349   unsigned LaneSize = NumElts/NumLanes;
4350   // 2 or 4 elements in one lane
4351
4352   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4353   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4354     for (unsigned i = 0; i != LaneSize; ++i) {
4355       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4356         return false;
4357       if (symetricMaskRequired) {
4358         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4359           ExpectedMaskVal[i] = Mask[i+l] - l;
4360           continue;
4361         }
4362         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4363           return false;
4364       }
4365     }
4366   }
4367   return true;
4368 }
4369
4370 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4371 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4372 /// element of vector 2 and the other elements to come from vector 1 in order.
4373 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4374                                bool V2IsSplat = false, bool V2IsUndef = false) {
4375   if (!VT.is128BitVector())
4376     return false;
4377
4378   unsigned NumOps = VT.getVectorNumElements();
4379   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4380     return false;
4381
4382   if (!isUndefOrEqual(Mask[0], 0))
4383     return false;
4384
4385   for (unsigned i = 1; i != NumOps; ++i)
4386     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4387           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4388           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4389       return false;
4390
4391   return true;
4392 }
4393
4394 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4395 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4396 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4397 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4398                            const X86Subtarget *Subtarget) {
4399   if (!Subtarget->hasSSE3())
4400     return false;
4401
4402   unsigned NumElems = VT.getVectorNumElements();
4403
4404   if ((VT.is128BitVector() && NumElems != 4) ||
4405       (VT.is256BitVector() && NumElems != 8) ||
4406       (VT.is512BitVector() && NumElems != 16))
4407     return false;
4408
4409   // "i+1" is the value the indexed mask element must have
4410   for (unsigned i = 0; i != NumElems; i += 2)
4411     if (!isUndefOrEqual(Mask[i], i+1) ||
4412         !isUndefOrEqual(Mask[i+1], i+1))
4413       return false;
4414
4415   return true;
4416 }
4417
4418 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4419 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4420 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4421 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4422                            const X86Subtarget *Subtarget) {
4423   if (!Subtarget->hasSSE3())
4424     return false;
4425
4426   unsigned NumElems = VT.getVectorNumElements();
4427
4428   if ((VT.is128BitVector() && NumElems != 4) ||
4429       (VT.is256BitVector() && NumElems != 8) ||
4430       (VT.is512BitVector() && NumElems != 16))
4431     return false;
4432
4433   // "i" is the value the indexed mask element must have
4434   for (unsigned i = 0; i != NumElems; i += 2)
4435     if (!isUndefOrEqual(Mask[i], i) ||
4436         !isUndefOrEqual(Mask[i+1], i))
4437       return false;
4438
4439   return true;
4440 }
4441
4442 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4443 /// specifies a shuffle of elements that is suitable for input to 256-bit
4444 /// version of MOVDDUP.
4445 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4446   if (!HasFp256 || !VT.is256BitVector())
4447     return false;
4448
4449   unsigned NumElts = VT.getVectorNumElements();
4450   if (NumElts != 4)
4451     return false;
4452
4453   for (unsigned i = 0; i != NumElts/2; ++i)
4454     if (!isUndefOrEqual(Mask[i], 0))
4455       return false;
4456   for (unsigned i = NumElts/2; i != NumElts; ++i)
4457     if (!isUndefOrEqual(Mask[i], NumElts/2))
4458       return false;
4459   return true;
4460 }
4461
4462 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4463 /// specifies a shuffle of elements that is suitable for input to 128-bit
4464 /// version of MOVDDUP.
4465 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4466   if (!VT.is128BitVector())
4467     return false;
4468
4469   unsigned e = VT.getVectorNumElements() / 2;
4470   for (unsigned i = 0; i != e; ++i)
4471     if (!isUndefOrEqual(Mask[i], i))
4472       return false;
4473   for (unsigned i = 0; i != e; ++i)
4474     if (!isUndefOrEqual(Mask[e+i], i))
4475       return false;
4476   return true;
4477 }
4478
4479 /// isVEXTRACTIndex - Return true if the specified
4480 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4481 /// suitable for instruction that extract 128 or 256 bit vectors
4482 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4483   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4484   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4485     return false;
4486
4487   // The index should be aligned on a vecWidth-bit boundary.
4488   uint64_t Index =
4489     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4490
4491   MVT VT = N->getSimpleValueType(0);
4492   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4493   bool Result = (Index * ElSize) % vecWidth == 0;
4494
4495   return Result;
4496 }
4497
4498 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4499 /// operand specifies a subvector insert that is suitable for input to
4500 /// insertion of 128 or 256-bit subvectors
4501 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4502   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4503   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4504     return false;
4505   // The index should be aligned on a vecWidth-bit boundary.
4506   uint64_t Index =
4507     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4508
4509   MVT VT = N->getSimpleValueType(0);
4510   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4511   bool Result = (Index * ElSize) % vecWidth == 0;
4512
4513   return Result;
4514 }
4515
4516 bool X86::isVINSERT128Index(SDNode *N) {
4517   return isVINSERTIndex(N, 128);
4518 }
4519
4520 bool X86::isVINSERT256Index(SDNode *N) {
4521   return isVINSERTIndex(N, 256);
4522 }
4523
4524 bool X86::isVEXTRACT128Index(SDNode *N) {
4525   return isVEXTRACTIndex(N, 128);
4526 }
4527
4528 bool X86::isVEXTRACT256Index(SDNode *N) {
4529   return isVEXTRACTIndex(N, 256);
4530 }
4531
4532 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4533 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4534 /// Handles 128-bit and 256-bit.
4535 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4536   MVT VT = N->getSimpleValueType(0);
4537
4538   assert((VT.getSizeInBits() >= 128) &&
4539          "Unsupported vector type for PSHUF/SHUFP");
4540
4541   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4542   // independently on 128-bit lanes.
4543   unsigned NumElts = VT.getVectorNumElements();
4544   unsigned NumLanes = VT.getSizeInBits()/128;
4545   unsigned NumLaneElts = NumElts/NumLanes;
4546
4547   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4548          "Only supports 2, 4 or 8 elements per lane");
4549
4550   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4551   unsigned Mask = 0;
4552   for (unsigned i = 0; i != NumElts; ++i) {
4553     int Elt = N->getMaskElt(i);
4554     if (Elt < 0) continue;
4555     Elt &= NumLaneElts - 1;
4556     unsigned ShAmt = (i << Shift) % 8;
4557     Mask |= Elt << ShAmt;
4558   }
4559
4560   return Mask;
4561 }
4562
4563 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4564 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4565 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4566   MVT VT = N->getSimpleValueType(0);
4567
4568   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4569          "Unsupported vector type for PSHUFHW");
4570
4571   unsigned NumElts = VT.getVectorNumElements();
4572
4573   unsigned Mask = 0;
4574   for (unsigned l = 0; l != NumElts; l += 8) {
4575     // 8 nodes per lane, but we only care about the last 4.
4576     for (unsigned i = 0; i < 4; ++i) {
4577       int Elt = N->getMaskElt(l+i+4);
4578       if (Elt < 0) continue;
4579       Elt &= 0x3; // only 2-bits.
4580       Mask |= Elt << (i * 2);
4581     }
4582   }
4583
4584   return Mask;
4585 }
4586
4587 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4588 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4589 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4590   MVT VT = N->getSimpleValueType(0);
4591
4592   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4593          "Unsupported vector type for PSHUFHW");
4594
4595   unsigned NumElts = VT.getVectorNumElements();
4596
4597   unsigned Mask = 0;
4598   for (unsigned l = 0; l != NumElts; l += 8) {
4599     // 8 nodes per lane, but we only care about the first 4.
4600     for (unsigned i = 0; i < 4; ++i) {
4601       int Elt = N->getMaskElt(l+i);
4602       if (Elt < 0) continue;
4603       Elt &= 0x3; // only 2-bits
4604       Mask |= Elt << (i * 2);
4605     }
4606   }
4607
4608   return Mask;
4609 }
4610
4611 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4612 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4613 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4614   MVT VT = SVOp->getSimpleValueType(0);
4615   unsigned EltSize = VT.is512BitVector() ? 1 :
4616     VT.getVectorElementType().getSizeInBits() >> 3;
4617
4618   unsigned NumElts = VT.getVectorNumElements();
4619   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4620   unsigned NumLaneElts = NumElts/NumLanes;
4621
4622   int Val = 0;
4623   unsigned i;
4624   for (i = 0; i != NumElts; ++i) {
4625     Val = SVOp->getMaskElt(i);
4626     if (Val >= 0)
4627       break;
4628   }
4629   if (Val >= (int)NumElts)
4630     Val -= NumElts - NumLaneElts;
4631
4632   assert(Val - i > 0 && "PALIGNR imm should be positive");
4633   return (Val - i) * EltSize;
4634 }
4635
4636 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4637   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4638   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4639     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4640
4641   uint64_t Index =
4642     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4643
4644   MVT VecVT = N->getOperand(0).getSimpleValueType();
4645   MVT ElVT = VecVT.getVectorElementType();
4646
4647   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4648   return Index / NumElemsPerChunk;
4649 }
4650
4651 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4652   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4653   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4654     llvm_unreachable("Illegal insert subvector for VINSERT");
4655
4656   uint64_t Index =
4657     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4658
4659   MVT VecVT = N->getSimpleValueType(0);
4660   MVT ElVT = VecVT.getVectorElementType();
4661
4662   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4663   return Index / NumElemsPerChunk;
4664 }
4665
4666 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4667 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4668 /// and VINSERTI128 instructions.
4669 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4670   return getExtractVEXTRACTImmediate(N, 128);
4671 }
4672
4673 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4674 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4675 /// and VINSERTI64x4 instructions.
4676 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4677   return getExtractVEXTRACTImmediate(N, 256);
4678 }
4679
4680 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4681 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4682 /// and VINSERTI128 instructions.
4683 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4684   return getInsertVINSERTImmediate(N, 128);
4685 }
4686
4687 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4688 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4689 /// and VINSERTI64x4 instructions.
4690 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4691   return getInsertVINSERTImmediate(N, 256);
4692 }
4693
4694 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4695 /// constant +0.0.
4696 bool X86::isZeroNode(SDValue Elt) {
4697   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4698     return CN->isNullValue();
4699   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4700     return CFP->getValueAPF().isPosZero();
4701   return false;
4702 }
4703
4704 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4705 /// their permute mask.
4706 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4707                                     SelectionDAG &DAG) {
4708   MVT VT = SVOp->getSimpleValueType(0);
4709   unsigned NumElems = VT.getVectorNumElements();
4710   SmallVector<int, 8> MaskVec;
4711
4712   for (unsigned i = 0; i != NumElems; ++i) {
4713     int Idx = SVOp->getMaskElt(i);
4714     if (Idx >= 0) {
4715       if (Idx < (int)NumElems)
4716         Idx += NumElems;
4717       else
4718         Idx -= NumElems;
4719     }
4720     MaskVec.push_back(Idx);
4721   }
4722   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4723                               SVOp->getOperand(0), &MaskVec[0]);
4724 }
4725
4726 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4727 /// match movhlps. The lower half elements should come from upper half of
4728 /// V1 (and in order), and the upper half elements should come from the upper
4729 /// half of V2 (and in order).
4730 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4731   if (!VT.is128BitVector())
4732     return false;
4733   if (VT.getVectorNumElements() != 4)
4734     return false;
4735   for (unsigned i = 0, e = 2; i != e; ++i)
4736     if (!isUndefOrEqual(Mask[i], i+2))
4737       return false;
4738   for (unsigned i = 2; i != 4; ++i)
4739     if (!isUndefOrEqual(Mask[i], i+4))
4740       return false;
4741   return true;
4742 }
4743
4744 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4745 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4746 /// required.
4747 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4748   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4749     return false;
4750   N = N->getOperand(0).getNode();
4751   if (!ISD::isNON_EXTLoad(N))
4752     return false;
4753   if (LD)
4754     *LD = cast<LoadSDNode>(N);
4755   return true;
4756 }
4757
4758 // Test whether the given value is a vector value which will be legalized
4759 // into a load.
4760 static bool WillBeConstantPoolLoad(SDNode *N) {
4761   if (N->getOpcode() != ISD::BUILD_VECTOR)
4762     return false;
4763
4764   // Check for any non-constant elements.
4765   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4766     switch (N->getOperand(i).getNode()->getOpcode()) {
4767     case ISD::UNDEF:
4768     case ISD::ConstantFP:
4769     case ISD::Constant:
4770       break;
4771     default:
4772       return false;
4773     }
4774
4775   // Vectors of all-zeros and all-ones are materialized with special
4776   // instructions rather than being loaded.
4777   return !ISD::isBuildVectorAllZeros(N) &&
4778          !ISD::isBuildVectorAllOnes(N);
4779 }
4780
4781 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4782 /// match movlp{s|d}. The lower half elements should come from lower half of
4783 /// V1 (and in order), and the upper half elements should come from the upper
4784 /// half of V2 (and in order). And since V1 will become the source of the
4785 /// MOVLP, it must be either a vector load or a scalar load to vector.
4786 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4787                                ArrayRef<int> Mask, MVT VT) {
4788   if (!VT.is128BitVector())
4789     return false;
4790
4791   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4792     return false;
4793   // Is V2 is a vector load, don't do this transformation. We will try to use
4794   // load folding shufps op.
4795   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4796     return false;
4797
4798   unsigned NumElems = VT.getVectorNumElements();
4799
4800   if (NumElems != 2 && NumElems != 4)
4801     return false;
4802   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4803     if (!isUndefOrEqual(Mask[i], i))
4804       return false;
4805   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4806     if (!isUndefOrEqual(Mask[i], i+NumElems))
4807       return false;
4808   return true;
4809 }
4810
4811 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4812 /// all the same.
4813 static bool isSplatVector(SDNode *N) {
4814   if (N->getOpcode() != ISD::BUILD_VECTOR)
4815     return false;
4816
4817   SDValue SplatValue = N->getOperand(0);
4818   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4819     if (N->getOperand(i) != SplatValue)
4820       return false;
4821   return true;
4822 }
4823
4824 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4825 /// to an zero vector.
4826 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4827 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4828   SDValue V1 = N->getOperand(0);
4829   SDValue V2 = N->getOperand(1);
4830   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4831   for (unsigned i = 0; i != NumElems; ++i) {
4832     int Idx = N->getMaskElt(i);
4833     if (Idx >= (int)NumElems) {
4834       unsigned Opc = V2.getOpcode();
4835       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4836         continue;
4837       if (Opc != ISD::BUILD_VECTOR ||
4838           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4839         return false;
4840     } else if (Idx >= 0) {
4841       unsigned Opc = V1.getOpcode();
4842       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4843         continue;
4844       if (Opc != ISD::BUILD_VECTOR ||
4845           !X86::isZeroNode(V1.getOperand(Idx)))
4846         return false;
4847     }
4848   }
4849   return true;
4850 }
4851
4852 /// getZeroVector - Returns a vector of specified type with all zero elements.
4853 ///
4854 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4855                              SelectionDAG &DAG, SDLoc dl) {
4856   assert(VT.isVector() && "Expected a vector type");
4857
4858   // Always build SSE zero vectors as <4 x i32> bitcasted
4859   // to their dest type. This ensures they get CSE'd.
4860   SDValue Vec;
4861   if (VT.is128BitVector()) {  // SSE
4862     if (Subtarget->hasSSE2()) {  // SSE2
4863       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4864       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4865     } else { // SSE1
4866       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4867       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4868     }
4869   } else if (VT.is256BitVector()) { // AVX
4870     if (Subtarget->hasInt256()) { // AVX2
4871       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4872       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4873       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4874     } else {
4875       // 256-bit logic and arithmetic instructions in AVX are all
4876       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4877       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4878       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4879       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4880     }
4881   } else if (VT.is512BitVector()) { // AVX-512
4882       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4883       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4884                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4885       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4886   } else if (VT.getScalarType() == MVT::i1) {
4887     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4888     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4889     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4890     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4891   } else
4892     llvm_unreachable("Unexpected vector type");
4893
4894   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4895 }
4896
4897 /// getOnesVector - Returns a vector of specified type with all bits set.
4898 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4899 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4900 /// Then bitcast to their original type, ensuring they get CSE'd.
4901 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4902                              SDLoc dl) {
4903   assert(VT.isVector() && "Expected a vector type");
4904
4905   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4906   SDValue Vec;
4907   if (VT.is256BitVector()) {
4908     if (HasInt256) { // AVX2
4909       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4910       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4911     } else { // AVX
4912       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4913       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4914     }
4915   } else if (VT.is128BitVector()) {
4916     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4917   } else
4918     llvm_unreachable("Unexpected vector type");
4919
4920   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4921 }
4922
4923 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4924 /// that point to V2 points to its first element.
4925 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4926   for (unsigned i = 0; i != NumElems; ++i) {
4927     if (Mask[i] > (int)NumElems) {
4928       Mask[i] = NumElems;
4929     }
4930   }
4931 }
4932
4933 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4934 /// operation of specified width.
4935 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4936                        SDValue V2) {
4937   unsigned NumElems = VT.getVectorNumElements();
4938   SmallVector<int, 8> Mask;
4939   Mask.push_back(NumElems);
4940   for (unsigned i = 1; i != NumElems; ++i)
4941     Mask.push_back(i);
4942   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4943 }
4944
4945 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4946 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4947                           SDValue V2) {
4948   unsigned NumElems = VT.getVectorNumElements();
4949   SmallVector<int, 8> Mask;
4950   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4951     Mask.push_back(i);
4952     Mask.push_back(i + NumElems);
4953   }
4954   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4955 }
4956
4957 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4958 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4959                           SDValue V2) {
4960   unsigned NumElems = VT.getVectorNumElements();
4961   SmallVector<int, 8> Mask;
4962   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4963     Mask.push_back(i + Half);
4964     Mask.push_back(i + NumElems + Half);
4965   }
4966   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4967 }
4968
4969 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4970 // a generic shuffle instruction because the target has no such instructions.
4971 // Generate shuffles which repeat i16 and i8 several times until they can be
4972 // represented by v4f32 and then be manipulated by target suported shuffles.
4973 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4974   MVT VT = V.getSimpleValueType();
4975   int NumElems = VT.getVectorNumElements();
4976   SDLoc dl(V);
4977
4978   while (NumElems > 4) {
4979     if (EltNo < NumElems/2) {
4980       V = getUnpackl(DAG, dl, VT, V, V);
4981     } else {
4982       V = getUnpackh(DAG, dl, VT, V, V);
4983       EltNo -= NumElems/2;
4984     }
4985     NumElems >>= 1;
4986   }
4987   return V;
4988 }
4989
4990 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4991 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4992   MVT VT = V.getSimpleValueType();
4993   SDLoc dl(V);
4994
4995   if (VT.is128BitVector()) {
4996     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4997     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4998     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4999                              &SplatMask[0]);
5000   } else if (VT.is256BitVector()) {
5001     // To use VPERMILPS to splat scalars, the second half of indicies must
5002     // refer to the higher part, which is a duplication of the lower one,
5003     // because VPERMILPS can only handle in-lane permutations.
5004     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5005                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5006
5007     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5008     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5009                              &SplatMask[0]);
5010   } else
5011     llvm_unreachable("Vector size not supported");
5012
5013   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5014 }
5015
5016 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5017 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5018   MVT SrcVT = SV->getSimpleValueType(0);
5019   SDValue V1 = SV->getOperand(0);
5020   SDLoc dl(SV);
5021
5022   int EltNo = SV->getSplatIndex();
5023   int NumElems = SrcVT.getVectorNumElements();
5024   bool Is256BitVec = SrcVT.is256BitVector();
5025
5026   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5027          "Unknown how to promote splat for type");
5028
5029   // Extract the 128-bit part containing the splat element and update
5030   // the splat element index when it refers to the higher register.
5031   if (Is256BitVec) {
5032     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5033     if (EltNo >= NumElems/2)
5034       EltNo -= NumElems/2;
5035   }
5036
5037   // All i16 and i8 vector types can't be used directly by a generic shuffle
5038   // instruction because the target has no such instruction. Generate shuffles
5039   // which repeat i16 and i8 several times until they fit in i32, and then can
5040   // be manipulated by target suported shuffles.
5041   MVT EltVT = SrcVT.getVectorElementType();
5042   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5043     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5044
5045   // Recreate the 256-bit vector and place the same 128-bit vector
5046   // into the low and high part. This is necessary because we want
5047   // to use VPERM* to shuffle the vectors
5048   if (Is256BitVec) {
5049     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5050   }
5051
5052   return getLegalSplat(DAG, V1, EltNo);
5053 }
5054
5055 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5056 /// vector of zero or undef vector.  This produces a shuffle where the low
5057 /// element of V2 is swizzled into the zero/undef vector, landing at element
5058 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5059 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5060                                            bool IsZero,
5061                                            const X86Subtarget *Subtarget,
5062                                            SelectionDAG &DAG) {
5063   MVT VT = V2.getSimpleValueType();
5064   SDValue V1 = IsZero
5065     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5066   unsigned NumElems = VT.getVectorNumElements();
5067   SmallVector<int, 16> MaskVec;
5068   for (unsigned i = 0; i != NumElems; ++i)
5069     // If this is the insertion idx, put the low elt of V2 here.
5070     MaskVec.push_back(i == Idx ? NumElems : i);
5071   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5072 }
5073
5074 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5075 /// target specific opcode. Returns true if the Mask could be calculated.
5076 /// Sets IsUnary to true if only uses one source.
5077 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5078                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5079   unsigned NumElems = VT.getVectorNumElements();
5080   SDValue ImmN;
5081
5082   IsUnary = false;
5083   switch(N->getOpcode()) {
5084   case X86ISD::SHUFP:
5085     ImmN = N->getOperand(N->getNumOperands()-1);
5086     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5087     break;
5088   case X86ISD::UNPCKH:
5089     DecodeUNPCKHMask(VT, Mask);
5090     break;
5091   case X86ISD::UNPCKL:
5092     DecodeUNPCKLMask(VT, Mask);
5093     break;
5094   case X86ISD::MOVHLPS:
5095     DecodeMOVHLPSMask(NumElems, Mask);
5096     break;
5097   case X86ISD::MOVLHPS:
5098     DecodeMOVLHPSMask(NumElems, Mask);
5099     break;
5100   case X86ISD::PALIGNR:
5101     ImmN = N->getOperand(N->getNumOperands()-1);
5102     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5103     break;
5104   case X86ISD::PSHUFD:
5105   case X86ISD::VPERMILP:
5106     ImmN = N->getOperand(N->getNumOperands()-1);
5107     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5108     IsUnary = true;
5109     break;
5110   case X86ISD::PSHUFHW:
5111     ImmN = N->getOperand(N->getNumOperands()-1);
5112     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5113     IsUnary = true;
5114     break;
5115   case X86ISD::PSHUFLW:
5116     ImmN = N->getOperand(N->getNumOperands()-1);
5117     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5118     IsUnary = true;
5119     break;
5120   case X86ISD::VPERMI:
5121     ImmN = N->getOperand(N->getNumOperands()-1);
5122     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5123     IsUnary = true;
5124     break;
5125   case X86ISD::MOVSS:
5126   case X86ISD::MOVSD: {
5127     // The index 0 always comes from the first element of the second source,
5128     // this is why MOVSS and MOVSD are used in the first place. The other
5129     // elements come from the other positions of the first source vector
5130     Mask.push_back(NumElems);
5131     for (unsigned i = 1; i != NumElems; ++i) {
5132       Mask.push_back(i);
5133     }
5134     break;
5135   }
5136   case X86ISD::VPERM2X128:
5137     ImmN = N->getOperand(N->getNumOperands()-1);
5138     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5139     if (Mask.empty()) return false;
5140     break;
5141   case X86ISD::MOVDDUP:
5142   case X86ISD::MOVLHPD:
5143   case X86ISD::MOVLPD:
5144   case X86ISD::MOVLPS:
5145   case X86ISD::MOVSHDUP:
5146   case X86ISD::MOVSLDUP:
5147     // Not yet implemented
5148     return false;
5149   default: llvm_unreachable("unknown target shuffle node");
5150   }
5151
5152   return true;
5153 }
5154
5155 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5156 /// element of the result of the vector shuffle.
5157 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5158                                    unsigned Depth) {
5159   if (Depth == 6)
5160     return SDValue();  // Limit search depth.
5161
5162   SDValue V = SDValue(N, 0);
5163   EVT VT = V.getValueType();
5164   unsigned Opcode = V.getOpcode();
5165
5166   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5167   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5168     int Elt = SV->getMaskElt(Index);
5169
5170     if (Elt < 0)
5171       return DAG.getUNDEF(VT.getVectorElementType());
5172
5173     unsigned NumElems = VT.getVectorNumElements();
5174     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5175                                          : SV->getOperand(1);
5176     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5177   }
5178
5179   // Recurse into target specific vector shuffles to find scalars.
5180   if (isTargetShuffle(Opcode)) {
5181     MVT ShufVT = V.getSimpleValueType();
5182     unsigned NumElems = ShufVT.getVectorNumElements();
5183     SmallVector<int, 16> ShuffleMask;
5184     bool IsUnary;
5185
5186     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5187       return SDValue();
5188
5189     int Elt = ShuffleMask[Index];
5190     if (Elt < 0)
5191       return DAG.getUNDEF(ShufVT.getVectorElementType());
5192
5193     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5194                                          : N->getOperand(1);
5195     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5196                                Depth+1);
5197   }
5198
5199   // Actual nodes that may contain scalar elements
5200   if (Opcode == ISD::BITCAST) {
5201     V = V.getOperand(0);
5202     EVT SrcVT = V.getValueType();
5203     unsigned NumElems = VT.getVectorNumElements();
5204
5205     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5206       return SDValue();
5207   }
5208
5209   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5210     return (Index == 0) ? V.getOperand(0)
5211                         : DAG.getUNDEF(VT.getVectorElementType());
5212
5213   if (V.getOpcode() == ISD::BUILD_VECTOR)
5214     return V.getOperand(Index);
5215
5216   return SDValue();
5217 }
5218
5219 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5220 /// shuffle operation which come from a consecutively from a zero. The
5221 /// search can start in two different directions, from left or right.
5222 /// We count undefs as zeros until PreferredNum is reached.
5223 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5224                                          unsigned NumElems, bool ZerosFromLeft,
5225                                          SelectionDAG &DAG,
5226                                          unsigned PreferredNum = -1U) {
5227   unsigned NumZeros = 0;
5228   for (unsigned i = 0; i != NumElems; ++i) {
5229     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5230     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5231     if (!Elt.getNode())
5232       break;
5233
5234     if (X86::isZeroNode(Elt))
5235       ++NumZeros;
5236     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5237       NumZeros = std::min(NumZeros + 1, PreferredNum);
5238     else
5239       break;
5240   }
5241
5242   return NumZeros;
5243 }
5244
5245 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5246 /// correspond consecutively to elements from one of the vector operands,
5247 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5248 static
5249 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5250                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5251                               unsigned NumElems, unsigned &OpNum) {
5252   bool SeenV1 = false;
5253   bool SeenV2 = false;
5254
5255   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5256     int Idx = SVOp->getMaskElt(i);
5257     // Ignore undef indicies
5258     if (Idx < 0)
5259       continue;
5260
5261     if (Idx < (int)NumElems)
5262       SeenV1 = true;
5263     else
5264       SeenV2 = true;
5265
5266     // Only accept consecutive elements from the same vector
5267     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5268       return false;
5269   }
5270
5271   OpNum = SeenV1 ? 0 : 1;
5272   return true;
5273 }
5274
5275 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5276 /// logical left shift of a vector.
5277 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5278                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5279   unsigned NumElems =
5280     SVOp->getSimpleValueType(0).getVectorNumElements();
5281   unsigned NumZeros = getNumOfConsecutiveZeros(
5282       SVOp, NumElems, false /* check zeros from right */, DAG,
5283       SVOp->getMaskElt(0));
5284   unsigned OpSrc;
5285
5286   if (!NumZeros)
5287     return false;
5288
5289   // Considering the elements in the mask that are not consecutive zeros,
5290   // check if they consecutively come from only one of the source vectors.
5291   //
5292   //               V1 = {X, A, B, C}     0
5293   //                         \  \  \    /
5294   //   vector_shuffle V1, V2 <1, 2, 3, X>
5295   //
5296   if (!isShuffleMaskConsecutive(SVOp,
5297             0,                   // Mask Start Index
5298             NumElems-NumZeros,   // Mask End Index(exclusive)
5299             NumZeros,            // Where to start looking in the src vector
5300             NumElems,            // Number of elements in vector
5301             OpSrc))              // Which source operand ?
5302     return false;
5303
5304   isLeft = false;
5305   ShAmt = NumZeros;
5306   ShVal = SVOp->getOperand(OpSrc);
5307   return true;
5308 }
5309
5310 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5311 /// logical left shift of a vector.
5312 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5313                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5314   unsigned NumElems =
5315     SVOp->getSimpleValueType(0).getVectorNumElements();
5316   unsigned NumZeros = getNumOfConsecutiveZeros(
5317       SVOp, NumElems, true /* check zeros from left */, DAG,
5318       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5319   unsigned OpSrc;
5320
5321   if (!NumZeros)
5322     return false;
5323
5324   // Considering the elements in the mask that are not consecutive zeros,
5325   // check if they consecutively come from only one of the source vectors.
5326   //
5327   //                           0    { A, B, X, X } = V2
5328   //                          / \    /  /
5329   //   vector_shuffle V1, V2 <X, X, 4, 5>
5330   //
5331   if (!isShuffleMaskConsecutive(SVOp,
5332             NumZeros,     // Mask Start Index
5333             NumElems,     // Mask End Index(exclusive)
5334             0,            // Where to start looking in the src vector
5335             NumElems,     // Number of elements in vector
5336             OpSrc))       // Which source operand ?
5337     return false;
5338
5339   isLeft = true;
5340   ShAmt = NumZeros;
5341   ShVal = SVOp->getOperand(OpSrc);
5342   return true;
5343 }
5344
5345 /// isVectorShift - Returns true if the shuffle can be implemented as a
5346 /// logical left or right shift of a vector.
5347 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5348                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5349   // Although the logic below support any bitwidth size, there are no
5350   // shift instructions which handle more than 128-bit vectors.
5351   if (!SVOp->getSimpleValueType(0).is128BitVector())
5352     return false;
5353
5354   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5355       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5356     return true;
5357
5358   return false;
5359 }
5360
5361 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5362 ///
5363 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5364                                        unsigned NumNonZero, unsigned NumZero,
5365                                        SelectionDAG &DAG,
5366                                        const X86Subtarget* Subtarget,
5367                                        const TargetLowering &TLI) {
5368   if (NumNonZero > 8)
5369     return SDValue();
5370
5371   SDLoc dl(Op);
5372   SDValue V;
5373   bool First = true;
5374   for (unsigned i = 0; i < 16; ++i) {
5375     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5376     if (ThisIsNonZero && First) {
5377       if (NumZero)
5378         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5379       else
5380         V = DAG.getUNDEF(MVT::v8i16);
5381       First = false;
5382     }
5383
5384     if ((i & 1) != 0) {
5385       SDValue ThisElt, LastElt;
5386       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5387       if (LastIsNonZero) {
5388         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5389                               MVT::i16, Op.getOperand(i-1));
5390       }
5391       if (ThisIsNonZero) {
5392         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5393         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5394                               ThisElt, DAG.getConstant(8, MVT::i8));
5395         if (LastIsNonZero)
5396           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5397       } else
5398         ThisElt = LastElt;
5399
5400       if (ThisElt.getNode())
5401         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5402                         DAG.getIntPtrConstant(i/2));
5403     }
5404   }
5405
5406   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5407 }
5408
5409 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5410 ///
5411 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5412                                      unsigned NumNonZero, unsigned NumZero,
5413                                      SelectionDAG &DAG,
5414                                      const X86Subtarget* Subtarget,
5415                                      const TargetLowering &TLI) {
5416   if (NumNonZero > 4)
5417     return SDValue();
5418
5419   SDLoc dl(Op);
5420   SDValue V;
5421   bool First = true;
5422   for (unsigned i = 0; i < 8; ++i) {
5423     bool isNonZero = (NonZeros & (1 << i)) != 0;
5424     if (isNonZero) {
5425       if (First) {
5426         if (NumZero)
5427           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5428         else
5429           V = DAG.getUNDEF(MVT::v8i16);
5430         First = false;
5431       }
5432       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5433                       MVT::v8i16, V, Op.getOperand(i),
5434                       DAG.getIntPtrConstant(i));
5435     }
5436   }
5437
5438   return V;
5439 }
5440
5441 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5442 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5443                                      unsigned NonZeros, unsigned NumNonZero,
5444                                      unsigned NumZero, SelectionDAG &DAG,
5445                                      const X86Subtarget *Subtarget,
5446                                      const TargetLowering &TLI) {
5447   // We know there's at least one non-zero element
5448   unsigned FirstNonZeroIdx = 0;
5449   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5450   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5451          X86::isZeroNode(FirstNonZero)) {
5452     ++FirstNonZeroIdx;
5453     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5454   }
5455
5456   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5457       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5458     return SDValue();
5459
5460   SDValue V = FirstNonZero.getOperand(0);
5461   MVT VVT = V.getSimpleValueType();
5462   if (VVT != MVT::v4f32 && VVT != MVT::v4i32)
5463     return SDValue();
5464
5465   unsigned FirstNonZeroDst =
5466       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5467   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5468   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5469   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5470
5471   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5472     SDValue Elem = Op.getOperand(Idx);
5473     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5474       continue;
5475
5476     // TODO: What else can be here? Deal with it.
5477     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5478       return SDValue();
5479
5480     // TODO: Some optimizations are still possible here
5481     // ex: Getting one element from a vector, and the rest from another.
5482     if (Elem.getOperand(0) != V)
5483       return SDValue();
5484
5485     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5486     if (Dst == Idx)
5487       ++CorrectIdx;
5488     else if (IncorrectIdx == -1U) {
5489       IncorrectIdx = Idx;
5490       IncorrectDst = Dst;
5491     } else
5492       // There was already one element with an incorrect index.
5493       // We can't optimize this case to an insertps.
5494       return SDValue();
5495   }
5496
5497   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5498     SDLoc dl(Op);
5499     EVT VT = Op.getSimpleValueType();
5500     unsigned ElementMoveMask = 0;
5501     if (IncorrectIdx == -1U)
5502       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5503     else
5504       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5505
5506     SDValue InsertpsMask =
5507         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5508     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5509   }
5510
5511   return SDValue();
5512 }
5513
5514 /// getVShift - Return a vector logical shift node.
5515 ///
5516 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5517                          unsigned NumBits, SelectionDAG &DAG,
5518                          const TargetLowering &TLI, SDLoc dl) {
5519   assert(VT.is128BitVector() && "Unknown type for VShift");
5520   EVT ShVT = MVT::v2i64;
5521   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5522   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5523   return DAG.getNode(ISD::BITCAST, dl, VT,
5524                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5525                              DAG.getConstant(NumBits,
5526                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5527 }
5528
5529 static SDValue
5530 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5531
5532   // Check if the scalar load can be widened into a vector load. And if
5533   // the address is "base + cst" see if the cst can be "absorbed" into
5534   // the shuffle mask.
5535   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5536     SDValue Ptr = LD->getBasePtr();
5537     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5538       return SDValue();
5539     EVT PVT = LD->getValueType(0);
5540     if (PVT != MVT::i32 && PVT != MVT::f32)
5541       return SDValue();
5542
5543     int FI = -1;
5544     int64_t Offset = 0;
5545     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5546       FI = FINode->getIndex();
5547       Offset = 0;
5548     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5549                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5550       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5551       Offset = Ptr.getConstantOperandVal(1);
5552       Ptr = Ptr.getOperand(0);
5553     } else {
5554       return SDValue();
5555     }
5556
5557     // FIXME: 256-bit vector instructions don't require a strict alignment,
5558     // improve this code to support it better.
5559     unsigned RequiredAlign = VT.getSizeInBits()/8;
5560     SDValue Chain = LD->getChain();
5561     // Make sure the stack object alignment is at least 16 or 32.
5562     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5563     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5564       if (MFI->isFixedObjectIndex(FI)) {
5565         // Can't change the alignment. FIXME: It's possible to compute
5566         // the exact stack offset and reference FI + adjust offset instead.
5567         // If someone *really* cares about this. That's the way to implement it.
5568         return SDValue();
5569       } else {
5570         MFI->setObjectAlignment(FI, RequiredAlign);
5571       }
5572     }
5573
5574     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5575     // Ptr + (Offset & ~15).
5576     if (Offset < 0)
5577       return SDValue();
5578     if ((Offset % RequiredAlign) & 3)
5579       return SDValue();
5580     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5581     if (StartOffset)
5582       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5583                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5584
5585     int EltNo = (Offset - StartOffset) >> 2;
5586     unsigned NumElems = VT.getVectorNumElements();
5587
5588     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5589     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5590                              LD->getPointerInfo().getWithOffset(StartOffset),
5591                              false, false, false, 0);
5592
5593     SmallVector<int, 8> Mask;
5594     for (unsigned i = 0; i != NumElems; ++i)
5595       Mask.push_back(EltNo);
5596
5597     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5598   }
5599
5600   return SDValue();
5601 }
5602
5603 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5604 /// vector of type 'VT', see if the elements can be replaced by a single large
5605 /// load which has the same value as a build_vector whose operands are 'elts'.
5606 ///
5607 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5608 ///
5609 /// FIXME: we'd also like to handle the case where the last elements are zero
5610 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5611 /// There's even a handy isZeroNode for that purpose.
5612 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5613                                         SDLoc &DL, SelectionDAG &DAG,
5614                                         bool isAfterLegalize) {
5615   EVT EltVT = VT.getVectorElementType();
5616   unsigned NumElems = Elts.size();
5617
5618   LoadSDNode *LDBase = nullptr;
5619   unsigned LastLoadedElt = -1U;
5620
5621   // For each element in the initializer, see if we've found a load or an undef.
5622   // If we don't find an initial load element, or later load elements are
5623   // non-consecutive, bail out.
5624   for (unsigned i = 0; i < NumElems; ++i) {
5625     SDValue Elt = Elts[i];
5626
5627     if (!Elt.getNode() ||
5628         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5629       return SDValue();
5630     if (!LDBase) {
5631       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5632         return SDValue();
5633       LDBase = cast<LoadSDNode>(Elt.getNode());
5634       LastLoadedElt = i;
5635       continue;
5636     }
5637     if (Elt.getOpcode() == ISD::UNDEF)
5638       continue;
5639
5640     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5641     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5642       return SDValue();
5643     LastLoadedElt = i;
5644   }
5645
5646   // If we have found an entire vector of loads and undefs, then return a large
5647   // load of the entire vector width starting at the base pointer.  If we found
5648   // consecutive loads for the low half, generate a vzext_load node.
5649   if (LastLoadedElt == NumElems - 1) {
5650
5651     if (isAfterLegalize &&
5652         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5653       return SDValue();
5654
5655     SDValue NewLd = SDValue();
5656
5657     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5658       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5659                           LDBase->getPointerInfo(),
5660                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5661                           LDBase->isInvariant(), 0);
5662     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5663                         LDBase->getPointerInfo(),
5664                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5665                         LDBase->isInvariant(), LDBase->getAlignment());
5666
5667     if (LDBase->hasAnyUseOfValue(1)) {
5668       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5669                                      SDValue(LDBase, 1),
5670                                      SDValue(NewLd.getNode(), 1));
5671       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5672       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5673                              SDValue(NewLd.getNode(), 1));
5674     }
5675
5676     return NewLd;
5677   }
5678   if (NumElems == 4 && LastLoadedElt == 1 &&
5679       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5680     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5681     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5682     SDValue ResNode =
5683         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5684                                 LDBase->getPointerInfo(),
5685                                 LDBase->getAlignment(),
5686                                 false/*isVolatile*/, true/*ReadMem*/,
5687                                 false/*WriteMem*/);
5688
5689     // Make sure the newly-created LOAD is in the same position as LDBase in
5690     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5691     // update uses of LDBase's output chain to use the TokenFactor.
5692     if (LDBase->hasAnyUseOfValue(1)) {
5693       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5694                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5695       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5696       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5697                              SDValue(ResNode.getNode(), 1));
5698     }
5699
5700     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5701   }
5702   return SDValue();
5703 }
5704
5705 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5706 /// to generate a splat value for the following cases:
5707 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5708 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5709 /// a scalar load, or a constant.
5710 /// The VBROADCAST node is returned when a pattern is found,
5711 /// or SDValue() otherwise.
5712 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5713                                     SelectionDAG &DAG) {
5714   if (!Subtarget->hasFp256())
5715     return SDValue();
5716
5717   MVT VT = Op.getSimpleValueType();
5718   SDLoc dl(Op);
5719
5720   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5721          "Unsupported vector type for broadcast.");
5722
5723   SDValue Ld;
5724   bool ConstSplatVal;
5725
5726   switch (Op.getOpcode()) {
5727     default:
5728       // Unknown pattern found.
5729       return SDValue();
5730
5731     case ISD::BUILD_VECTOR: {
5732       // The BUILD_VECTOR node must be a splat.
5733       if (!isSplatVector(Op.getNode()))
5734         return SDValue();
5735
5736       Ld = Op.getOperand(0);
5737       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5738                      Ld.getOpcode() == ISD::ConstantFP);
5739
5740       // The suspected load node has several users. Make sure that all
5741       // of its users are from the BUILD_VECTOR node.
5742       // Constants may have multiple users.
5743       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5744         return SDValue();
5745       break;
5746     }
5747
5748     case ISD::VECTOR_SHUFFLE: {
5749       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5750
5751       // Shuffles must have a splat mask where the first element is
5752       // broadcasted.
5753       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5754         return SDValue();
5755
5756       SDValue Sc = Op.getOperand(0);
5757       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5758           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5759
5760         if (!Subtarget->hasInt256())
5761           return SDValue();
5762
5763         // Use the register form of the broadcast instruction available on AVX2.
5764         if (VT.getSizeInBits() >= 256)
5765           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5766         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5767       }
5768
5769       Ld = Sc.getOperand(0);
5770       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5771                        Ld.getOpcode() == ISD::ConstantFP);
5772
5773       // The scalar_to_vector node and the suspected
5774       // load node must have exactly one user.
5775       // Constants may have multiple users.
5776
5777       // AVX-512 has register version of the broadcast
5778       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5779         Ld.getValueType().getSizeInBits() >= 32;
5780       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5781           !hasRegVer))
5782         return SDValue();
5783       break;
5784     }
5785   }
5786
5787   bool IsGE256 = (VT.getSizeInBits() >= 256);
5788
5789   // Handle the broadcasting a single constant scalar from the constant pool
5790   // into a vector. On Sandybridge it is still better to load a constant vector
5791   // from the constant pool and not to broadcast it from a scalar.
5792   if (ConstSplatVal && Subtarget->hasInt256()) {
5793     EVT CVT = Ld.getValueType();
5794     assert(!CVT.isVector() && "Must not broadcast a vector type");
5795     unsigned ScalarSize = CVT.getSizeInBits();
5796
5797     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5798       const Constant *C = nullptr;
5799       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5800         C = CI->getConstantIntValue();
5801       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5802         C = CF->getConstantFPValue();
5803
5804       assert(C && "Invalid constant type");
5805
5806       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5807       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5808       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5809       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5810                        MachinePointerInfo::getConstantPool(),
5811                        false, false, false, Alignment);
5812
5813       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5814     }
5815   }
5816
5817   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5818   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5819
5820   // Handle AVX2 in-register broadcasts.
5821   if (!IsLoad && Subtarget->hasInt256() &&
5822       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5823     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5824
5825   // The scalar source must be a normal load.
5826   if (!IsLoad)
5827     return SDValue();
5828
5829   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5830     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5831
5832   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5833   // double since there is no vbroadcastsd xmm
5834   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5835     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5836       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5837   }
5838
5839   // Unsupported broadcast.
5840   return SDValue();
5841 }
5842
5843 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5844 /// underlying vector and index.
5845 ///
5846 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5847 /// index.
5848 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5849                                          SDValue ExtIdx) {
5850   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5851   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5852     return Idx;
5853
5854   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5855   // lowered this:
5856   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5857   // to:
5858   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5859   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5860   //                           undef)
5861   //                       Constant<0>)
5862   // In this case the vector is the extract_subvector expression and the index
5863   // is 2, as specified by the shuffle.
5864   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5865   SDValue ShuffleVec = SVOp->getOperand(0);
5866   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5867   assert(ShuffleVecVT.getVectorElementType() ==
5868          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5869
5870   int ShuffleIdx = SVOp->getMaskElt(Idx);
5871   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5872     ExtractedFromVec = ShuffleVec;
5873     return ShuffleIdx;
5874   }
5875   return Idx;
5876 }
5877
5878 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5879   MVT VT = Op.getSimpleValueType();
5880
5881   // Skip if insert_vec_elt is not supported.
5882   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5883   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5884     return SDValue();
5885
5886   SDLoc DL(Op);
5887   unsigned NumElems = Op.getNumOperands();
5888
5889   SDValue VecIn1;
5890   SDValue VecIn2;
5891   SmallVector<unsigned, 4> InsertIndices;
5892   SmallVector<int, 8> Mask(NumElems, -1);
5893
5894   for (unsigned i = 0; i != NumElems; ++i) {
5895     unsigned Opc = Op.getOperand(i).getOpcode();
5896
5897     if (Opc == ISD::UNDEF)
5898       continue;
5899
5900     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5901       // Quit if more than 1 elements need inserting.
5902       if (InsertIndices.size() > 1)
5903         return SDValue();
5904
5905       InsertIndices.push_back(i);
5906       continue;
5907     }
5908
5909     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5910     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5911     // Quit if non-constant index.
5912     if (!isa<ConstantSDNode>(ExtIdx))
5913       return SDValue();
5914     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5915
5916     // Quit if extracted from vector of different type.
5917     if (ExtractedFromVec.getValueType() != VT)
5918       return SDValue();
5919
5920     if (!VecIn1.getNode())
5921       VecIn1 = ExtractedFromVec;
5922     else if (VecIn1 != ExtractedFromVec) {
5923       if (!VecIn2.getNode())
5924         VecIn2 = ExtractedFromVec;
5925       else if (VecIn2 != ExtractedFromVec)
5926         // Quit if more than 2 vectors to shuffle
5927         return SDValue();
5928     }
5929
5930     if (ExtractedFromVec == VecIn1)
5931       Mask[i] = Idx;
5932     else if (ExtractedFromVec == VecIn2)
5933       Mask[i] = Idx + NumElems;
5934   }
5935
5936   if (!VecIn1.getNode())
5937     return SDValue();
5938
5939   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5940   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5941   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5942     unsigned Idx = InsertIndices[i];
5943     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5944                      DAG.getIntPtrConstant(Idx));
5945   }
5946
5947   return NV;
5948 }
5949
5950 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5951 SDValue
5952 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5953
5954   MVT VT = Op.getSimpleValueType();
5955   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5956          "Unexpected type in LowerBUILD_VECTORvXi1!");
5957
5958   SDLoc dl(Op);
5959   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5960     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5961     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5962     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5963   }
5964
5965   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5966     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5967     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5968     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5969   }
5970
5971   bool AllContants = true;
5972   uint64_t Immediate = 0;
5973   int NonConstIdx = -1;
5974   bool IsSplat = true;
5975   unsigned NumNonConsts = 0;
5976   unsigned NumConsts = 0;
5977   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5978     SDValue In = Op.getOperand(idx);
5979     if (In.getOpcode() == ISD::UNDEF)
5980       continue;
5981     if (!isa<ConstantSDNode>(In)) {
5982       AllContants = false;
5983       NonConstIdx = idx;
5984       NumNonConsts++;
5985     }
5986     else {
5987       NumConsts++;
5988       if (cast<ConstantSDNode>(In)->getZExtValue())
5989       Immediate |= (1ULL << idx);
5990     }
5991     if (In != Op.getOperand(0))
5992       IsSplat = false;
5993   }
5994
5995   if (AllContants) {
5996     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5997       DAG.getConstant(Immediate, MVT::i16));
5998     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5999                        DAG.getIntPtrConstant(0));
6000   }
6001
6002   if (NumNonConsts == 1 && NonConstIdx != 0) {
6003     SDValue DstVec;
6004     if (NumConsts) {
6005       SDValue VecAsImm = DAG.getConstant(Immediate,
6006                                          MVT::getIntegerVT(VT.getSizeInBits()));
6007       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6008     }
6009     else 
6010       DstVec = DAG.getUNDEF(VT);
6011     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6012                        Op.getOperand(NonConstIdx),
6013                        DAG.getIntPtrConstant(NonConstIdx));
6014   }
6015   if (!IsSplat && (NonConstIdx != 0))
6016     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6017   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6018   SDValue Select;
6019   if (IsSplat)
6020     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6021                           DAG.getConstant(-1, SelectVT),
6022                           DAG.getConstant(0, SelectVT));
6023   else
6024     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6025                          DAG.getConstant((Immediate | 1), SelectVT),
6026                          DAG.getConstant(Immediate, SelectVT));
6027   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6028 }
6029
6030 SDValue
6031 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6032   SDLoc dl(Op);
6033
6034   MVT VT = Op.getSimpleValueType();
6035   MVT ExtVT = VT.getVectorElementType();
6036   unsigned NumElems = Op.getNumOperands();
6037
6038   // Generate vectors for predicate vectors.
6039   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6040     return LowerBUILD_VECTORvXi1(Op, DAG);
6041
6042   // Vectors containing all zeros can be matched by pxor and xorps later
6043   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6044     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6045     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6046     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6047       return Op;
6048
6049     return getZeroVector(VT, Subtarget, DAG, dl);
6050   }
6051
6052   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6053   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6054   // vpcmpeqd on 256-bit vectors.
6055   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6056     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6057       return Op;
6058
6059     if (!VT.is512BitVector())
6060       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6061   }
6062
6063   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6064   if (Broadcast.getNode())
6065     return Broadcast;
6066
6067   unsigned EVTBits = ExtVT.getSizeInBits();
6068
6069   unsigned NumZero  = 0;
6070   unsigned NumNonZero = 0;
6071   unsigned NonZeros = 0;
6072   bool IsAllConstants = true;
6073   SmallSet<SDValue, 8> Values;
6074   for (unsigned i = 0; i < NumElems; ++i) {
6075     SDValue Elt = Op.getOperand(i);
6076     if (Elt.getOpcode() == ISD::UNDEF)
6077       continue;
6078     Values.insert(Elt);
6079     if (Elt.getOpcode() != ISD::Constant &&
6080         Elt.getOpcode() != ISD::ConstantFP)
6081       IsAllConstants = false;
6082     if (X86::isZeroNode(Elt))
6083       NumZero++;
6084     else {
6085       NonZeros |= (1 << i);
6086       NumNonZero++;
6087     }
6088   }
6089
6090   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6091   if (NumNonZero == 0)
6092     return DAG.getUNDEF(VT);
6093
6094   // Special case for single non-zero, non-undef, element.
6095   if (NumNonZero == 1) {
6096     unsigned Idx = countTrailingZeros(NonZeros);
6097     SDValue Item = Op.getOperand(Idx);
6098
6099     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6100     // the value are obviously zero, truncate the value to i32 and do the
6101     // insertion that way.  Only do this if the value is non-constant or if the
6102     // value is a constant being inserted into element 0.  It is cheaper to do
6103     // a constant pool load than it is to do a movd + shuffle.
6104     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6105         (!IsAllConstants || Idx == 0)) {
6106       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6107         // Handle SSE only.
6108         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6109         EVT VecVT = MVT::v4i32;
6110         unsigned VecElts = 4;
6111
6112         // Truncate the value (which may itself be a constant) to i32, and
6113         // convert it to a vector with movd (S2V+shuffle to zero extend).
6114         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6115         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6116         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6117
6118         // Now we have our 32-bit value zero extended in the low element of
6119         // a vector.  If Idx != 0, swizzle it into place.
6120         if (Idx != 0) {
6121           SmallVector<int, 4> Mask;
6122           Mask.push_back(Idx);
6123           for (unsigned i = 1; i != VecElts; ++i)
6124             Mask.push_back(i);
6125           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6126                                       &Mask[0]);
6127         }
6128         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6129       }
6130     }
6131
6132     // If we have a constant or non-constant insertion into the low element of
6133     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6134     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6135     // depending on what the source datatype is.
6136     if (Idx == 0) {
6137       if (NumZero == 0)
6138         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6139
6140       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6141           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6142         if (VT.is256BitVector() || VT.is512BitVector()) {
6143           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6144           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6145                              Item, DAG.getIntPtrConstant(0));
6146         }
6147         assert(VT.is128BitVector() && "Expected an SSE value type!");
6148         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6149         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6150         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6151       }
6152
6153       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6154         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6155         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6156         if (VT.is256BitVector()) {
6157           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6158           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6159         } else {
6160           assert(VT.is128BitVector() && "Expected an SSE value type!");
6161           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6162         }
6163         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6164       }
6165     }
6166
6167     // Is it a vector logical left shift?
6168     if (NumElems == 2 && Idx == 1 &&
6169         X86::isZeroNode(Op.getOperand(0)) &&
6170         !X86::isZeroNode(Op.getOperand(1))) {
6171       unsigned NumBits = VT.getSizeInBits();
6172       return getVShift(true, VT,
6173                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6174                                    VT, Op.getOperand(1)),
6175                        NumBits/2, DAG, *this, dl);
6176     }
6177
6178     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6179       return SDValue();
6180
6181     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6182     // is a non-constant being inserted into an element other than the low one,
6183     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6184     // movd/movss) to move this into the low element, then shuffle it into
6185     // place.
6186     if (EVTBits == 32) {
6187       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6188
6189       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6190       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6191       SmallVector<int, 8> MaskVec;
6192       for (unsigned i = 0; i != NumElems; ++i)
6193         MaskVec.push_back(i == Idx ? 0 : 1);
6194       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6195     }
6196   }
6197
6198   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6199   if (Values.size() == 1) {
6200     if (EVTBits == 32) {
6201       // Instead of a shuffle like this:
6202       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6203       // Check if it's possible to issue this instead.
6204       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6205       unsigned Idx = countTrailingZeros(NonZeros);
6206       SDValue Item = Op.getOperand(Idx);
6207       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6208         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6209     }
6210     return SDValue();
6211   }
6212
6213   // A vector full of immediates; various special cases are already
6214   // handled, so this is best done with a single constant-pool load.
6215   if (IsAllConstants)
6216     return SDValue();
6217
6218   // For AVX-length vectors, build the individual 128-bit pieces and use
6219   // shuffles to put them in place.
6220   if (VT.is256BitVector() || VT.is512BitVector()) {
6221     SmallVector<SDValue, 64> V;
6222     for (unsigned i = 0; i != NumElems; ++i)
6223       V.push_back(Op.getOperand(i));
6224
6225     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6226
6227     // Build both the lower and upper subvector.
6228     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6229                                 makeArrayRef(&V[0], NumElems/2));
6230     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6231                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6232
6233     // Recreate the wider vector with the lower and upper part.
6234     if (VT.is256BitVector())
6235       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6236     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6237   }
6238
6239   // Let legalizer expand 2-wide build_vectors.
6240   if (EVTBits == 64) {
6241     if (NumNonZero == 1) {
6242       // One half is zero or undef.
6243       unsigned Idx = countTrailingZeros(NonZeros);
6244       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6245                                  Op.getOperand(Idx));
6246       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6247     }
6248     return SDValue();
6249   }
6250
6251   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6252   if (EVTBits == 8 && NumElems == 16) {
6253     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6254                                         Subtarget, *this);
6255     if (V.getNode()) return V;
6256   }
6257
6258   if (EVTBits == 16 && NumElems == 8) {
6259     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6260                                       Subtarget, *this);
6261     if (V.getNode()) return V;
6262   }
6263
6264   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6265   if (EVTBits == 32 && NumElems == 4) {
6266     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6267                                       NumZero, DAG, Subtarget, *this);
6268     if (V.getNode())
6269       return V;
6270   }
6271
6272   // If element VT is == 32 bits, turn it into a number of shuffles.
6273   SmallVector<SDValue, 8> V(NumElems);
6274   if (NumElems == 4 && NumZero > 0) {
6275     for (unsigned i = 0; i < 4; ++i) {
6276       bool isZero = !(NonZeros & (1 << i));
6277       if (isZero)
6278         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6279       else
6280         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6281     }
6282
6283     for (unsigned i = 0; i < 2; ++i) {
6284       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6285         default: break;
6286         case 0:
6287           V[i] = V[i*2];  // Must be a zero vector.
6288           break;
6289         case 1:
6290           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6291           break;
6292         case 2:
6293           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6294           break;
6295         case 3:
6296           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6297           break;
6298       }
6299     }
6300
6301     bool Reverse1 = (NonZeros & 0x3) == 2;
6302     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6303     int MaskVec[] = {
6304       Reverse1 ? 1 : 0,
6305       Reverse1 ? 0 : 1,
6306       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6307       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6308     };
6309     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6310   }
6311
6312   if (Values.size() > 1 && VT.is128BitVector()) {
6313     // Check for a build vector of consecutive loads.
6314     for (unsigned i = 0; i < NumElems; ++i)
6315       V[i] = Op.getOperand(i);
6316
6317     // Check for elements which are consecutive loads.
6318     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6319     if (LD.getNode())
6320       return LD;
6321
6322     // Check for a build vector from mostly shuffle plus few inserting.
6323     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6324     if (Sh.getNode())
6325       return Sh;
6326
6327     // For SSE 4.1, use insertps to put the high elements into the low element.
6328     if (getSubtarget()->hasSSE41()) {
6329       SDValue Result;
6330       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6331         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6332       else
6333         Result = DAG.getUNDEF(VT);
6334
6335       for (unsigned i = 1; i < NumElems; ++i) {
6336         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6337         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6338                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6339       }
6340       return Result;
6341     }
6342
6343     // Otherwise, expand into a number of unpckl*, start by extending each of
6344     // our (non-undef) elements to the full vector width with the element in the
6345     // bottom slot of the vector (which generates no code for SSE).
6346     for (unsigned i = 0; i < NumElems; ++i) {
6347       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6348         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6349       else
6350         V[i] = DAG.getUNDEF(VT);
6351     }
6352
6353     // Next, we iteratively mix elements, e.g. for v4f32:
6354     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6355     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6356     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6357     unsigned EltStride = NumElems >> 1;
6358     while (EltStride != 0) {
6359       for (unsigned i = 0; i < EltStride; ++i) {
6360         // If V[i+EltStride] is undef and this is the first round of mixing,
6361         // then it is safe to just drop this shuffle: V[i] is already in the
6362         // right place, the one element (since it's the first round) being
6363         // inserted as undef can be dropped.  This isn't safe for successive
6364         // rounds because they will permute elements within both vectors.
6365         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6366             EltStride == NumElems/2)
6367           continue;
6368
6369         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6370       }
6371       EltStride >>= 1;
6372     }
6373     return V[0];
6374   }
6375   return SDValue();
6376 }
6377
6378 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6379 // to create 256-bit vectors from two other 128-bit ones.
6380 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6381   SDLoc dl(Op);
6382   MVT ResVT = Op.getSimpleValueType();
6383
6384   assert((ResVT.is256BitVector() ||
6385           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6386
6387   SDValue V1 = Op.getOperand(0);
6388   SDValue V2 = Op.getOperand(1);
6389   unsigned NumElems = ResVT.getVectorNumElements();
6390   if(ResVT.is256BitVector())
6391     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6392
6393   if (Op.getNumOperands() == 4) {
6394     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6395                                 ResVT.getVectorNumElements()/2);
6396     SDValue V3 = Op.getOperand(2);
6397     SDValue V4 = Op.getOperand(3);
6398     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6399       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6400   }
6401   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6402 }
6403
6404 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6405   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6406   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6407          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6408           Op.getNumOperands() == 4)));
6409
6410   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6411   // from two other 128-bit ones.
6412
6413   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6414   return LowerAVXCONCAT_VECTORS(Op, DAG);
6415 }
6416
6417 // Try to lower a shuffle node into a simple blend instruction.
6418 static SDValue
6419 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6420                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6421   SDValue V1 = SVOp->getOperand(0);
6422   SDValue V2 = SVOp->getOperand(1);
6423   SDLoc dl(SVOp);
6424   MVT VT = SVOp->getSimpleValueType(0);
6425   MVT EltVT = VT.getVectorElementType();
6426   unsigned NumElems = VT.getVectorNumElements();
6427
6428   // There is no blend with immediate in AVX-512.
6429   if (VT.is512BitVector())
6430     return SDValue();
6431
6432   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6433     return SDValue();
6434   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6435     return SDValue();
6436
6437   // Check the mask for BLEND and build the value.
6438   unsigned MaskValue = 0;
6439   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6440   unsigned NumLanes = (NumElems-1)/8 + 1;
6441   unsigned NumElemsInLane = NumElems / NumLanes;
6442
6443   // Blend for v16i16 should be symetric for the both lanes.
6444   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6445
6446     int SndLaneEltIdx = (NumLanes == 2) ?
6447       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6448     int EltIdx = SVOp->getMaskElt(i);
6449
6450     if ((EltIdx < 0 || EltIdx == (int)i) &&
6451         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6452       continue;
6453
6454     if (((unsigned)EltIdx == (i + NumElems)) &&
6455         (SndLaneEltIdx < 0 ||
6456          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6457       MaskValue |= (1<<i);
6458     else
6459       return SDValue();
6460   }
6461
6462   // Convert i32 vectors to floating point if it is not AVX2.
6463   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6464   MVT BlendVT = VT;
6465   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6466     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6467                                NumElems);
6468     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6469     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6470   }
6471
6472   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6473                             DAG.getConstant(MaskValue, MVT::i32));
6474   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6475 }
6476
6477 /// In vector type \p VT, return true if the element at index \p InputIdx
6478 /// falls on a different 128-bit lane than \p OutputIdx.
6479 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6480                                      unsigned OutputIdx) {
6481   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6482   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6483 }
6484
6485 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6486 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6487 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6488 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6489 /// zero.
6490 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6491                          SelectionDAG &DAG) {
6492   MVT VT = V1.getSimpleValueType();
6493   assert(VT.is128BitVector() || VT.is256BitVector());
6494
6495   MVT EltVT = VT.getVectorElementType();
6496   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6497   unsigned NumElts = VT.getVectorNumElements();
6498
6499   SmallVector<SDValue, 32> PshufbMask;
6500   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6501     int InputIdx = MaskVals[OutputIdx];
6502     unsigned InputByteIdx;
6503
6504     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6505       InputByteIdx = 0x80;
6506     else {
6507       // Cross lane is not allowed.
6508       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6509         return SDValue();
6510       InputByteIdx = InputIdx * EltSizeInBytes;
6511       // Index is an byte offset within the 128-bit lane.
6512       InputByteIdx &= 0xf;
6513     }
6514
6515     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6516       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6517       if (InputByteIdx != 0x80)
6518         ++InputByteIdx;
6519     }
6520   }
6521
6522   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6523   if (ShufVT != VT)
6524     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6525   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6526                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6527 }
6528
6529 // v8i16 shuffles - Prefer shuffles in the following order:
6530 // 1. [all]   pshuflw, pshufhw, optional move
6531 // 2. [ssse3] 1 x pshufb
6532 // 3. [ssse3] 2 x pshufb + 1 x por
6533 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6534 static SDValue
6535 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6536                          SelectionDAG &DAG) {
6537   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6538   SDValue V1 = SVOp->getOperand(0);
6539   SDValue V2 = SVOp->getOperand(1);
6540   SDLoc dl(SVOp);
6541   SmallVector<int, 8> MaskVals;
6542
6543   // Determine if more than 1 of the words in each of the low and high quadwords
6544   // of the result come from the same quadword of one of the two inputs.  Undef
6545   // mask values count as coming from any quadword, for better codegen.
6546   //
6547   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6548   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6549   unsigned LoQuad[] = { 0, 0, 0, 0 };
6550   unsigned HiQuad[] = { 0, 0, 0, 0 };
6551   // Indices of quads used.
6552   std::bitset<4> InputQuads;
6553   for (unsigned i = 0; i < 8; ++i) {
6554     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6555     int EltIdx = SVOp->getMaskElt(i);
6556     MaskVals.push_back(EltIdx);
6557     if (EltIdx < 0) {
6558       ++Quad[0];
6559       ++Quad[1];
6560       ++Quad[2];
6561       ++Quad[3];
6562       continue;
6563     }
6564     ++Quad[EltIdx / 4];
6565     InputQuads.set(EltIdx / 4);
6566   }
6567
6568   int BestLoQuad = -1;
6569   unsigned MaxQuad = 1;
6570   for (unsigned i = 0; i < 4; ++i) {
6571     if (LoQuad[i] > MaxQuad) {
6572       BestLoQuad = i;
6573       MaxQuad = LoQuad[i];
6574     }
6575   }
6576
6577   int BestHiQuad = -1;
6578   MaxQuad = 1;
6579   for (unsigned i = 0; i < 4; ++i) {
6580     if (HiQuad[i] > MaxQuad) {
6581       BestHiQuad = i;
6582       MaxQuad = HiQuad[i];
6583     }
6584   }
6585
6586   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6587   // of the two input vectors, shuffle them into one input vector so only a
6588   // single pshufb instruction is necessary. If there are more than 2 input
6589   // quads, disable the next transformation since it does not help SSSE3.
6590   bool V1Used = InputQuads[0] || InputQuads[1];
6591   bool V2Used = InputQuads[2] || InputQuads[3];
6592   if (Subtarget->hasSSSE3()) {
6593     if (InputQuads.count() == 2 && V1Used && V2Used) {
6594       BestLoQuad = InputQuads[0] ? 0 : 1;
6595       BestHiQuad = InputQuads[2] ? 2 : 3;
6596     }
6597     if (InputQuads.count() > 2) {
6598       BestLoQuad = -1;
6599       BestHiQuad = -1;
6600     }
6601   }
6602
6603   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6604   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6605   // words from all 4 input quadwords.
6606   SDValue NewV;
6607   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6608     int MaskV[] = {
6609       BestLoQuad < 0 ? 0 : BestLoQuad,
6610       BestHiQuad < 0 ? 1 : BestHiQuad
6611     };
6612     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6613                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6614                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6615     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6616
6617     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6618     // source words for the shuffle, to aid later transformations.
6619     bool AllWordsInNewV = true;
6620     bool InOrder[2] = { true, true };
6621     for (unsigned i = 0; i != 8; ++i) {
6622       int idx = MaskVals[i];
6623       if (idx != (int)i)
6624         InOrder[i/4] = false;
6625       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6626         continue;
6627       AllWordsInNewV = false;
6628       break;
6629     }
6630
6631     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6632     if (AllWordsInNewV) {
6633       for (int i = 0; i != 8; ++i) {
6634         int idx = MaskVals[i];
6635         if (idx < 0)
6636           continue;
6637         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6638         if ((idx != i) && idx < 4)
6639           pshufhw = false;
6640         if ((idx != i) && idx > 3)
6641           pshuflw = false;
6642       }
6643       V1 = NewV;
6644       V2Used = false;
6645       BestLoQuad = 0;
6646       BestHiQuad = 1;
6647     }
6648
6649     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6650     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6651     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6652       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6653       unsigned TargetMask = 0;
6654       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6655                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6656       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6657       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6658                              getShufflePSHUFLWImmediate(SVOp);
6659       V1 = NewV.getOperand(0);
6660       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6661     }
6662   }
6663
6664   // Promote splats to a larger type which usually leads to more efficient code.
6665   // FIXME: Is this true if pshufb is available?
6666   if (SVOp->isSplat())
6667     return PromoteSplat(SVOp, DAG);
6668
6669   // If we have SSSE3, and all words of the result are from 1 input vector,
6670   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6671   // is present, fall back to case 4.
6672   if (Subtarget->hasSSSE3()) {
6673     SmallVector<SDValue,16> pshufbMask;
6674
6675     // If we have elements from both input vectors, set the high bit of the
6676     // shuffle mask element to zero out elements that come from V2 in the V1
6677     // mask, and elements that come from V1 in the V2 mask, so that the two
6678     // results can be OR'd together.
6679     bool TwoInputs = V1Used && V2Used;
6680     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6681     if (!TwoInputs)
6682       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6683
6684     // Calculate the shuffle mask for the second input, shuffle it, and
6685     // OR it with the first shuffled input.
6686     CommuteVectorShuffleMask(MaskVals, 8);
6687     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6688     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6689     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6690   }
6691
6692   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6693   // and update MaskVals with new element order.
6694   std::bitset<8> InOrder;
6695   if (BestLoQuad >= 0) {
6696     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6697     for (int i = 0; i != 4; ++i) {
6698       int idx = MaskVals[i];
6699       if (idx < 0) {
6700         InOrder.set(i);
6701       } else if ((idx / 4) == BestLoQuad) {
6702         MaskV[i] = idx & 3;
6703         InOrder.set(i);
6704       }
6705     }
6706     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6707                                 &MaskV[0]);
6708
6709     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6710       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6711       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6712                                   NewV.getOperand(0),
6713                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6714     }
6715   }
6716
6717   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6718   // and update MaskVals with the new element order.
6719   if (BestHiQuad >= 0) {
6720     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6721     for (unsigned i = 4; i != 8; ++i) {
6722       int idx = MaskVals[i];
6723       if (idx < 0) {
6724         InOrder.set(i);
6725       } else if ((idx / 4) == BestHiQuad) {
6726         MaskV[i] = (idx & 3) + 4;
6727         InOrder.set(i);
6728       }
6729     }
6730     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6731                                 &MaskV[0]);
6732
6733     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6734       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6735       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6736                                   NewV.getOperand(0),
6737                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6738     }
6739   }
6740
6741   // In case BestHi & BestLo were both -1, which means each quadword has a word
6742   // from each of the four input quadwords, calculate the InOrder bitvector now
6743   // before falling through to the insert/extract cleanup.
6744   if (BestLoQuad == -1 && BestHiQuad == -1) {
6745     NewV = V1;
6746     for (int i = 0; i != 8; ++i)
6747       if (MaskVals[i] < 0 || MaskVals[i] == i)
6748         InOrder.set(i);
6749   }
6750
6751   // The other elements are put in the right place using pextrw and pinsrw.
6752   for (unsigned i = 0; i != 8; ++i) {
6753     if (InOrder[i])
6754       continue;
6755     int EltIdx = MaskVals[i];
6756     if (EltIdx < 0)
6757       continue;
6758     SDValue ExtOp = (EltIdx < 8) ?
6759       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6760                   DAG.getIntPtrConstant(EltIdx)) :
6761       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6762                   DAG.getIntPtrConstant(EltIdx - 8));
6763     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6764                        DAG.getIntPtrConstant(i));
6765   }
6766   return NewV;
6767 }
6768
6769 /// \brief v16i16 shuffles
6770 ///
6771 /// FIXME: We only support generation of a single pshufb currently.  We can
6772 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6773 /// well (e.g 2 x pshufb + 1 x por).
6774 static SDValue
6775 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6776   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6777   SDValue V1 = SVOp->getOperand(0);
6778   SDValue V2 = SVOp->getOperand(1);
6779   SDLoc dl(SVOp);
6780
6781   if (V2.getOpcode() != ISD::UNDEF)
6782     return SDValue();
6783
6784   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6785   return getPSHUFB(MaskVals, V1, dl, DAG);
6786 }
6787
6788 // v16i8 shuffles - Prefer shuffles in the following order:
6789 // 1. [ssse3] 1 x pshufb
6790 // 2. [ssse3] 2 x pshufb + 1 x por
6791 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6792 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6793                                         const X86Subtarget* Subtarget,
6794                                         SelectionDAG &DAG) {
6795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6796   SDValue V1 = SVOp->getOperand(0);
6797   SDValue V2 = SVOp->getOperand(1);
6798   SDLoc dl(SVOp);
6799   ArrayRef<int> MaskVals = SVOp->getMask();
6800
6801   // Promote splats to a larger type which usually leads to more efficient code.
6802   // FIXME: Is this true if pshufb is available?
6803   if (SVOp->isSplat())
6804     return PromoteSplat(SVOp, DAG);
6805
6806   // If we have SSSE3, case 1 is generated when all result bytes come from
6807   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6808   // present, fall back to case 3.
6809
6810   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6811   if (Subtarget->hasSSSE3()) {
6812     SmallVector<SDValue,16> pshufbMask;
6813
6814     // If all result elements are from one input vector, then only translate
6815     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6816     //
6817     // Otherwise, we have elements from both input vectors, and must zero out
6818     // elements that come from V2 in the first mask, and V1 in the second mask
6819     // so that we can OR them together.
6820     for (unsigned i = 0; i != 16; ++i) {
6821       int EltIdx = MaskVals[i];
6822       if (EltIdx < 0 || EltIdx >= 16)
6823         EltIdx = 0x80;
6824       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6825     }
6826     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6827                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6828                                  MVT::v16i8, pshufbMask));
6829
6830     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6831     // the 2nd operand if it's undefined or zero.
6832     if (V2.getOpcode() == ISD::UNDEF ||
6833         ISD::isBuildVectorAllZeros(V2.getNode()))
6834       return V1;
6835
6836     // Calculate the shuffle mask for the second input, shuffle it, and
6837     // OR it with the first shuffled input.
6838     pshufbMask.clear();
6839     for (unsigned i = 0; i != 16; ++i) {
6840       int EltIdx = MaskVals[i];
6841       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6842       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6843     }
6844     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6845                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6846                                  MVT::v16i8, pshufbMask));
6847     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6848   }
6849
6850   // No SSSE3 - Calculate in place words and then fix all out of place words
6851   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6852   // the 16 different words that comprise the two doublequadword input vectors.
6853   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6854   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6855   SDValue NewV = V1;
6856   for (int i = 0; i != 8; ++i) {
6857     int Elt0 = MaskVals[i*2];
6858     int Elt1 = MaskVals[i*2+1];
6859
6860     // This word of the result is all undef, skip it.
6861     if (Elt0 < 0 && Elt1 < 0)
6862       continue;
6863
6864     // This word of the result is already in the correct place, skip it.
6865     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6866       continue;
6867
6868     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6869     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6870     SDValue InsElt;
6871
6872     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6873     // using a single extract together, load it and store it.
6874     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6875       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6876                            DAG.getIntPtrConstant(Elt1 / 2));
6877       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6878                         DAG.getIntPtrConstant(i));
6879       continue;
6880     }
6881
6882     // If Elt1 is defined, extract it from the appropriate source.  If the
6883     // source byte is not also odd, shift the extracted word left 8 bits
6884     // otherwise clear the bottom 8 bits if we need to do an or.
6885     if (Elt1 >= 0) {
6886       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6887                            DAG.getIntPtrConstant(Elt1 / 2));
6888       if ((Elt1 & 1) == 0)
6889         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6890                              DAG.getConstant(8,
6891                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6892       else if (Elt0 >= 0)
6893         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6894                              DAG.getConstant(0xFF00, MVT::i16));
6895     }
6896     // If Elt0 is defined, extract it from the appropriate source.  If the
6897     // source byte is not also even, shift the extracted word right 8 bits. If
6898     // Elt1 was also defined, OR the extracted values together before
6899     // inserting them in the result.
6900     if (Elt0 >= 0) {
6901       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6902                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6903       if ((Elt0 & 1) != 0)
6904         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6905                               DAG.getConstant(8,
6906                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6907       else if (Elt1 >= 0)
6908         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6909                              DAG.getConstant(0x00FF, MVT::i16));
6910       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6911                          : InsElt0;
6912     }
6913     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6914                        DAG.getIntPtrConstant(i));
6915   }
6916   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6917 }
6918
6919 // v32i8 shuffles - Translate to VPSHUFB if possible.
6920 static
6921 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6922                                  const X86Subtarget *Subtarget,
6923                                  SelectionDAG &DAG) {
6924   MVT VT = SVOp->getSimpleValueType(0);
6925   SDValue V1 = SVOp->getOperand(0);
6926   SDValue V2 = SVOp->getOperand(1);
6927   SDLoc dl(SVOp);
6928   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6929
6930   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6931   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6932   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6933
6934   // VPSHUFB may be generated if
6935   // (1) one of input vector is undefined or zeroinitializer.
6936   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6937   // And (2) the mask indexes don't cross the 128-bit lane.
6938   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6939       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6940     return SDValue();
6941
6942   if (V1IsAllZero && !V2IsAllZero) {
6943     CommuteVectorShuffleMask(MaskVals, 32);
6944     V1 = V2;
6945   }
6946   return getPSHUFB(MaskVals, V1, dl, DAG);
6947 }
6948
6949 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6950 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6951 /// done when every pair / quad of shuffle mask elements point to elements in
6952 /// the right sequence. e.g.
6953 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6954 static
6955 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6956                                  SelectionDAG &DAG) {
6957   MVT VT = SVOp->getSimpleValueType(0);
6958   SDLoc dl(SVOp);
6959   unsigned NumElems = VT.getVectorNumElements();
6960   MVT NewVT;
6961   unsigned Scale;
6962   switch (VT.SimpleTy) {
6963   default: llvm_unreachable("Unexpected!");
6964   case MVT::v2i64:
6965   case MVT::v2f64:
6966            return SDValue(SVOp, 0);
6967   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6968   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6969   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6970   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6971   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6972   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6973   }
6974
6975   SmallVector<int, 8> MaskVec;
6976   for (unsigned i = 0; i != NumElems; i += Scale) {
6977     int StartIdx = -1;
6978     for (unsigned j = 0; j != Scale; ++j) {
6979       int EltIdx = SVOp->getMaskElt(i+j);
6980       if (EltIdx < 0)
6981         continue;
6982       if (StartIdx < 0)
6983         StartIdx = (EltIdx / Scale);
6984       if (EltIdx != (int)(StartIdx*Scale + j))
6985         return SDValue();
6986     }
6987     MaskVec.push_back(StartIdx);
6988   }
6989
6990   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6991   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6992   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6993 }
6994
6995 /// getVZextMovL - Return a zero-extending vector move low node.
6996 ///
6997 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6998                             SDValue SrcOp, SelectionDAG &DAG,
6999                             const X86Subtarget *Subtarget, SDLoc dl) {
7000   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7001     LoadSDNode *LD = nullptr;
7002     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7003       LD = dyn_cast<LoadSDNode>(SrcOp);
7004     if (!LD) {
7005       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7006       // instead.
7007       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7008       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7009           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7010           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7011           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7012         // PR2108
7013         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7014         return DAG.getNode(ISD::BITCAST, dl, VT,
7015                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7016                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7017                                                    OpVT,
7018                                                    SrcOp.getOperand(0)
7019                                                           .getOperand(0))));
7020       }
7021     }
7022   }
7023
7024   return DAG.getNode(ISD::BITCAST, dl, VT,
7025                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7026                                  DAG.getNode(ISD::BITCAST, dl,
7027                                              OpVT, SrcOp)));
7028 }
7029
7030 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7031 /// which could not be matched by any known target speficic shuffle
7032 static SDValue
7033 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7034
7035   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7036   if (NewOp.getNode())
7037     return NewOp;
7038
7039   MVT VT = SVOp->getSimpleValueType(0);
7040
7041   unsigned NumElems = VT.getVectorNumElements();
7042   unsigned NumLaneElems = NumElems / 2;
7043
7044   SDLoc dl(SVOp);
7045   MVT EltVT = VT.getVectorElementType();
7046   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7047   SDValue Output[2];
7048
7049   SmallVector<int, 16> Mask;
7050   for (unsigned l = 0; l < 2; ++l) {
7051     // Build a shuffle mask for the output, discovering on the fly which
7052     // input vectors to use as shuffle operands (recorded in InputUsed).
7053     // If building a suitable shuffle vector proves too hard, then bail
7054     // out with UseBuildVector set.
7055     bool UseBuildVector = false;
7056     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7057     unsigned LaneStart = l * NumLaneElems;
7058     for (unsigned i = 0; i != NumLaneElems; ++i) {
7059       // The mask element.  This indexes into the input.
7060       int Idx = SVOp->getMaskElt(i+LaneStart);
7061       if (Idx < 0) {
7062         // the mask element does not index into any input vector.
7063         Mask.push_back(-1);
7064         continue;
7065       }
7066
7067       // The input vector this mask element indexes into.
7068       int Input = Idx / NumLaneElems;
7069
7070       // Turn the index into an offset from the start of the input vector.
7071       Idx -= Input * NumLaneElems;
7072
7073       // Find or create a shuffle vector operand to hold this input.
7074       unsigned OpNo;
7075       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7076         if (InputUsed[OpNo] == Input)
7077           // This input vector is already an operand.
7078           break;
7079         if (InputUsed[OpNo] < 0) {
7080           // Create a new operand for this input vector.
7081           InputUsed[OpNo] = Input;
7082           break;
7083         }
7084       }
7085
7086       if (OpNo >= array_lengthof(InputUsed)) {
7087         // More than two input vectors used!  Give up on trying to create a
7088         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7089         UseBuildVector = true;
7090         break;
7091       }
7092
7093       // Add the mask index for the new shuffle vector.
7094       Mask.push_back(Idx + OpNo * NumLaneElems);
7095     }
7096
7097     if (UseBuildVector) {
7098       SmallVector<SDValue, 16> SVOps;
7099       for (unsigned i = 0; i != NumLaneElems; ++i) {
7100         // The mask element.  This indexes into the input.
7101         int Idx = SVOp->getMaskElt(i+LaneStart);
7102         if (Idx < 0) {
7103           SVOps.push_back(DAG.getUNDEF(EltVT));
7104           continue;
7105         }
7106
7107         // The input vector this mask element indexes into.
7108         int Input = Idx / NumElems;
7109
7110         // Turn the index into an offset from the start of the input vector.
7111         Idx -= Input * NumElems;
7112
7113         // Extract the vector element by hand.
7114         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7115                                     SVOp->getOperand(Input),
7116                                     DAG.getIntPtrConstant(Idx)));
7117       }
7118
7119       // Construct the output using a BUILD_VECTOR.
7120       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7121     } else if (InputUsed[0] < 0) {
7122       // No input vectors were used! The result is undefined.
7123       Output[l] = DAG.getUNDEF(NVT);
7124     } else {
7125       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7126                                         (InputUsed[0] % 2) * NumLaneElems,
7127                                         DAG, dl);
7128       // If only one input was used, use an undefined vector for the other.
7129       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7130         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7131                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7132       // At least one input vector was used. Create a new shuffle vector.
7133       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7134     }
7135
7136     Mask.clear();
7137   }
7138
7139   // Concatenate the result back
7140   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7141 }
7142
7143 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7144 /// 4 elements, and match them with several different shuffle types.
7145 static SDValue
7146 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7147   SDValue V1 = SVOp->getOperand(0);
7148   SDValue V2 = SVOp->getOperand(1);
7149   SDLoc dl(SVOp);
7150   MVT VT = SVOp->getSimpleValueType(0);
7151
7152   assert(VT.is128BitVector() && "Unsupported vector size");
7153
7154   std::pair<int, int> Locs[4];
7155   int Mask1[] = { -1, -1, -1, -1 };
7156   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7157
7158   unsigned NumHi = 0;
7159   unsigned NumLo = 0;
7160   for (unsigned i = 0; i != 4; ++i) {
7161     int Idx = PermMask[i];
7162     if (Idx < 0) {
7163       Locs[i] = std::make_pair(-1, -1);
7164     } else {
7165       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7166       if (Idx < 4) {
7167         Locs[i] = std::make_pair(0, NumLo);
7168         Mask1[NumLo] = Idx;
7169         NumLo++;
7170       } else {
7171         Locs[i] = std::make_pair(1, NumHi);
7172         if (2+NumHi < 4)
7173           Mask1[2+NumHi] = Idx;
7174         NumHi++;
7175       }
7176     }
7177   }
7178
7179   if (NumLo <= 2 && NumHi <= 2) {
7180     // If no more than two elements come from either vector. This can be
7181     // implemented with two shuffles. First shuffle gather the elements.
7182     // The second shuffle, which takes the first shuffle as both of its
7183     // vector operands, put the elements into the right order.
7184     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7185
7186     int Mask2[] = { -1, -1, -1, -1 };
7187
7188     for (unsigned i = 0; i != 4; ++i)
7189       if (Locs[i].first != -1) {
7190         unsigned Idx = (i < 2) ? 0 : 4;
7191         Idx += Locs[i].first * 2 + Locs[i].second;
7192         Mask2[i] = Idx;
7193       }
7194
7195     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7196   }
7197
7198   if (NumLo == 3 || NumHi == 3) {
7199     // Otherwise, we must have three elements from one vector, call it X, and
7200     // one element from the other, call it Y.  First, use a shufps to build an
7201     // intermediate vector with the one element from Y and the element from X
7202     // that will be in the same half in the final destination (the indexes don't
7203     // matter). Then, use a shufps to build the final vector, taking the half
7204     // containing the element from Y from the intermediate, and the other half
7205     // from X.
7206     if (NumHi == 3) {
7207       // Normalize it so the 3 elements come from V1.
7208       CommuteVectorShuffleMask(PermMask, 4);
7209       std::swap(V1, V2);
7210     }
7211
7212     // Find the element from V2.
7213     unsigned HiIndex;
7214     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7215       int Val = PermMask[HiIndex];
7216       if (Val < 0)
7217         continue;
7218       if (Val >= 4)
7219         break;
7220     }
7221
7222     Mask1[0] = PermMask[HiIndex];
7223     Mask1[1] = -1;
7224     Mask1[2] = PermMask[HiIndex^1];
7225     Mask1[3] = -1;
7226     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7227
7228     if (HiIndex >= 2) {
7229       Mask1[0] = PermMask[0];
7230       Mask1[1] = PermMask[1];
7231       Mask1[2] = HiIndex & 1 ? 6 : 4;
7232       Mask1[3] = HiIndex & 1 ? 4 : 6;
7233       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7234     }
7235
7236     Mask1[0] = HiIndex & 1 ? 2 : 0;
7237     Mask1[1] = HiIndex & 1 ? 0 : 2;
7238     Mask1[2] = PermMask[2];
7239     Mask1[3] = PermMask[3];
7240     if (Mask1[2] >= 0)
7241       Mask1[2] += 4;
7242     if (Mask1[3] >= 0)
7243       Mask1[3] += 4;
7244     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7245   }
7246
7247   // Break it into (shuffle shuffle_hi, shuffle_lo).
7248   int LoMask[] = { -1, -1, -1, -1 };
7249   int HiMask[] = { -1, -1, -1, -1 };
7250
7251   int *MaskPtr = LoMask;
7252   unsigned MaskIdx = 0;
7253   unsigned LoIdx = 0;
7254   unsigned HiIdx = 2;
7255   for (unsigned i = 0; i != 4; ++i) {
7256     if (i == 2) {
7257       MaskPtr = HiMask;
7258       MaskIdx = 1;
7259       LoIdx = 0;
7260       HiIdx = 2;
7261     }
7262     int Idx = PermMask[i];
7263     if (Idx < 0) {
7264       Locs[i] = std::make_pair(-1, -1);
7265     } else if (Idx < 4) {
7266       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7267       MaskPtr[LoIdx] = Idx;
7268       LoIdx++;
7269     } else {
7270       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7271       MaskPtr[HiIdx] = Idx;
7272       HiIdx++;
7273     }
7274   }
7275
7276   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7277   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7278   int MaskOps[] = { -1, -1, -1, -1 };
7279   for (unsigned i = 0; i != 4; ++i)
7280     if (Locs[i].first != -1)
7281       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7282   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7283 }
7284
7285 static bool MayFoldVectorLoad(SDValue V) {
7286   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7287     V = V.getOperand(0);
7288
7289   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7290     V = V.getOperand(0);
7291   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7292       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7293     // BUILD_VECTOR (load), undef
7294     V = V.getOperand(0);
7295
7296   return MayFoldLoad(V);
7297 }
7298
7299 static
7300 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7301   MVT VT = Op.getSimpleValueType();
7302
7303   // Canonizalize to v2f64.
7304   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7305   return DAG.getNode(ISD::BITCAST, dl, VT,
7306                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7307                                           V1, DAG));
7308 }
7309
7310 static
7311 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7312                         bool HasSSE2) {
7313   SDValue V1 = Op.getOperand(0);
7314   SDValue V2 = Op.getOperand(1);
7315   MVT VT = Op.getSimpleValueType();
7316
7317   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7318
7319   if (HasSSE2 && VT == MVT::v2f64)
7320     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7321
7322   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7323   return DAG.getNode(ISD::BITCAST, dl, VT,
7324                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7325                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7326                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7327 }
7328
7329 static
7330 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7331   SDValue V1 = Op.getOperand(0);
7332   SDValue V2 = Op.getOperand(1);
7333   MVT VT = Op.getSimpleValueType();
7334
7335   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7336          "unsupported shuffle type");
7337
7338   if (V2.getOpcode() == ISD::UNDEF)
7339     V2 = V1;
7340
7341   // v4i32 or v4f32
7342   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7343 }
7344
7345 static
7346 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7347   SDValue V1 = Op.getOperand(0);
7348   SDValue V2 = Op.getOperand(1);
7349   MVT VT = Op.getSimpleValueType();
7350   unsigned NumElems = VT.getVectorNumElements();
7351
7352   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7353   // operand of these instructions is only memory, so check if there's a
7354   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7355   // same masks.
7356   bool CanFoldLoad = false;
7357
7358   // Trivial case, when V2 comes from a load.
7359   if (MayFoldVectorLoad(V2))
7360     CanFoldLoad = true;
7361
7362   // When V1 is a load, it can be folded later into a store in isel, example:
7363   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7364   //    turns into:
7365   //  (MOVLPSmr addr:$src1, VR128:$src2)
7366   // So, recognize this potential and also use MOVLPS or MOVLPD
7367   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7368     CanFoldLoad = true;
7369
7370   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7371   if (CanFoldLoad) {
7372     if (HasSSE2 && NumElems == 2)
7373       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7374
7375     if (NumElems == 4)
7376       // If we don't care about the second element, proceed to use movss.
7377       if (SVOp->getMaskElt(1) != -1)
7378         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7379   }
7380
7381   // movl and movlp will both match v2i64, but v2i64 is never matched by
7382   // movl earlier because we make it strict to avoid messing with the movlp load
7383   // folding logic (see the code above getMOVLP call). Match it here then,
7384   // this is horrible, but will stay like this until we move all shuffle
7385   // matching to x86 specific nodes. Note that for the 1st condition all
7386   // types are matched with movsd.
7387   if (HasSSE2) {
7388     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7389     // as to remove this logic from here, as much as possible
7390     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7391       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7392     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7393   }
7394
7395   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7396
7397   // Invert the operand order and use SHUFPS to match it.
7398   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7399                               getShuffleSHUFImmediate(SVOp), DAG);
7400 }
7401
7402 // It is only safe to call this function if isINSERTPSMask is true for
7403 // this shufflevector mask.
7404 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7405                            SelectionDAG &DAG) {
7406   // Generate an insertps instruction when inserting an f32 from memory onto a
7407   // v4f32 or when copying a member from one v4f32 to another.
7408   // We also use it for transferring i32 from one register to another,
7409   // since it simply copies the same bits.
7410   // If we're transfering an i32 from memory to a specific element in a
7411   // register, we output a generic DAG that will match the PINSRD
7412   // instruction.
7413   // TODO: Optimize for AVX cases too (VINSERTPS)
7414   MVT VT = SVOp->getSimpleValueType(0);
7415   MVT EVT = VT.getVectorElementType();
7416   SDValue V1 = SVOp->getOperand(0);
7417   SDValue V2 = SVOp->getOperand(1);
7418   auto Mask = SVOp->getMask();
7419   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7420          "unsupported vector type for insertps/pinsrd");
7421
7422   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7423                              [](const int &i) { return i < 4; });
7424
7425   SDValue From;
7426   SDValue To;
7427   unsigned DestIndex;
7428   if (FromV1 == 1) {
7429     From = V1;
7430     To = V2;
7431     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7432                              [](const int &i) { return i < 4; }) -
7433                 Mask.begin();
7434   } else {
7435     From = V2;
7436     To = V1;
7437     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7438                              [](const int &i) { return i >= 4; }) -
7439                 Mask.begin();
7440   }
7441
7442   if (MayFoldLoad(From)) {
7443     // Trivial case, when From comes from a load and is only used by the
7444     // shuffle. Make it use insertps from the vector that we need from that
7445     // load.
7446     SDValue Addr = From.getOperand(1);
7447     SDValue NewAddr =
7448         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7449                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7450                                     Addr.getSimpleValueType()));
7451
7452     LoadSDNode *Load = cast<LoadSDNode>(From);
7453     SDValue NewLoad =
7454         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7455                     DAG.getMachineFunction().getMachineMemOperand(
7456                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7457
7458     if (EVT == MVT::f32) {
7459       // Create this as a scalar to vector to match the instruction pattern.
7460       SDValue LoadScalarToVector =
7461           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7462       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7463       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7464                          InsertpsMask);
7465     } else { // EVT == MVT::i32
7466       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7467       // instruction, to match the PINSRD instruction, which loads an i32 to a
7468       // certain vector element.
7469       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7470                          DAG.getConstant(DestIndex, MVT::i32));
7471     }
7472   }
7473
7474   // Vector-element-to-vector
7475   unsigned SrcIndex = Mask[DestIndex] % 4;
7476   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7477   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7478 }
7479
7480 // Reduce a vector shuffle to zext.
7481 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7482                                     SelectionDAG &DAG) {
7483   // PMOVZX is only available from SSE41.
7484   if (!Subtarget->hasSSE41())
7485     return SDValue();
7486
7487   MVT VT = Op.getSimpleValueType();
7488
7489   // Only AVX2 support 256-bit vector integer extending.
7490   if (!Subtarget->hasInt256() && VT.is256BitVector())
7491     return SDValue();
7492
7493   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7494   SDLoc DL(Op);
7495   SDValue V1 = Op.getOperand(0);
7496   SDValue V2 = Op.getOperand(1);
7497   unsigned NumElems = VT.getVectorNumElements();
7498
7499   // Extending is an unary operation and the element type of the source vector
7500   // won't be equal to or larger than i64.
7501   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7502       VT.getVectorElementType() == MVT::i64)
7503     return SDValue();
7504
7505   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7506   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7507   while ((1U << Shift) < NumElems) {
7508     if (SVOp->getMaskElt(1U << Shift) == 1)
7509       break;
7510     Shift += 1;
7511     // The maximal ratio is 8, i.e. from i8 to i64.
7512     if (Shift > 3)
7513       return SDValue();
7514   }
7515
7516   // Check the shuffle mask.
7517   unsigned Mask = (1U << Shift) - 1;
7518   for (unsigned i = 0; i != NumElems; ++i) {
7519     int EltIdx = SVOp->getMaskElt(i);
7520     if ((i & Mask) != 0 && EltIdx != -1)
7521       return SDValue();
7522     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7523       return SDValue();
7524   }
7525
7526   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7527   MVT NeVT = MVT::getIntegerVT(NBits);
7528   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7529
7530   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7531     return SDValue();
7532
7533   // Simplify the operand as it's prepared to be fed into shuffle.
7534   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7535   if (V1.getOpcode() == ISD::BITCAST &&
7536       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7537       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7538       V1.getOperand(0).getOperand(0)
7539         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7540     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7541     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7542     ConstantSDNode *CIdx =
7543       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7544     // If it's foldable, i.e. normal load with single use, we will let code
7545     // selection to fold it. Otherwise, we will short the conversion sequence.
7546     if (CIdx && CIdx->getZExtValue() == 0 &&
7547         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7548       MVT FullVT = V.getSimpleValueType();
7549       MVT V1VT = V1.getSimpleValueType();
7550       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7551         // The "ext_vec_elt" node is wider than the result node.
7552         // In this case we should extract subvector from V.
7553         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7554         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7555         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7556                                         FullVT.getVectorNumElements()/Ratio);
7557         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7558                         DAG.getIntPtrConstant(0));
7559       }
7560       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7561     }
7562   }
7563
7564   return DAG.getNode(ISD::BITCAST, DL, VT,
7565                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7566 }
7567
7568 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7569                                       SelectionDAG &DAG) {
7570   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7571   MVT VT = Op.getSimpleValueType();
7572   SDLoc dl(Op);
7573   SDValue V1 = Op.getOperand(0);
7574   SDValue V2 = Op.getOperand(1);
7575
7576   if (isZeroShuffle(SVOp))
7577     return getZeroVector(VT, Subtarget, DAG, dl);
7578
7579   // Handle splat operations
7580   if (SVOp->isSplat()) {
7581     // Use vbroadcast whenever the splat comes from a foldable load
7582     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7583     if (Broadcast.getNode())
7584       return Broadcast;
7585   }
7586
7587   // Check integer expanding shuffles.
7588   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7589   if (NewOp.getNode())
7590     return NewOp;
7591
7592   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7593   // do it!
7594   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7595       VT == MVT::v32i8) {
7596     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7597     if (NewOp.getNode())
7598       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7599   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7600     // FIXME: Figure out a cleaner way to do this.
7601     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7602       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7603       if (NewOp.getNode()) {
7604         MVT NewVT = NewOp.getSimpleValueType();
7605         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7606                                NewVT, true, false))
7607           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7608                               dl);
7609       }
7610     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7611       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7612       if (NewOp.getNode()) {
7613         MVT NewVT = NewOp.getSimpleValueType();
7614         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7615           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7616                               dl);
7617       }
7618     }
7619   }
7620   return SDValue();
7621 }
7622
7623 SDValue
7624 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7625   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7626   SDValue V1 = Op.getOperand(0);
7627   SDValue V2 = Op.getOperand(1);
7628   MVT VT = Op.getSimpleValueType();
7629   SDLoc dl(Op);
7630   unsigned NumElems = VT.getVectorNumElements();
7631   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7632   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7633   bool V1IsSplat = false;
7634   bool V2IsSplat = false;
7635   bool HasSSE2 = Subtarget->hasSSE2();
7636   bool HasFp256    = Subtarget->hasFp256();
7637   bool HasInt256   = Subtarget->hasInt256();
7638   MachineFunction &MF = DAG.getMachineFunction();
7639   bool OptForSize = MF.getFunction()->getAttributes().
7640     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7641
7642   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7643
7644   if (V1IsUndef && V2IsUndef)
7645     return DAG.getUNDEF(VT);
7646
7647   // When we create a shuffle node we put the UNDEF node to second operand,
7648   // but in some cases the first operand may be transformed to UNDEF.
7649   // In this case we should just commute the node.
7650   if (V1IsUndef)
7651     return CommuteVectorShuffle(SVOp, DAG);
7652
7653   // Vector shuffle lowering takes 3 steps:
7654   //
7655   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7656   //    narrowing and commutation of operands should be handled.
7657   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7658   //    shuffle nodes.
7659   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7660   //    so the shuffle can be broken into other shuffles and the legalizer can
7661   //    try the lowering again.
7662   //
7663   // The general idea is that no vector_shuffle operation should be left to
7664   // be matched during isel, all of them must be converted to a target specific
7665   // node here.
7666
7667   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7668   // narrowing and commutation of operands should be handled. The actual code
7669   // doesn't include all of those, work in progress...
7670   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7671   if (NewOp.getNode())
7672     return NewOp;
7673
7674   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7675
7676   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7677   // unpckh_undef). Only use pshufd if speed is more important than size.
7678   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7679     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7680   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7681     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7682
7683   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7684       V2IsUndef && MayFoldVectorLoad(V1))
7685     return getMOVDDup(Op, dl, V1, DAG);
7686
7687   if (isMOVHLPS_v_undef_Mask(M, VT))
7688     return getMOVHighToLow(Op, dl, DAG);
7689
7690   // Use to match splats
7691   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7692       (VT == MVT::v2f64 || VT == MVT::v2i64))
7693     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7694
7695   if (isPSHUFDMask(M, VT)) {
7696     // The actual implementation will match the mask in the if above and then
7697     // during isel it can match several different instructions, not only pshufd
7698     // as its name says, sad but true, emulate the behavior for now...
7699     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7700       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7701
7702     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7703
7704     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7705       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7706
7707     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7708       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7709                                   DAG);
7710
7711     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7712                                 TargetMask, DAG);
7713   }
7714
7715   if (isPALIGNRMask(M, VT, Subtarget))
7716     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7717                                 getShufflePALIGNRImmediate(SVOp),
7718                                 DAG);
7719
7720   // Check if this can be converted into a logical shift.
7721   bool isLeft = false;
7722   unsigned ShAmt = 0;
7723   SDValue ShVal;
7724   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7725   if (isShift && ShVal.hasOneUse()) {
7726     // If the shifted value has multiple uses, it may be cheaper to use
7727     // v_set0 + movlhps or movhlps, etc.
7728     MVT EltVT = VT.getVectorElementType();
7729     ShAmt *= EltVT.getSizeInBits();
7730     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7731   }
7732
7733   if (isMOVLMask(M, VT)) {
7734     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7735       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7736     if (!isMOVLPMask(M, VT)) {
7737       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7738         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7739
7740       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7741         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7742     }
7743   }
7744
7745   // FIXME: fold these into legal mask.
7746   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7747     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7748
7749   if (isMOVHLPSMask(M, VT))
7750     return getMOVHighToLow(Op, dl, DAG);
7751
7752   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7753     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7754
7755   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7756     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7757
7758   if (isMOVLPMask(M, VT))
7759     return getMOVLP(Op, dl, DAG, HasSSE2);
7760
7761   if (ShouldXformToMOVHLPS(M, VT) ||
7762       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7763     return CommuteVectorShuffle(SVOp, DAG);
7764
7765   if (isShift) {
7766     // No better options. Use a vshldq / vsrldq.
7767     MVT EltVT = VT.getVectorElementType();
7768     ShAmt *= EltVT.getSizeInBits();
7769     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7770   }
7771
7772   bool Commuted = false;
7773   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7774   // 1,1,1,1 -> v8i16 though.
7775   V1IsSplat = isSplatVector(V1.getNode());
7776   V2IsSplat = isSplatVector(V2.getNode());
7777
7778   // Canonicalize the splat or undef, if present, to be on the RHS.
7779   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7780     CommuteVectorShuffleMask(M, NumElems);
7781     std::swap(V1, V2);
7782     std::swap(V1IsSplat, V2IsSplat);
7783     Commuted = true;
7784   }
7785
7786   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7787     // Shuffling low element of v1 into undef, just return v1.
7788     if (V2IsUndef)
7789       return V1;
7790     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7791     // the instruction selector will not match, so get a canonical MOVL with
7792     // swapped operands to undo the commute.
7793     return getMOVL(DAG, dl, VT, V2, V1);
7794   }
7795
7796   if (isUNPCKLMask(M, VT, HasInt256))
7797     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7798
7799   if (isUNPCKHMask(M, VT, HasInt256))
7800     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7801
7802   if (V2IsSplat) {
7803     // Normalize mask so all entries that point to V2 points to its first
7804     // element then try to match unpck{h|l} again. If match, return a
7805     // new vector_shuffle with the corrected mask.p
7806     SmallVector<int, 8> NewMask(M.begin(), M.end());
7807     NormalizeMask(NewMask, NumElems);
7808     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7809       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7810     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7811       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7812   }
7813
7814   if (Commuted) {
7815     // Commute is back and try unpck* again.
7816     // FIXME: this seems wrong.
7817     CommuteVectorShuffleMask(M, NumElems);
7818     std::swap(V1, V2);
7819     std::swap(V1IsSplat, V2IsSplat);
7820
7821     if (isUNPCKLMask(M, VT, HasInt256))
7822       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7823
7824     if (isUNPCKHMask(M, VT, HasInt256))
7825       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7826   }
7827
7828   // Normalize the node to match x86 shuffle ops if needed
7829   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7830     return CommuteVectorShuffle(SVOp, DAG);
7831
7832   // The checks below are all present in isShuffleMaskLegal, but they are
7833   // inlined here right now to enable us to directly emit target specific
7834   // nodes, and remove one by one until they don't return Op anymore.
7835
7836   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7837       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7838     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7839       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7840   }
7841
7842   if (isPSHUFHWMask(M, VT, HasInt256))
7843     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7844                                 getShufflePSHUFHWImmediate(SVOp),
7845                                 DAG);
7846
7847   if (isPSHUFLWMask(M, VT, HasInt256))
7848     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7849                                 getShufflePSHUFLWImmediate(SVOp),
7850                                 DAG);
7851
7852   if (isSHUFPMask(M, VT))
7853     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7854                                 getShuffleSHUFImmediate(SVOp), DAG);
7855
7856   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7857     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7858   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7859     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7860
7861   //===--------------------------------------------------------------------===//
7862   // Generate target specific nodes for 128 or 256-bit shuffles only
7863   // supported in the AVX instruction set.
7864   //
7865
7866   // Handle VMOVDDUPY permutations
7867   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7868     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7869
7870   // Handle VPERMILPS/D* permutations
7871   if (isVPERMILPMask(M, VT)) {
7872     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7873       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7874                                   getShuffleSHUFImmediate(SVOp), DAG);
7875     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7876                                 getShuffleSHUFImmediate(SVOp), DAG);
7877   }
7878
7879   unsigned Idx;
7880   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7881     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7882                               Idx*(NumElems/2), DAG, dl);
7883
7884   // Handle VPERM2F128/VPERM2I128 permutations
7885   if (isVPERM2X128Mask(M, VT, HasFp256))
7886     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7887                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7888
7889   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7890   if (BlendOp.getNode())
7891     return BlendOp;
7892
7893   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7894     return getINSERTPS(SVOp, dl, DAG);
7895
7896   unsigned Imm8;
7897   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7898     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7899
7900   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7901       VT.is512BitVector()) {
7902     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7903     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7904     SmallVector<SDValue, 16> permclMask;
7905     for (unsigned i = 0; i != NumElems; ++i) {
7906       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7907     }
7908
7909     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7910     if (V2IsUndef)
7911       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7912       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7913                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7914     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7915                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7916   }
7917
7918   //===--------------------------------------------------------------------===//
7919   // Since no target specific shuffle was selected for this generic one,
7920   // lower it into other known shuffles. FIXME: this isn't true yet, but
7921   // this is the plan.
7922   //
7923
7924   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7925   if (VT == MVT::v8i16) {
7926     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7927     if (NewOp.getNode())
7928       return NewOp;
7929   }
7930
7931   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7932     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7933     if (NewOp.getNode())
7934       return NewOp;
7935   }
7936
7937   if (VT == MVT::v16i8) {
7938     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7939     if (NewOp.getNode())
7940       return NewOp;
7941   }
7942
7943   if (VT == MVT::v32i8) {
7944     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7945     if (NewOp.getNode())
7946       return NewOp;
7947   }
7948
7949   // Handle all 128-bit wide vectors with 4 elements, and match them with
7950   // several different shuffle types.
7951   if (NumElems == 4 && VT.is128BitVector())
7952     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7953
7954   // Handle general 256-bit shuffles
7955   if (VT.is256BitVector())
7956     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7957
7958   return SDValue();
7959 }
7960
7961 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7962   MVT VT = Op.getSimpleValueType();
7963   SDLoc dl(Op);
7964
7965   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7966     return SDValue();
7967
7968   if (VT.getSizeInBits() == 8) {
7969     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7970                                   Op.getOperand(0), Op.getOperand(1));
7971     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7972                                   DAG.getValueType(VT));
7973     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7974   }
7975
7976   if (VT.getSizeInBits() == 16) {
7977     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7978     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7979     if (Idx == 0)
7980       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7981                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7982                                      DAG.getNode(ISD::BITCAST, dl,
7983                                                  MVT::v4i32,
7984                                                  Op.getOperand(0)),
7985                                      Op.getOperand(1)));
7986     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7987                                   Op.getOperand(0), Op.getOperand(1));
7988     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7989                                   DAG.getValueType(VT));
7990     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7991   }
7992
7993   if (VT == MVT::f32) {
7994     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7995     // the result back to FR32 register. It's only worth matching if the
7996     // result has a single use which is a store or a bitcast to i32.  And in
7997     // the case of a store, it's not worth it if the index is a constant 0,
7998     // because a MOVSSmr can be used instead, which is smaller and faster.
7999     if (!Op.hasOneUse())
8000       return SDValue();
8001     SDNode *User = *Op.getNode()->use_begin();
8002     if ((User->getOpcode() != ISD::STORE ||
8003          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8004           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8005         (User->getOpcode() != ISD::BITCAST ||
8006          User->getValueType(0) != MVT::i32))
8007       return SDValue();
8008     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8009                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8010                                               Op.getOperand(0)),
8011                                               Op.getOperand(1));
8012     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8013   }
8014
8015   if (VT == MVT::i32 || VT == MVT::i64) {
8016     // ExtractPS/pextrq works with constant index.
8017     if (isa<ConstantSDNode>(Op.getOperand(1)))
8018       return Op;
8019   }
8020   return SDValue();
8021 }
8022
8023 /// Extract one bit from mask vector, like v16i1 or v8i1.
8024 /// AVX-512 feature.
8025 SDValue
8026 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8027   SDValue Vec = Op.getOperand(0);
8028   SDLoc dl(Vec);
8029   MVT VecVT = Vec.getSimpleValueType();
8030   SDValue Idx = Op.getOperand(1);
8031   MVT EltVT = Op.getSimpleValueType();
8032
8033   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8034
8035   // variable index can't be handled in mask registers,
8036   // extend vector to VR512
8037   if (!isa<ConstantSDNode>(Idx)) {
8038     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8039     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8040     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8041                               ExtVT.getVectorElementType(), Ext, Idx);
8042     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8043   }
8044
8045   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8046   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8047   unsigned MaxSift = rc->getSize()*8 - 1;
8048   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8049                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8050   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8051                     DAG.getConstant(MaxSift, MVT::i8));
8052   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8053                        DAG.getIntPtrConstant(0));
8054 }
8055
8056 SDValue
8057 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8058                                            SelectionDAG &DAG) const {
8059   SDLoc dl(Op);
8060   SDValue Vec = Op.getOperand(0);
8061   MVT VecVT = Vec.getSimpleValueType();
8062   SDValue Idx = Op.getOperand(1);
8063
8064   if (Op.getSimpleValueType() == MVT::i1)
8065     return ExtractBitFromMaskVector(Op, DAG);
8066
8067   if (!isa<ConstantSDNode>(Idx)) {
8068     if (VecVT.is512BitVector() ||
8069         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8070          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8071
8072       MVT MaskEltVT =
8073         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8074       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8075                                     MaskEltVT.getSizeInBits());
8076
8077       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8078       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8079                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8080                                 Idx, DAG.getConstant(0, getPointerTy()));
8081       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8082       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8083                         Perm, DAG.getConstant(0, getPointerTy()));
8084     }
8085     return SDValue();
8086   }
8087
8088   // If this is a 256-bit vector result, first extract the 128-bit vector and
8089   // then extract the element from the 128-bit vector.
8090   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8091
8092     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8093     // Get the 128-bit vector.
8094     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8095     MVT EltVT = VecVT.getVectorElementType();
8096
8097     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8098
8099     //if (IdxVal >= NumElems/2)
8100     //  IdxVal -= NumElems/2;
8101     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8102     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8103                        DAG.getConstant(IdxVal, MVT::i32));
8104   }
8105
8106   assert(VecVT.is128BitVector() && "Unexpected vector length");
8107
8108   if (Subtarget->hasSSE41()) {
8109     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8110     if (Res.getNode())
8111       return Res;
8112   }
8113
8114   MVT VT = Op.getSimpleValueType();
8115   // TODO: handle v16i8.
8116   if (VT.getSizeInBits() == 16) {
8117     SDValue Vec = Op.getOperand(0);
8118     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8119     if (Idx == 0)
8120       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8121                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8122                                      DAG.getNode(ISD::BITCAST, dl,
8123                                                  MVT::v4i32, Vec),
8124                                      Op.getOperand(1)));
8125     // Transform it so it match pextrw which produces a 32-bit result.
8126     MVT EltVT = MVT::i32;
8127     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8128                                   Op.getOperand(0), Op.getOperand(1));
8129     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8130                                   DAG.getValueType(VT));
8131     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8132   }
8133
8134   if (VT.getSizeInBits() == 32) {
8135     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8136     if (Idx == 0)
8137       return Op;
8138
8139     // SHUFPS the element to the lowest double word, then movss.
8140     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8141     MVT VVT = Op.getOperand(0).getSimpleValueType();
8142     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8143                                        DAG.getUNDEF(VVT), Mask);
8144     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8145                        DAG.getIntPtrConstant(0));
8146   }
8147
8148   if (VT.getSizeInBits() == 64) {
8149     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8150     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8151     //        to match extract_elt for f64.
8152     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8153     if (Idx == 0)
8154       return Op;
8155
8156     // UNPCKHPD the element to the lowest double word, then movsd.
8157     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8158     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8159     int Mask[2] = { 1, -1 };
8160     MVT VVT = Op.getOperand(0).getSimpleValueType();
8161     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8162                                        DAG.getUNDEF(VVT), Mask);
8163     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8164                        DAG.getIntPtrConstant(0));
8165   }
8166
8167   return SDValue();
8168 }
8169
8170 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8171   MVT VT = Op.getSimpleValueType();
8172   MVT EltVT = VT.getVectorElementType();
8173   SDLoc dl(Op);
8174
8175   SDValue N0 = Op.getOperand(0);
8176   SDValue N1 = Op.getOperand(1);
8177   SDValue N2 = Op.getOperand(2);
8178
8179   if (!VT.is128BitVector())
8180     return SDValue();
8181
8182   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8183       isa<ConstantSDNode>(N2)) {
8184     unsigned Opc;
8185     if (VT == MVT::v8i16)
8186       Opc = X86ISD::PINSRW;
8187     else if (VT == MVT::v16i8)
8188       Opc = X86ISD::PINSRB;
8189     else
8190       Opc = X86ISD::PINSRB;
8191
8192     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8193     // argument.
8194     if (N1.getValueType() != MVT::i32)
8195       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8196     if (N2.getValueType() != MVT::i32)
8197       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8198     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8199   }
8200
8201   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8202     // Bits [7:6] of the constant are the source select.  This will always be
8203     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8204     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8205     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8206     // Bits [5:4] of the constant are the destination select.  This is the
8207     //  value of the incoming immediate.
8208     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8209     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8210     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8211     // Create this as a scalar to vector..
8212     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8213     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8214   }
8215
8216   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8217     // PINSR* works with constant index.
8218     return Op;
8219   }
8220   return SDValue();
8221 }
8222
8223 /// Insert one bit to mask vector, like v16i1 or v8i1.
8224 /// AVX-512 feature.
8225 SDValue 
8226 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8227   SDLoc dl(Op);
8228   SDValue Vec = Op.getOperand(0);
8229   SDValue Elt = Op.getOperand(1);
8230   SDValue Idx = Op.getOperand(2);
8231   MVT VecVT = Vec.getSimpleValueType();
8232
8233   if (!isa<ConstantSDNode>(Idx)) {
8234     // Non constant index. Extend source and destination,
8235     // insert element and then truncate the result.
8236     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8237     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8238     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8239       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8240       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8241     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8242   }
8243
8244   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8245   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8246   if (Vec.getOpcode() == ISD::UNDEF)
8247     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8248                        DAG.getConstant(IdxVal, MVT::i8));
8249   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8250   unsigned MaxSift = rc->getSize()*8 - 1;
8251   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8252                     DAG.getConstant(MaxSift, MVT::i8));
8253   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8254                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8255   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8256 }
8257 SDValue
8258 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8259   MVT VT = Op.getSimpleValueType();
8260   MVT EltVT = VT.getVectorElementType();
8261   
8262   if (EltVT == MVT::i1)
8263     return InsertBitToMaskVector(Op, DAG);
8264
8265   SDLoc dl(Op);
8266   SDValue N0 = Op.getOperand(0);
8267   SDValue N1 = Op.getOperand(1);
8268   SDValue N2 = Op.getOperand(2);
8269
8270   // If this is a 256-bit vector result, first extract the 128-bit vector,
8271   // insert the element into the extracted half and then place it back.
8272   if (VT.is256BitVector() || VT.is512BitVector()) {
8273     if (!isa<ConstantSDNode>(N2))
8274       return SDValue();
8275
8276     // Get the desired 128-bit vector half.
8277     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8278     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8279
8280     // Insert the element into the desired half.
8281     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8282     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8283
8284     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8285                     DAG.getConstant(IdxIn128, MVT::i32));
8286
8287     // Insert the changed part back to the 256-bit vector
8288     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8289   }
8290
8291   if (Subtarget->hasSSE41())
8292     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8293
8294   if (EltVT == MVT::i8)
8295     return SDValue();
8296
8297   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8298     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8299     // as its second argument.
8300     if (N1.getValueType() != MVT::i32)
8301       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8302     if (N2.getValueType() != MVT::i32)
8303       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8304     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8305   }
8306   return SDValue();
8307 }
8308
8309 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8310   SDLoc dl(Op);
8311   MVT OpVT = Op.getSimpleValueType();
8312
8313   // If this is a 256-bit vector result, first insert into a 128-bit
8314   // vector and then insert into the 256-bit vector.
8315   if (!OpVT.is128BitVector()) {
8316     // Insert into a 128-bit vector.
8317     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8318     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8319                                  OpVT.getVectorNumElements() / SizeFactor);
8320
8321     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8322
8323     // Insert the 128-bit vector.
8324     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8325   }
8326
8327   if (OpVT == MVT::v1i64 &&
8328       Op.getOperand(0).getValueType() == MVT::i64)
8329     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8330
8331   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8332   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8333   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8334                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8335 }
8336
8337 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8338 // a simple subregister reference or explicit instructions to grab
8339 // upper bits of a vector.
8340 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8341                                       SelectionDAG &DAG) {
8342   SDLoc dl(Op);
8343   SDValue In =  Op.getOperand(0);
8344   SDValue Idx = Op.getOperand(1);
8345   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8346   MVT ResVT   = Op.getSimpleValueType();
8347   MVT InVT    = In.getSimpleValueType();
8348
8349   if (Subtarget->hasFp256()) {
8350     if (ResVT.is128BitVector() &&
8351         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8352         isa<ConstantSDNode>(Idx)) {
8353       return Extract128BitVector(In, IdxVal, DAG, dl);
8354     }
8355     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8356         isa<ConstantSDNode>(Idx)) {
8357       return Extract256BitVector(In, IdxVal, DAG, dl);
8358     }
8359   }
8360   return SDValue();
8361 }
8362
8363 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8364 // simple superregister reference or explicit instructions to insert
8365 // the upper bits of a vector.
8366 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8367                                      SelectionDAG &DAG) {
8368   if (Subtarget->hasFp256()) {
8369     SDLoc dl(Op.getNode());
8370     SDValue Vec = Op.getNode()->getOperand(0);
8371     SDValue SubVec = Op.getNode()->getOperand(1);
8372     SDValue Idx = Op.getNode()->getOperand(2);
8373
8374     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8375          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8376         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8377         isa<ConstantSDNode>(Idx)) {
8378       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8379       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8380     }
8381
8382     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8383         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8384         isa<ConstantSDNode>(Idx)) {
8385       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8386       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8387     }
8388   }
8389   return SDValue();
8390 }
8391
8392 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8393 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8394 // one of the above mentioned nodes. It has to be wrapped because otherwise
8395 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8396 // be used to form addressing mode. These wrapped nodes will be selected
8397 // into MOV32ri.
8398 SDValue
8399 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8400   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8401
8402   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8403   // global base reg.
8404   unsigned char OpFlag = 0;
8405   unsigned WrapperKind = X86ISD::Wrapper;
8406   CodeModel::Model M = getTargetMachine().getCodeModel();
8407
8408   if (Subtarget->isPICStyleRIPRel() &&
8409       (M == CodeModel::Small || M == CodeModel::Kernel))
8410     WrapperKind = X86ISD::WrapperRIP;
8411   else if (Subtarget->isPICStyleGOT())
8412     OpFlag = X86II::MO_GOTOFF;
8413   else if (Subtarget->isPICStyleStubPIC())
8414     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8415
8416   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8417                                              CP->getAlignment(),
8418                                              CP->getOffset(), OpFlag);
8419   SDLoc DL(CP);
8420   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8421   // With PIC, the address is actually $g + Offset.
8422   if (OpFlag) {
8423     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8424                          DAG.getNode(X86ISD::GlobalBaseReg,
8425                                      SDLoc(), getPointerTy()),
8426                          Result);
8427   }
8428
8429   return Result;
8430 }
8431
8432 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8433   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8434
8435   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8436   // global base reg.
8437   unsigned char OpFlag = 0;
8438   unsigned WrapperKind = X86ISD::Wrapper;
8439   CodeModel::Model M = getTargetMachine().getCodeModel();
8440
8441   if (Subtarget->isPICStyleRIPRel() &&
8442       (M == CodeModel::Small || M == CodeModel::Kernel))
8443     WrapperKind = X86ISD::WrapperRIP;
8444   else if (Subtarget->isPICStyleGOT())
8445     OpFlag = X86II::MO_GOTOFF;
8446   else if (Subtarget->isPICStyleStubPIC())
8447     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8448
8449   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8450                                           OpFlag);
8451   SDLoc DL(JT);
8452   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8453
8454   // With PIC, the address is actually $g + Offset.
8455   if (OpFlag)
8456     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8457                          DAG.getNode(X86ISD::GlobalBaseReg,
8458                                      SDLoc(), getPointerTy()),
8459                          Result);
8460
8461   return Result;
8462 }
8463
8464 SDValue
8465 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8466   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8467
8468   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8469   // global base reg.
8470   unsigned char OpFlag = 0;
8471   unsigned WrapperKind = X86ISD::Wrapper;
8472   CodeModel::Model M = getTargetMachine().getCodeModel();
8473
8474   if (Subtarget->isPICStyleRIPRel() &&
8475       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8476     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8477       OpFlag = X86II::MO_GOTPCREL;
8478     WrapperKind = X86ISD::WrapperRIP;
8479   } else if (Subtarget->isPICStyleGOT()) {
8480     OpFlag = X86II::MO_GOT;
8481   } else if (Subtarget->isPICStyleStubPIC()) {
8482     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8483   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8484     OpFlag = X86II::MO_DARWIN_NONLAZY;
8485   }
8486
8487   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8488
8489   SDLoc DL(Op);
8490   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8491
8492   // With PIC, the address is actually $g + Offset.
8493   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8494       !Subtarget->is64Bit()) {
8495     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8496                          DAG.getNode(X86ISD::GlobalBaseReg,
8497                                      SDLoc(), getPointerTy()),
8498                          Result);
8499   }
8500
8501   // For symbols that require a load from a stub to get the address, emit the
8502   // load.
8503   if (isGlobalStubReference(OpFlag))
8504     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8505                          MachinePointerInfo::getGOT(), false, false, false, 0);
8506
8507   return Result;
8508 }
8509
8510 SDValue
8511 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8512   // Create the TargetBlockAddressAddress node.
8513   unsigned char OpFlags =
8514     Subtarget->ClassifyBlockAddressReference();
8515   CodeModel::Model M = getTargetMachine().getCodeModel();
8516   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8517   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8518   SDLoc dl(Op);
8519   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8520                                              OpFlags);
8521
8522   if (Subtarget->isPICStyleRIPRel() &&
8523       (M == CodeModel::Small || M == CodeModel::Kernel))
8524     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8525   else
8526     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8527
8528   // With PIC, the address is actually $g + Offset.
8529   if (isGlobalRelativeToPICBase(OpFlags)) {
8530     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8531                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8532                          Result);
8533   }
8534
8535   return Result;
8536 }
8537
8538 SDValue
8539 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8540                                       int64_t Offset, SelectionDAG &DAG) const {
8541   // Create the TargetGlobalAddress node, folding in the constant
8542   // offset if it is legal.
8543   unsigned char OpFlags =
8544     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8545   CodeModel::Model M = getTargetMachine().getCodeModel();
8546   SDValue Result;
8547   if (OpFlags == X86II::MO_NO_FLAG &&
8548       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8549     // A direct static reference to a global.
8550     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8551     Offset = 0;
8552   } else {
8553     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8554   }
8555
8556   if (Subtarget->isPICStyleRIPRel() &&
8557       (M == CodeModel::Small || M == CodeModel::Kernel))
8558     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8559   else
8560     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8561
8562   // With PIC, the address is actually $g + Offset.
8563   if (isGlobalRelativeToPICBase(OpFlags)) {
8564     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8565                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8566                          Result);
8567   }
8568
8569   // For globals that require a load from a stub to get the address, emit the
8570   // load.
8571   if (isGlobalStubReference(OpFlags))
8572     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8573                          MachinePointerInfo::getGOT(), false, false, false, 0);
8574
8575   // If there was a non-zero offset that we didn't fold, create an explicit
8576   // addition for it.
8577   if (Offset != 0)
8578     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8579                          DAG.getConstant(Offset, getPointerTy()));
8580
8581   return Result;
8582 }
8583
8584 SDValue
8585 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8586   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8587   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8588   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8589 }
8590
8591 static SDValue
8592 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8593            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8594            unsigned char OperandFlags, bool LocalDynamic = false) {
8595   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8596   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8597   SDLoc dl(GA);
8598   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8599                                            GA->getValueType(0),
8600                                            GA->getOffset(),
8601                                            OperandFlags);
8602
8603   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8604                                            : X86ISD::TLSADDR;
8605
8606   if (InFlag) {
8607     SDValue Ops[] = { Chain,  TGA, *InFlag };
8608     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8609   } else {
8610     SDValue Ops[]  = { Chain, TGA };
8611     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8612   }
8613
8614   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8615   MFI->setAdjustsStack(true);
8616
8617   SDValue Flag = Chain.getValue(1);
8618   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8619 }
8620
8621 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8622 static SDValue
8623 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8624                                 const EVT PtrVT) {
8625   SDValue InFlag;
8626   SDLoc dl(GA);  // ? function entry point might be better
8627   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8628                                    DAG.getNode(X86ISD::GlobalBaseReg,
8629                                                SDLoc(), PtrVT), InFlag);
8630   InFlag = Chain.getValue(1);
8631
8632   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8633 }
8634
8635 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8636 static SDValue
8637 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8638                                 const EVT PtrVT) {
8639   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8640                     X86::RAX, X86II::MO_TLSGD);
8641 }
8642
8643 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8644                                            SelectionDAG &DAG,
8645                                            const EVT PtrVT,
8646                                            bool is64Bit) {
8647   SDLoc dl(GA);
8648
8649   // Get the start address of the TLS block for this module.
8650   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8651       .getInfo<X86MachineFunctionInfo>();
8652   MFI->incNumLocalDynamicTLSAccesses();
8653
8654   SDValue Base;
8655   if (is64Bit) {
8656     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8657                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8658   } else {
8659     SDValue InFlag;
8660     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8661         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8662     InFlag = Chain.getValue(1);
8663     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8664                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8665   }
8666
8667   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8668   // of Base.
8669
8670   // Build x@dtpoff.
8671   unsigned char OperandFlags = X86II::MO_DTPOFF;
8672   unsigned WrapperKind = X86ISD::Wrapper;
8673   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8674                                            GA->getValueType(0),
8675                                            GA->getOffset(), OperandFlags);
8676   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8677
8678   // Add x@dtpoff with the base.
8679   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8680 }
8681
8682 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8683 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8684                                    const EVT PtrVT, TLSModel::Model model,
8685                                    bool is64Bit, bool isPIC) {
8686   SDLoc dl(GA);
8687
8688   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8689   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8690                                                          is64Bit ? 257 : 256));
8691
8692   SDValue ThreadPointer =
8693       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8694                   MachinePointerInfo(Ptr), false, false, false, 0);
8695
8696   unsigned char OperandFlags = 0;
8697   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8698   // initialexec.
8699   unsigned WrapperKind = X86ISD::Wrapper;
8700   if (model == TLSModel::LocalExec) {
8701     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8702   } else if (model == TLSModel::InitialExec) {
8703     if (is64Bit) {
8704       OperandFlags = X86II::MO_GOTTPOFF;
8705       WrapperKind = X86ISD::WrapperRIP;
8706     } else {
8707       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8708     }
8709   } else {
8710     llvm_unreachable("Unexpected model");
8711   }
8712
8713   // emit "addl x@ntpoff,%eax" (local exec)
8714   // or "addl x@indntpoff,%eax" (initial exec)
8715   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8716   SDValue TGA =
8717       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8718                                  GA->getOffset(), OperandFlags);
8719   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8720
8721   if (model == TLSModel::InitialExec) {
8722     if (isPIC && !is64Bit) {
8723       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8724                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8725                            Offset);
8726     }
8727
8728     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8729                          MachinePointerInfo::getGOT(), false, false, false, 0);
8730   }
8731
8732   // The address of the thread local variable is the add of the thread
8733   // pointer with the offset of the variable.
8734   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8735 }
8736
8737 SDValue
8738 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8739
8740   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8741   const GlobalValue *GV = GA->getGlobal();
8742
8743   if (Subtarget->isTargetELF()) {
8744     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8745
8746     switch (model) {
8747       case TLSModel::GeneralDynamic:
8748         if (Subtarget->is64Bit())
8749           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8750         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8751       case TLSModel::LocalDynamic:
8752         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8753                                            Subtarget->is64Bit());
8754       case TLSModel::InitialExec:
8755       case TLSModel::LocalExec:
8756         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8757                                    Subtarget->is64Bit(),
8758                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8759     }
8760     llvm_unreachable("Unknown TLS model.");
8761   }
8762
8763   if (Subtarget->isTargetDarwin()) {
8764     // Darwin only has one model of TLS.  Lower to that.
8765     unsigned char OpFlag = 0;
8766     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8767                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8768
8769     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8770     // global base reg.
8771     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8772                   !Subtarget->is64Bit();
8773     if (PIC32)
8774       OpFlag = X86II::MO_TLVP_PIC_BASE;
8775     else
8776       OpFlag = X86II::MO_TLVP;
8777     SDLoc DL(Op);
8778     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8779                                                 GA->getValueType(0),
8780                                                 GA->getOffset(), OpFlag);
8781     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8782
8783     // With PIC32, the address is actually $g + Offset.
8784     if (PIC32)
8785       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8786                            DAG.getNode(X86ISD::GlobalBaseReg,
8787                                        SDLoc(), getPointerTy()),
8788                            Offset);
8789
8790     // Lowering the machine isd will make sure everything is in the right
8791     // location.
8792     SDValue Chain = DAG.getEntryNode();
8793     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8794     SDValue Args[] = { Chain, Offset };
8795     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8796
8797     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8798     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8799     MFI->setAdjustsStack(true);
8800
8801     // And our return value (tls address) is in the standard call return value
8802     // location.
8803     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8804     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8805                               Chain.getValue(1));
8806   }
8807
8808   if (Subtarget->isTargetKnownWindowsMSVC() ||
8809       Subtarget->isTargetWindowsGNU()) {
8810     // Just use the implicit TLS architecture
8811     // Need to generate someting similar to:
8812     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8813     //                                  ; from TEB
8814     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8815     //   mov     rcx, qword [rdx+rcx*8]
8816     //   mov     eax, .tls$:tlsvar
8817     //   [rax+rcx] contains the address
8818     // Windows 64bit: gs:0x58
8819     // Windows 32bit: fs:__tls_array
8820
8821     // If GV is an alias then use the aliasee for determining
8822     // thread-localness.
8823     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8824       GV = GA->getAliasedGlobal();
8825     SDLoc dl(GA);
8826     SDValue Chain = DAG.getEntryNode();
8827
8828     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8829     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8830     // use its literal value of 0x2C.
8831     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8832                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8833                                                              256)
8834                                         : Type::getInt32PtrTy(*DAG.getContext(),
8835                                                               257));
8836
8837     SDValue TlsArray =
8838         Subtarget->is64Bit()
8839             ? DAG.getIntPtrConstant(0x58)
8840             : (Subtarget->isTargetWindowsGNU()
8841                    ? DAG.getIntPtrConstant(0x2C)
8842                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8843
8844     SDValue ThreadPointer =
8845         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8846                     MachinePointerInfo(Ptr), false, false, false, 0);
8847
8848     // Load the _tls_index variable
8849     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8850     if (Subtarget->is64Bit())
8851       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8852                            IDX, MachinePointerInfo(), MVT::i32,
8853                            false, false, 0);
8854     else
8855       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8856                         false, false, false, 0);
8857
8858     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8859                                     getPointerTy());
8860     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8861
8862     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8863     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8864                       false, false, false, 0);
8865
8866     // Get the offset of start of .tls section
8867     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8868                                              GA->getValueType(0),
8869                                              GA->getOffset(), X86II::MO_SECREL);
8870     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8871
8872     // The address of the thread local variable is the add of the thread
8873     // pointer with the offset of the variable.
8874     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8875   }
8876
8877   llvm_unreachable("TLS not implemented for this target.");
8878 }
8879
8880 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8881 /// and take a 2 x i32 value to shift plus a shift amount.
8882 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8883   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8884   MVT VT = Op.getSimpleValueType();
8885   unsigned VTBits = VT.getSizeInBits();
8886   SDLoc dl(Op);
8887   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8888   SDValue ShOpLo = Op.getOperand(0);
8889   SDValue ShOpHi = Op.getOperand(1);
8890   SDValue ShAmt  = Op.getOperand(2);
8891   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8892   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8893   // during isel.
8894   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8895                                   DAG.getConstant(VTBits - 1, MVT::i8));
8896   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8897                                      DAG.getConstant(VTBits - 1, MVT::i8))
8898                        : DAG.getConstant(0, VT);
8899
8900   SDValue Tmp2, Tmp3;
8901   if (Op.getOpcode() == ISD::SHL_PARTS) {
8902     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8903     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8904   } else {
8905     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8906     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8907   }
8908
8909   // If the shift amount is larger or equal than the width of a part we can't
8910   // rely on the results of shld/shrd. Insert a test and select the appropriate
8911   // values for large shift amounts.
8912   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8913                                 DAG.getConstant(VTBits, MVT::i8));
8914   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8915                              AndNode, DAG.getConstant(0, MVT::i8));
8916
8917   SDValue Hi, Lo;
8918   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8919   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8920   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8921
8922   if (Op.getOpcode() == ISD::SHL_PARTS) {
8923     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8924     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8925   } else {
8926     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8927     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8928   }
8929
8930   SDValue Ops[2] = { Lo, Hi };
8931   return DAG.getMergeValues(Ops, dl);
8932 }
8933
8934 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8935                                            SelectionDAG &DAG) const {
8936   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8937
8938   if (SrcVT.isVector())
8939     return SDValue();
8940
8941   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8942          "Unknown SINT_TO_FP to lower!");
8943
8944   // These are really Legal; return the operand so the caller accepts it as
8945   // Legal.
8946   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8947     return Op;
8948   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8949       Subtarget->is64Bit()) {
8950     return Op;
8951   }
8952
8953   SDLoc dl(Op);
8954   unsigned Size = SrcVT.getSizeInBits()/8;
8955   MachineFunction &MF = DAG.getMachineFunction();
8956   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8957   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8958   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8959                                StackSlot,
8960                                MachinePointerInfo::getFixedStack(SSFI),
8961                                false, false, 0);
8962   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8963 }
8964
8965 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8966                                      SDValue StackSlot,
8967                                      SelectionDAG &DAG) const {
8968   // Build the FILD
8969   SDLoc DL(Op);
8970   SDVTList Tys;
8971   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8972   if (useSSE)
8973     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8974   else
8975     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8976
8977   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8978
8979   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8980   MachineMemOperand *MMO;
8981   if (FI) {
8982     int SSFI = FI->getIndex();
8983     MMO =
8984       DAG.getMachineFunction()
8985       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8986                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8987   } else {
8988     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8989     StackSlot = StackSlot.getOperand(1);
8990   }
8991   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8992   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8993                                            X86ISD::FILD, DL,
8994                                            Tys, Ops, SrcVT, MMO);
8995
8996   if (useSSE) {
8997     Chain = Result.getValue(1);
8998     SDValue InFlag = Result.getValue(2);
8999
9000     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9001     // shouldn't be necessary except that RFP cannot be live across
9002     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9003     MachineFunction &MF = DAG.getMachineFunction();
9004     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9005     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9006     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9007     Tys = DAG.getVTList(MVT::Other);
9008     SDValue Ops[] = {
9009       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9010     };
9011     MachineMemOperand *MMO =
9012       DAG.getMachineFunction()
9013       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9014                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9015
9016     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9017                                     Ops, Op.getValueType(), MMO);
9018     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9019                          MachinePointerInfo::getFixedStack(SSFI),
9020                          false, false, false, 0);
9021   }
9022
9023   return Result;
9024 }
9025
9026 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9027 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9028                                                SelectionDAG &DAG) const {
9029   // This algorithm is not obvious. Here it is what we're trying to output:
9030   /*
9031      movq       %rax,  %xmm0
9032      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9033      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9034      #ifdef __SSE3__
9035        haddpd   %xmm0, %xmm0
9036      #else
9037        pshufd   $0x4e, %xmm0, %xmm1
9038        addpd    %xmm1, %xmm0
9039      #endif
9040   */
9041
9042   SDLoc dl(Op);
9043   LLVMContext *Context = DAG.getContext();
9044
9045   // Build some magic constants.
9046   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9047   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9048   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9049
9050   SmallVector<Constant*,2> CV1;
9051   CV1.push_back(
9052     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9053                                       APInt(64, 0x4330000000000000ULL))));
9054   CV1.push_back(
9055     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9056                                       APInt(64, 0x4530000000000000ULL))));
9057   Constant *C1 = ConstantVector::get(CV1);
9058   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9059
9060   // Load the 64-bit value into an XMM register.
9061   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9062                             Op.getOperand(0));
9063   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9064                               MachinePointerInfo::getConstantPool(),
9065                               false, false, false, 16);
9066   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9067                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9068                               CLod0);
9069
9070   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9071                               MachinePointerInfo::getConstantPool(),
9072                               false, false, false, 16);
9073   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9074   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9075   SDValue Result;
9076
9077   if (Subtarget->hasSSE3()) {
9078     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9079     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9080   } else {
9081     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9082     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9083                                            S2F, 0x4E, DAG);
9084     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9085                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9086                          Sub);
9087   }
9088
9089   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9090                      DAG.getIntPtrConstant(0));
9091 }
9092
9093 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9094 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9095                                                SelectionDAG &DAG) const {
9096   SDLoc dl(Op);
9097   // FP constant to bias correct the final result.
9098   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9099                                    MVT::f64);
9100
9101   // Load the 32-bit value into an XMM register.
9102   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9103                              Op.getOperand(0));
9104
9105   // Zero out the upper parts of the register.
9106   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9107
9108   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9109                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9110                      DAG.getIntPtrConstant(0));
9111
9112   // Or the load with the bias.
9113   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9114                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9115                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9116                                                    MVT::v2f64, Load)),
9117                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9118                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9119                                                    MVT::v2f64, Bias)));
9120   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9121                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9122                    DAG.getIntPtrConstant(0));
9123
9124   // Subtract the bias.
9125   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9126
9127   // Handle final rounding.
9128   EVT DestVT = Op.getValueType();
9129
9130   if (DestVT.bitsLT(MVT::f64))
9131     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9132                        DAG.getIntPtrConstant(0));
9133   if (DestVT.bitsGT(MVT::f64))
9134     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9135
9136   // Handle final rounding.
9137   return Sub;
9138 }
9139
9140 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9141                                                SelectionDAG &DAG) const {
9142   SDValue N0 = Op.getOperand(0);
9143   MVT SVT = N0.getSimpleValueType();
9144   SDLoc dl(Op);
9145
9146   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9147           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9148          "Custom UINT_TO_FP is not supported!");
9149
9150   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9151   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9152                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9153 }
9154
9155 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9156                                            SelectionDAG &DAG) const {
9157   SDValue N0 = Op.getOperand(0);
9158   SDLoc dl(Op);
9159
9160   if (Op.getValueType().isVector())
9161     return lowerUINT_TO_FP_vec(Op, DAG);
9162
9163   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9164   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9165   // the optimization here.
9166   if (DAG.SignBitIsZero(N0))
9167     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9168
9169   MVT SrcVT = N0.getSimpleValueType();
9170   MVT DstVT = Op.getSimpleValueType();
9171   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9172     return LowerUINT_TO_FP_i64(Op, DAG);
9173   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9174     return LowerUINT_TO_FP_i32(Op, DAG);
9175   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9176     return SDValue();
9177
9178   // Make a 64-bit buffer, and use it to build an FILD.
9179   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9180   if (SrcVT == MVT::i32) {
9181     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9182     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9183                                      getPointerTy(), StackSlot, WordOff);
9184     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9185                                   StackSlot, MachinePointerInfo(),
9186                                   false, false, 0);
9187     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9188                                   OffsetSlot, MachinePointerInfo(),
9189                                   false, false, 0);
9190     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9191     return Fild;
9192   }
9193
9194   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9195   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9196                                StackSlot, MachinePointerInfo(),
9197                                false, false, 0);
9198   // For i64 source, we need to add the appropriate power of 2 if the input
9199   // was negative.  This is the same as the optimization in
9200   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9201   // we must be careful to do the computation in x87 extended precision, not
9202   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9203   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9204   MachineMemOperand *MMO =
9205     DAG.getMachineFunction()
9206     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9207                           MachineMemOperand::MOLoad, 8, 8);
9208
9209   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9210   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9211   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9212                                          MVT::i64, MMO);
9213
9214   APInt FF(32, 0x5F800000ULL);
9215
9216   // Check whether the sign bit is set.
9217   SDValue SignSet = DAG.getSetCC(dl,
9218                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9219                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9220                                  ISD::SETLT);
9221
9222   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9223   SDValue FudgePtr = DAG.getConstantPool(
9224                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9225                                          getPointerTy());
9226
9227   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9228   SDValue Zero = DAG.getIntPtrConstant(0);
9229   SDValue Four = DAG.getIntPtrConstant(4);
9230   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9231                                Zero, Four);
9232   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9233
9234   // Load the value out, extending it from f32 to f80.
9235   // FIXME: Avoid the extend by constructing the right constant pool?
9236   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9237                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9238                                  MVT::f32, false, false, 4);
9239   // Extend everything to 80 bits to force it to be done on x87.
9240   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9241   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9242 }
9243
9244 std::pair<SDValue,SDValue>
9245 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9246                                     bool IsSigned, bool IsReplace) const {
9247   SDLoc DL(Op);
9248
9249   EVT DstTy = Op.getValueType();
9250
9251   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9252     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9253     DstTy = MVT::i64;
9254   }
9255
9256   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9257          DstTy.getSimpleVT() >= MVT::i16 &&
9258          "Unknown FP_TO_INT to lower!");
9259
9260   // These are really Legal.
9261   if (DstTy == MVT::i32 &&
9262       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9263     return std::make_pair(SDValue(), SDValue());
9264   if (Subtarget->is64Bit() &&
9265       DstTy == MVT::i64 &&
9266       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9267     return std::make_pair(SDValue(), SDValue());
9268
9269   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9270   // stack slot, or into the FTOL runtime function.
9271   MachineFunction &MF = DAG.getMachineFunction();
9272   unsigned MemSize = DstTy.getSizeInBits()/8;
9273   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9274   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9275
9276   unsigned Opc;
9277   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9278     Opc = X86ISD::WIN_FTOL;
9279   else
9280     switch (DstTy.getSimpleVT().SimpleTy) {
9281     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9282     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9283     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9284     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9285     }
9286
9287   SDValue Chain = DAG.getEntryNode();
9288   SDValue Value = Op.getOperand(0);
9289   EVT TheVT = Op.getOperand(0).getValueType();
9290   // FIXME This causes a redundant load/store if the SSE-class value is already
9291   // in memory, such as if it is on the callstack.
9292   if (isScalarFPTypeInSSEReg(TheVT)) {
9293     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9294     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9295                          MachinePointerInfo::getFixedStack(SSFI),
9296                          false, false, 0);
9297     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9298     SDValue Ops[] = {
9299       Chain, StackSlot, DAG.getValueType(TheVT)
9300     };
9301
9302     MachineMemOperand *MMO =
9303       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9304                               MachineMemOperand::MOLoad, MemSize, MemSize);
9305     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9306     Chain = Value.getValue(1);
9307     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9308     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9309   }
9310
9311   MachineMemOperand *MMO =
9312     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9313                             MachineMemOperand::MOStore, MemSize, MemSize);
9314
9315   if (Opc != X86ISD::WIN_FTOL) {
9316     // Build the FP_TO_INT*_IN_MEM
9317     SDValue Ops[] = { Chain, Value, StackSlot };
9318     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9319                                            Ops, DstTy, MMO);
9320     return std::make_pair(FIST, StackSlot);
9321   } else {
9322     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9323       DAG.getVTList(MVT::Other, MVT::Glue),
9324       Chain, Value);
9325     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9326       MVT::i32, ftol.getValue(1));
9327     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9328       MVT::i32, eax.getValue(2));
9329     SDValue Ops[] = { eax, edx };
9330     SDValue pair = IsReplace
9331       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9332       : DAG.getMergeValues(Ops, DL);
9333     return std::make_pair(pair, SDValue());
9334   }
9335 }
9336
9337 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9338                               const X86Subtarget *Subtarget) {
9339   MVT VT = Op->getSimpleValueType(0);
9340   SDValue In = Op->getOperand(0);
9341   MVT InVT = In.getSimpleValueType();
9342   SDLoc dl(Op);
9343
9344   // Optimize vectors in AVX mode:
9345   //
9346   //   v8i16 -> v8i32
9347   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9348   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9349   //   Concat upper and lower parts.
9350   //
9351   //   v4i32 -> v4i64
9352   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9353   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9354   //   Concat upper and lower parts.
9355   //
9356
9357   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9358       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9359       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9360     return SDValue();
9361
9362   if (Subtarget->hasInt256())
9363     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9364
9365   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9366   SDValue Undef = DAG.getUNDEF(InVT);
9367   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9368   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9369   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9370
9371   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9372                              VT.getVectorNumElements()/2);
9373
9374   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9375   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9376
9377   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9378 }
9379
9380 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9381                                         SelectionDAG &DAG) {
9382   MVT VT = Op->getSimpleValueType(0);
9383   SDValue In = Op->getOperand(0);
9384   MVT InVT = In.getSimpleValueType();
9385   SDLoc DL(Op);
9386   unsigned int NumElts = VT.getVectorNumElements();
9387   if (NumElts != 8 && NumElts != 16)
9388     return SDValue();
9389
9390   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9391     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9392
9393   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9395   // Now we have only mask extension
9396   assert(InVT.getVectorElementType() == MVT::i1);
9397   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9398   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9399   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9400   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9401   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9402                            MachinePointerInfo::getConstantPool(),
9403                            false, false, false, Alignment);
9404
9405   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9406   if (VT.is512BitVector())
9407     return Brcst;
9408   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9409 }
9410
9411 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9412                                SelectionDAG &DAG) {
9413   if (Subtarget->hasFp256()) {
9414     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9415     if (Res.getNode())
9416       return Res;
9417   }
9418
9419   return SDValue();
9420 }
9421
9422 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9423                                 SelectionDAG &DAG) {
9424   SDLoc DL(Op);
9425   MVT VT = Op.getSimpleValueType();
9426   SDValue In = Op.getOperand(0);
9427   MVT SVT = In.getSimpleValueType();
9428
9429   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9430     return LowerZERO_EXTEND_AVX512(Op, DAG);
9431
9432   if (Subtarget->hasFp256()) {
9433     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9434     if (Res.getNode())
9435       return Res;
9436   }
9437
9438   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9439          VT.getVectorNumElements() != SVT.getVectorNumElements());
9440   return SDValue();
9441 }
9442
9443 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9444   SDLoc DL(Op);
9445   MVT VT = Op.getSimpleValueType();
9446   SDValue In = Op.getOperand(0);
9447   MVT InVT = In.getSimpleValueType();
9448
9449   if (VT == MVT::i1) {
9450     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9451            "Invalid scalar TRUNCATE operation");
9452     if (InVT == MVT::i32)
9453       return SDValue();
9454     if (InVT.getSizeInBits() == 64)
9455       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9456     else if (InVT.getSizeInBits() < 32)
9457       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9458     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9459   }
9460   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9461          "Invalid TRUNCATE operation");
9462
9463   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9464     if (VT.getVectorElementType().getSizeInBits() >=8)
9465       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9466
9467     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9468     unsigned NumElts = InVT.getVectorNumElements();
9469     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9470     if (InVT.getSizeInBits() < 512) {
9471       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9472       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9473       InVT = ExtVT;
9474     }
9475     
9476     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9477     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9478     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9479     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9480     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9481                            MachinePointerInfo::getConstantPool(),
9482                            false, false, false, Alignment);
9483     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9484     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9485     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9486   }
9487
9488   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9489     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9490     if (Subtarget->hasInt256()) {
9491       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9492       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9493       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9494                                 ShufMask);
9495       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9496                          DAG.getIntPtrConstant(0));
9497     }
9498
9499     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9500                                DAG.getIntPtrConstant(0));
9501     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9502                                DAG.getIntPtrConstant(2));
9503     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9504     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9505     static const int ShufMask[] = {0, 2, 4, 6};
9506     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9507   }
9508
9509   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9510     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9511     if (Subtarget->hasInt256()) {
9512       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9513
9514       SmallVector<SDValue,32> pshufbMask;
9515       for (unsigned i = 0; i < 2; ++i) {
9516         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9517         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9518         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9519         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9520         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9521         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9522         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9523         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9524         for (unsigned j = 0; j < 8; ++j)
9525           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9526       }
9527       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9528       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9529       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9530
9531       static const int ShufMask[] = {0,  2,  -1,  -1};
9532       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9533                                 &ShufMask[0]);
9534       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9535                        DAG.getIntPtrConstant(0));
9536       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9537     }
9538
9539     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9540                                DAG.getIntPtrConstant(0));
9541
9542     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9543                                DAG.getIntPtrConstant(4));
9544
9545     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9546     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9547
9548     // The PSHUFB mask:
9549     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9550                                    -1, -1, -1, -1, -1, -1, -1, -1};
9551
9552     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9553     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9554     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9555
9556     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9557     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9558
9559     // The MOVLHPS Mask:
9560     static const int ShufMask2[] = {0, 1, 4, 5};
9561     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9562     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9563   }
9564
9565   // Handle truncation of V256 to V128 using shuffles.
9566   if (!VT.is128BitVector() || !InVT.is256BitVector())
9567     return SDValue();
9568
9569   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9570
9571   unsigned NumElems = VT.getVectorNumElements();
9572   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9573
9574   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9575   // Prepare truncation shuffle mask
9576   for (unsigned i = 0; i != NumElems; ++i)
9577     MaskVec[i] = i * 2;
9578   SDValue V = DAG.getVectorShuffle(NVT, DL,
9579                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9580                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9581   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9582                      DAG.getIntPtrConstant(0));
9583 }
9584
9585 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9586                                            SelectionDAG &DAG) const {
9587   assert(!Op.getSimpleValueType().isVector());
9588
9589   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9590     /*IsSigned=*/ true, /*IsReplace=*/ false);
9591   SDValue FIST = Vals.first, StackSlot = Vals.second;
9592   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9593   if (!FIST.getNode()) return Op;
9594
9595   if (StackSlot.getNode())
9596     // Load the result.
9597     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9598                        FIST, StackSlot, MachinePointerInfo(),
9599                        false, false, false, 0);
9600
9601   // The node is the result.
9602   return FIST;
9603 }
9604
9605 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9606                                            SelectionDAG &DAG) const {
9607   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9608     /*IsSigned=*/ false, /*IsReplace=*/ false);
9609   SDValue FIST = Vals.first, StackSlot = Vals.second;
9610   assert(FIST.getNode() && "Unexpected failure");
9611
9612   if (StackSlot.getNode())
9613     // Load the result.
9614     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9615                        FIST, StackSlot, MachinePointerInfo(),
9616                        false, false, false, 0);
9617
9618   // The node is the result.
9619   return FIST;
9620 }
9621
9622 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9623   SDLoc DL(Op);
9624   MVT VT = Op.getSimpleValueType();
9625   SDValue In = Op.getOperand(0);
9626   MVT SVT = In.getSimpleValueType();
9627
9628   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9629
9630   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9631                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9632                                  In, DAG.getUNDEF(SVT)));
9633 }
9634
9635 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9636   LLVMContext *Context = DAG.getContext();
9637   SDLoc dl(Op);
9638   MVT VT = Op.getSimpleValueType();
9639   MVT EltVT = VT;
9640   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9641   if (VT.isVector()) {
9642     EltVT = VT.getVectorElementType();
9643     NumElts = VT.getVectorNumElements();
9644   }
9645   Constant *C;
9646   if (EltVT == MVT::f64)
9647     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9648                                           APInt(64, ~(1ULL << 63))));
9649   else
9650     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9651                                           APInt(32, ~(1U << 31))));
9652   C = ConstantVector::getSplat(NumElts, C);
9653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9654   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9655   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9656   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9657                              MachinePointerInfo::getConstantPool(),
9658                              false, false, false, Alignment);
9659   if (VT.isVector()) {
9660     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9661     return DAG.getNode(ISD::BITCAST, dl, VT,
9662                        DAG.getNode(ISD::AND, dl, ANDVT,
9663                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9664                                                Op.getOperand(0)),
9665                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9666   }
9667   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9668 }
9669
9670 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9671   LLVMContext *Context = DAG.getContext();
9672   SDLoc dl(Op);
9673   MVT VT = Op.getSimpleValueType();
9674   MVT EltVT = VT;
9675   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9676   if (VT.isVector()) {
9677     EltVT = VT.getVectorElementType();
9678     NumElts = VT.getVectorNumElements();
9679   }
9680   Constant *C;
9681   if (EltVT == MVT::f64)
9682     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9683                                           APInt(64, 1ULL << 63)));
9684   else
9685     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9686                                           APInt(32, 1U << 31)));
9687   C = ConstantVector::getSplat(NumElts, C);
9688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9689   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9690   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9691   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9692                              MachinePointerInfo::getConstantPool(),
9693                              false, false, false, Alignment);
9694   if (VT.isVector()) {
9695     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9696     return DAG.getNode(ISD::BITCAST, dl, VT,
9697                        DAG.getNode(ISD::XOR, dl, XORVT,
9698                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9699                                                Op.getOperand(0)),
9700                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9701   }
9702
9703   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9704 }
9705
9706 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9707   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9708   LLVMContext *Context = DAG.getContext();
9709   SDValue Op0 = Op.getOperand(0);
9710   SDValue Op1 = Op.getOperand(1);
9711   SDLoc dl(Op);
9712   MVT VT = Op.getSimpleValueType();
9713   MVT SrcVT = Op1.getSimpleValueType();
9714
9715   // If second operand is smaller, extend it first.
9716   if (SrcVT.bitsLT(VT)) {
9717     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9718     SrcVT = VT;
9719   }
9720   // And if it is bigger, shrink it first.
9721   if (SrcVT.bitsGT(VT)) {
9722     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9723     SrcVT = VT;
9724   }
9725
9726   // At this point the operands and the result should have the same
9727   // type, and that won't be f80 since that is not custom lowered.
9728
9729   // First get the sign bit of second operand.
9730   SmallVector<Constant*,4> CV;
9731   if (SrcVT == MVT::f64) {
9732     const fltSemantics &Sem = APFloat::IEEEdouble;
9733     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9734     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9735   } else {
9736     const fltSemantics &Sem = APFloat::IEEEsingle;
9737     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9738     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9739     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9740     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9741   }
9742   Constant *C = ConstantVector::get(CV);
9743   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9744   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9745                               MachinePointerInfo::getConstantPool(),
9746                               false, false, false, 16);
9747   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9748
9749   // Shift sign bit right or left if the two operands have different types.
9750   if (SrcVT.bitsGT(VT)) {
9751     // Op0 is MVT::f32, Op1 is MVT::f64.
9752     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9753     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9754                           DAG.getConstant(32, MVT::i32));
9755     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9756     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9757                           DAG.getIntPtrConstant(0));
9758   }
9759
9760   // Clear first operand sign bit.
9761   CV.clear();
9762   if (VT == MVT::f64) {
9763     const fltSemantics &Sem = APFloat::IEEEdouble;
9764     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9765                                                    APInt(64, ~(1ULL << 63)))));
9766     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9767   } else {
9768     const fltSemantics &Sem = APFloat::IEEEsingle;
9769     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9770                                                    APInt(32, ~(1U << 31)))));
9771     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9772     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9773     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9774   }
9775   C = ConstantVector::get(CV);
9776   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9777   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9778                               MachinePointerInfo::getConstantPool(),
9779                               false, false, false, 16);
9780   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9781
9782   // Or the value with the sign bit.
9783   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9784 }
9785
9786 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9787   SDValue N0 = Op.getOperand(0);
9788   SDLoc dl(Op);
9789   MVT VT = Op.getSimpleValueType();
9790
9791   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9792   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9793                                   DAG.getConstant(1, VT));
9794   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9795 }
9796
9797 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9798 //
9799 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9800                                       SelectionDAG &DAG) {
9801   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9802
9803   if (!Subtarget->hasSSE41())
9804     return SDValue();
9805
9806   if (!Op->hasOneUse())
9807     return SDValue();
9808
9809   SDNode *N = Op.getNode();
9810   SDLoc DL(N);
9811
9812   SmallVector<SDValue, 8> Opnds;
9813   DenseMap<SDValue, unsigned> VecInMap;
9814   SmallVector<SDValue, 8> VecIns;
9815   EVT VT = MVT::Other;
9816
9817   // Recognize a special case where a vector is casted into wide integer to
9818   // test all 0s.
9819   Opnds.push_back(N->getOperand(0));
9820   Opnds.push_back(N->getOperand(1));
9821
9822   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9823     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9824     // BFS traverse all OR'd operands.
9825     if (I->getOpcode() == ISD::OR) {
9826       Opnds.push_back(I->getOperand(0));
9827       Opnds.push_back(I->getOperand(1));
9828       // Re-evaluate the number of nodes to be traversed.
9829       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9830       continue;
9831     }
9832
9833     // Quit if a non-EXTRACT_VECTOR_ELT
9834     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9835       return SDValue();
9836
9837     // Quit if without a constant index.
9838     SDValue Idx = I->getOperand(1);
9839     if (!isa<ConstantSDNode>(Idx))
9840       return SDValue();
9841
9842     SDValue ExtractedFromVec = I->getOperand(0);
9843     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9844     if (M == VecInMap.end()) {
9845       VT = ExtractedFromVec.getValueType();
9846       // Quit if not 128/256-bit vector.
9847       if (!VT.is128BitVector() && !VT.is256BitVector())
9848         return SDValue();
9849       // Quit if not the same type.
9850       if (VecInMap.begin() != VecInMap.end() &&
9851           VT != VecInMap.begin()->first.getValueType())
9852         return SDValue();
9853       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9854       VecIns.push_back(ExtractedFromVec);
9855     }
9856     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9857   }
9858
9859   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9860          "Not extracted from 128-/256-bit vector.");
9861
9862   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9863
9864   for (DenseMap<SDValue, unsigned>::const_iterator
9865         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9866     // Quit if not all elements are used.
9867     if (I->second != FullMask)
9868       return SDValue();
9869   }
9870
9871   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9872
9873   // Cast all vectors into TestVT for PTEST.
9874   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9875     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9876
9877   // If more than one full vectors are evaluated, OR them first before PTEST.
9878   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9879     // Each iteration will OR 2 nodes and append the result until there is only
9880     // 1 node left, i.e. the final OR'd value of all vectors.
9881     SDValue LHS = VecIns[Slot];
9882     SDValue RHS = VecIns[Slot + 1];
9883     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9884   }
9885
9886   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9887                      VecIns.back(), VecIns.back());
9888 }
9889
9890 /// \brief return true if \c Op has a use that doesn't just read flags.
9891 static bool hasNonFlagsUse(SDValue Op) {
9892   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9893        ++UI) {
9894     SDNode *User = *UI;
9895     unsigned UOpNo = UI.getOperandNo();
9896     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9897       // Look pass truncate.
9898       UOpNo = User->use_begin().getOperandNo();
9899       User = *User->use_begin();
9900     }
9901
9902     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9903         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9904       return true;
9905   }
9906   return false;
9907 }
9908
9909 /// Emit nodes that will be selected as "test Op0,Op0", or something
9910 /// equivalent.
9911 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9912                                     SelectionDAG &DAG) const {
9913   if (Op.getValueType() == MVT::i1)
9914     // KORTEST instruction should be selected
9915     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9916                        DAG.getConstant(0, Op.getValueType()));
9917
9918   // CF and OF aren't always set the way we want. Determine which
9919   // of these we need.
9920   bool NeedCF = false;
9921   bool NeedOF = false;
9922   switch (X86CC) {
9923   default: break;
9924   case X86::COND_A: case X86::COND_AE:
9925   case X86::COND_B: case X86::COND_BE:
9926     NeedCF = true;
9927     break;
9928   case X86::COND_G: case X86::COND_GE:
9929   case X86::COND_L: case X86::COND_LE:
9930   case X86::COND_O: case X86::COND_NO:
9931     NeedOF = true;
9932     break;
9933   }
9934   // See if we can use the EFLAGS value from the operand instead of
9935   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9936   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9937   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9938     // Emit a CMP with 0, which is the TEST pattern.
9939     //if (Op.getValueType() == MVT::i1)
9940     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9941     //                     DAG.getConstant(0, MVT::i1));
9942     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9943                        DAG.getConstant(0, Op.getValueType()));
9944   }
9945   unsigned Opcode = 0;
9946   unsigned NumOperands = 0;
9947
9948   // Truncate operations may prevent the merge of the SETCC instruction
9949   // and the arithmetic instruction before it. Attempt to truncate the operands
9950   // of the arithmetic instruction and use a reduced bit-width instruction.
9951   bool NeedTruncation = false;
9952   SDValue ArithOp = Op;
9953   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9954     SDValue Arith = Op->getOperand(0);
9955     // Both the trunc and the arithmetic op need to have one user each.
9956     if (Arith->hasOneUse())
9957       switch (Arith.getOpcode()) {
9958         default: break;
9959         case ISD::ADD:
9960         case ISD::SUB:
9961         case ISD::AND:
9962         case ISD::OR:
9963         case ISD::XOR: {
9964           NeedTruncation = true;
9965           ArithOp = Arith;
9966         }
9967       }
9968   }
9969
9970   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9971   // which may be the result of a CAST.  We use the variable 'Op', which is the
9972   // non-casted variable when we check for possible users.
9973   switch (ArithOp.getOpcode()) {
9974   case ISD::ADD:
9975     // Due to an isel shortcoming, be conservative if this add is likely to be
9976     // selected as part of a load-modify-store instruction. When the root node
9977     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9978     // uses of other nodes in the match, such as the ADD in this case. This
9979     // leads to the ADD being left around and reselected, with the result being
9980     // two adds in the output.  Alas, even if none our users are stores, that
9981     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9982     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9983     // climbing the DAG back to the root, and it doesn't seem to be worth the
9984     // effort.
9985     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9986          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9987       if (UI->getOpcode() != ISD::CopyToReg &&
9988           UI->getOpcode() != ISD::SETCC &&
9989           UI->getOpcode() != ISD::STORE)
9990         goto default_case;
9991
9992     if (ConstantSDNode *C =
9993         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9994       // An add of one will be selected as an INC.
9995       if (C->getAPIntValue() == 1) {
9996         Opcode = X86ISD::INC;
9997         NumOperands = 1;
9998         break;
9999       }
10000
10001       // An add of negative one (subtract of one) will be selected as a DEC.
10002       if (C->getAPIntValue().isAllOnesValue()) {
10003         Opcode = X86ISD::DEC;
10004         NumOperands = 1;
10005         break;
10006       }
10007     }
10008
10009     // Otherwise use a regular EFLAGS-setting add.
10010     Opcode = X86ISD::ADD;
10011     NumOperands = 2;
10012     break;
10013   case ISD::SHL:
10014   case ISD::SRL:
10015     // If we have a constant logical shift that's only used in a comparison
10016     // against zero turn it into an equivalent AND. This allows turning it into
10017     // a TEST instruction later.
10018     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
10019         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10020       EVT VT = Op.getValueType();
10021       unsigned BitWidth = VT.getSizeInBits();
10022       unsigned ShAmt = Op->getConstantOperandVal(1);
10023       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10024         break;
10025       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10026                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10027                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10028       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10029         break;
10030       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10031                                 DAG.getConstant(Mask, VT));
10032       DAG.ReplaceAllUsesWith(Op, New);
10033       Op = New;
10034     }
10035     break;
10036
10037   case ISD::AND:
10038     // If the primary and result isn't used, don't bother using X86ISD::AND,
10039     // because a TEST instruction will be better.
10040     if (!hasNonFlagsUse(Op))
10041       break;
10042     // FALL THROUGH
10043   case ISD::SUB:
10044   case ISD::OR:
10045   case ISD::XOR:
10046     // Due to the ISEL shortcoming noted above, be conservative if this op is
10047     // likely to be selected as part of a load-modify-store instruction.
10048     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10049            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10050       if (UI->getOpcode() == ISD::STORE)
10051         goto default_case;
10052
10053     // Otherwise use a regular EFLAGS-setting instruction.
10054     switch (ArithOp.getOpcode()) {
10055     default: llvm_unreachable("unexpected operator!");
10056     case ISD::SUB: Opcode = X86ISD::SUB; break;
10057     case ISD::XOR: Opcode = X86ISD::XOR; break;
10058     case ISD::AND: Opcode = X86ISD::AND; break;
10059     case ISD::OR: {
10060       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10061         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10062         if (EFLAGS.getNode())
10063           return EFLAGS;
10064       }
10065       Opcode = X86ISD::OR;
10066       break;
10067     }
10068     }
10069
10070     NumOperands = 2;
10071     break;
10072   case X86ISD::ADD:
10073   case X86ISD::SUB:
10074   case X86ISD::INC:
10075   case X86ISD::DEC:
10076   case X86ISD::OR:
10077   case X86ISD::XOR:
10078   case X86ISD::AND:
10079     return SDValue(Op.getNode(), 1);
10080   default:
10081   default_case:
10082     break;
10083   }
10084
10085   // If we found that truncation is beneficial, perform the truncation and
10086   // update 'Op'.
10087   if (NeedTruncation) {
10088     EVT VT = Op.getValueType();
10089     SDValue WideVal = Op->getOperand(0);
10090     EVT WideVT = WideVal.getValueType();
10091     unsigned ConvertedOp = 0;
10092     // Use a target machine opcode to prevent further DAGCombine
10093     // optimizations that may separate the arithmetic operations
10094     // from the setcc node.
10095     switch (WideVal.getOpcode()) {
10096       default: break;
10097       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10098       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10099       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10100       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10101       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10102     }
10103
10104     if (ConvertedOp) {
10105       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10106       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10107         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10108         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10109         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10110       }
10111     }
10112   }
10113
10114   if (Opcode == 0)
10115     // Emit a CMP with 0, which is the TEST pattern.
10116     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10117                        DAG.getConstant(0, Op.getValueType()));
10118
10119   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10120   SmallVector<SDValue, 4> Ops;
10121   for (unsigned i = 0; i != NumOperands; ++i)
10122     Ops.push_back(Op.getOperand(i));
10123
10124   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10125   DAG.ReplaceAllUsesWith(Op, New);
10126   return SDValue(New.getNode(), 1);
10127 }
10128
10129 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10130 /// equivalent.
10131 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10132                                    SDLoc dl, SelectionDAG &DAG) const {
10133   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10134     if (C->getAPIntValue() == 0)
10135       return EmitTest(Op0, X86CC, dl, DAG);
10136
10137      if (Op0.getValueType() == MVT::i1)
10138        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10139   }
10140  
10141   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10142        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10143     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10144     // This avoids subregister aliasing issues. Keep the smaller reference 
10145     // if we're optimizing for size, however, as that'll allow better folding 
10146     // of memory operations.
10147     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10148         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10149              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10150         !Subtarget->isAtom()) {
10151       unsigned ExtendOp =
10152           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10153       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10154       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10155     }
10156     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10157     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10158     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10159                               Op0, Op1);
10160     return SDValue(Sub.getNode(), 1);
10161   }
10162   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10163 }
10164
10165 /// Convert a comparison if required by the subtarget.
10166 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10167                                                  SelectionDAG &DAG) const {
10168   // If the subtarget does not support the FUCOMI instruction, floating-point
10169   // comparisons have to be converted.
10170   if (Subtarget->hasCMov() ||
10171       Cmp.getOpcode() != X86ISD::CMP ||
10172       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10173       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10174     return Cmp;
10175
10176   // The instruction selector will select an FUCOM instruction instead of
10177   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10178   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10179   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10180   SDLoc dl(Cmp);
10181   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10182   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10183   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10184                             DAG.getConstant(8, MVT::i8));
10185   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10186   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10187 }
10188
10189 static bool isAllOnes(SDValue V) {
10190   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10191   return C && C->isAllOnesValue();
10192 }
10193
10194 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10195 /// if it's possible.
10196 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10197                                      SDLoc dl, SelectionDAG &DAG) const {
10198   SDValue Op0 = And.getOperand(0);
10199   SDValue Op1 = And.getOperand(1);
10200   if (Op0.getOpcode() == ISD::TRUNCATE)
10201     Op0 = Op0.getOperand(0);
10202   if (Op1.getOpcode() == ISD::TRUNCATE)
10203     Op1 = Op1.getOperand(0);
10204
10205   SDValue LHS, RHS;
10206   if (Op1.getOpcode() == ISD::SHL)
10207     std::swap(Op0, Op1);
10208   if (Op0.getOpcode() == ISD::SHL) {
10209     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10210       if (And00C->getZExtValue() == 1) {
10211         // If we looked past a truncate, check that it's only truncating away
10212         // known zeros.
10213         unsigned BitWidth = Op0.getValueSizeInBits();
10214         unsigned AndBitWidth = And.getValueSizeInBits();
10215         if (BitWidth > AndBitWidth) {
10216           APInt Zeros, Ones;
10217           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10218           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10219             return SDValue();
10220         }
10221         LHS = Op1;
10222         RHS = Op0.getOperand(1);
10223       }
10224   } else if (Op1.getOpcode() == ISD::Constant) {
10225     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10226     uint64_t AndRHSVal = AndRHS->getZExtValue();
10227     SDValue AndLHS = Op0;
10228
10229     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10230       LHS = AndLHS.getOperand(0);
10231       RHS = AndLHS.getOperand(1);
10232     }
10233
10234     // Use BT if the immediate can't be encoded in a TEST instruction.
10235     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10236       LHS = AndLHS;
10237       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10238     }
10239   }
10240
10241   if (LHS.getNode()) {
10242     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10243     // instruction.  Since the shift amount is in-range-or-undefined, we know
10244     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10245     // the encoding for the i16 version is larger than the i32 version.
10246     // Also promote i16 to i32 for performance / code size reason.
10247     if (LHS.getValueType() == MVT::i8 ||
10248         LHS.getValueType() == MVT::i16)
10249       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10250
10251     // If the operand types disagree, extend the shift amount to match.  Since
10252     // BT ignores high bits (like shifts) we can use anyextend.
10253     if (LHS.getValueType() != RHS.getValueType())
10254       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10255
10256     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10257     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10258     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10259                        DAG.getConstant(Cond, MVT::i8), BT);
10260   }
10261
10262   return SDValue();
10263 }
10264
10265 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10266 /// mask CMPs.
10267 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10268                               SDValue &Op1) {
10269   unsigned SSECC;
10270   bool Swap = false;
10271
10272   // SSE Condition code mapping:
10273   //  0 - EQ
10274   //  1 - LT
10275   //  2 - LE
10276   //  3 - UNORD
10277   //  4 - NEQ
10278   //  5 - NLT
10279   //  6 - NLE
10280   //  7 - ORD
10281   switch (SetCCOpcode) {
10282   default: llvm_unreachable("Unexpected SETCC condition");
10283   case ISD::SETOEQ:
10284   case ISD::SETEQ:  SSECC = 0; break;
10285   case ISD::SETOGT:
10286   case ISD::SETGT:  Swap = true; // Fallthrough
10287   case ISD::SETLT:
10288   case ISD::SETOLT: SSECC = 1; break;
10289   case ISD::SETOGE:
10290   case ISD::SETGE:  Swap = true; // Fallthrough
10291   case ISD::SETLE:
10292   case ISD::SETOLE: SSECC = 2; break;
10293   case ISD::SETUO:  SSECC = 3; break;
10294   case ISD::SETUNE:
10295   case ISD::SETNE:  SSECC = 4; break;
10296   case ISD::SETULE: Swap = true; // Fallthrough
10297   case ISD::SETUGE: SSECC = 5; break;
10298   case ISD::SETULT: Swap = true; // Fallthrough
10299   case ISD::SETUGT: SSECC = 6; break;
10300   case ISD::SETO:   SSECC = 7; break;
10301   case ISD::SETUEQ:
10302   case ISD::SETONE: SSECC = 8; break;
10303   }
10304   if (Swap)
10305     std::swap(Op0, Op1);
10306
10307   return SSECC;
10308 }
10309
10310 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10311 // ones, and then concatenate the result back.
10312 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10313   MVT VT = Op.getSimpleValueType();
10314
10315   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10316          "Unsupported value type for operation");
10317
10318   unsigned NumElems = VT.getVectorNumElements();
10319   SDLoc dl(Op);
10320   SDValue CC = Op.getOperand(2);
10321
10322   // Extract the LHS vectors
10323   SDValue LHS = Op.getOperand(0);
10324   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10325   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10326
10327   // Extract the RHS vectors
10328   SDValue RHS = Op.getOperand(1);
10329   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10330   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10331
10332   // Issue the operation on the smaller types and concatenate the result back
10333   MVT EltVT = VT.getVectorElementType();
10334   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10335   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10336                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10337                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10338 }
10339
10340 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10341                                      const X86Subtarget *Subtarget) {
10342   SDValue Op0 = Op.getOperand(0);
10343   SDValue Op1 = Op.getOperand(1);
10344   SDValue CC = Op.getOperand(2);
10345   MVT VT = Op.getSimpleValueType();
10346   SDLoc dl(Op);
10347
10348   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10349          Op.getValueType().getScalarType() == MVT::i1 &&
10350          "Cannot set masked compare for this operation");
10351
10352   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10353   unsigned  Opc = 0;
10354   bool Unsigned = false;
10355   bool Swap = false;
10356   unsigned SSECC;
10357   switch (SetCCOpcode) {
10358   default: llvm_unreachable("Unexpected SETCC condition");
10359   case ISD::SETNE:  SSECC = 4; break;
10360   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10361   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10362   case ISD::SETLT:  Swap = true; //fall-through
10363   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10364   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10365   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10366   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10367   case ISD::SETULE: Unsigned = true; //fall-through
10368   case ISD::SETLE:  SSECC = 2; break;
10369   }
10370
10371   if (Swap)
10372     std::swap(Op0, Op1);
10373   if (Opc)
10374     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10375   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10376   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10377                      DAG.getConstant(SSECC, MVT::i8));
10378 }
10379
10380 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10381 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10382 /// return an empty value.
10383 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10384 {
10385   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10386   if (!BV)
10387     return SDValue();
10388
10389   MVT VT = Op1.getSimpleValueType();
10390   MVT EVT = VT.getVectorElementType();
10391   unsigned n = VT.getVectorNumElements();
10392   SmallVector<SDValue, 8> ULTOp1;
10393
10394   for (unsigned i = 0; i < n; ++i) {
10395     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10396     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10397       return SDValue();
10398
10399     // Avoid underflow.
10400     APInt Val = Elt->getAPIntValue();
10401     if (Val == 0)
10402       return SDValue();
10403
10404     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10405   }
10406
10407   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10408 }
10409
10410 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10411                            SelectionDAG &DAG) {
10412   SDValue Op0 = Op.getOperand(0);
10413   SDValue Op1 = Op.getOperand(1);
10414   SDValue CC = Op.getOperand(2);
10415   MVT VT = Op.getSimpleValueType();
10416   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10417   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10418   SDLoc dl(Op);
10419
10420   if (isFP) {
10421 #ifndef NDEBUG
10422     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10423     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10424 #endif
10425
10426     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10427     unsigned Opc = X86ISD::CMPP;
10428     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10429       assert(VT.getVectorNumElements() <= 16);
10430       Opc = X86ISD::CMPM;
10431     }
10432     // In the two special cases we can't handle, emit two comparisons.
10433     if (SSECC == 8) {
10434       unsigned CC0, CC1;
10435       unsigned CombineOpc;
10436       if (SetCCOpcode == ISD::SETUEQ) {
10437         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10438       } else {
10439         assert(SetCCOpcode == ISD::SETONE);
10440         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10441       }
10442
10443       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10444                                  DAG.getConstant(CC0, MVT::i8));
10445       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10446                                  DAG.getConstant(CC1, MVT::i8));
10447       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10448     }
10449     // Handle all other FP comparisons here.
10450     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10451                        DAG.getConstant(SSECC, MVT::i8));
10452   }
10453
10454   // Break 256-bit integer vector compare into smaller ones.
10455   if (VT.is256BitVector() && !Subtarget->hasInt256())
10456     return Lower256IntVSETCC(Op, DAG);
10457
10458   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10459   EVT OpVT = Op1.getValueType();
10460   if (Subtarget->hasAVX512()) {
10461     if (Op1.getValueType().is512BitVector() ||
10462         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10463       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10464
10465     // In AVX-512 architecture setcc returns mask with i1 elements,
10466     // But there is no compare instruction for i8 and i16 elements.
10467     // We are not talking about 512-bit operands in this case, these
10468     // types are illegal.
10469     if (MaskResult &&
10470         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10471          OpVT.getVectorElementType().getSizeInBits() >= 8))
10472       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10473                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10474   }
10475
10476   // We are handling one of the integer comparisons here.  Since SSE only has
10477   // GT and EQ comparisons for integer, swapping operands and multiple
10478   // operations may be required for some comparisons.
10479   unsigned Opc;
10480   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10481   bool Subus = false;
10482
10483   switch (SetCCOpcode) {
10484   default: llvm_unreachable("Unexpected SETCC condition");
10485   case ISD::SETNE:  Invert = true;
10486   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10487   case ISD::SETLT:  Swap = true;
10488   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10489   case ISD::SETGE:  Swap = true;
10490   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10491                     Invert = true; break;
10492   case ISD::SETULT: Swap = true;
10493   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10494                     FlipSigns = true; break;
10495   case ISD::SETUGE: Swap = true;
10496   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10497                     FlipSigns = true; Invert = true; break;
10498   }
10499
10500   // Special case: Use min/max operations for SETULE/SETUGE
10501   MVT VET = VT.getVectorElementType();
10502   bool hasMinMax =
10503        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10504     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10505
10506   if (hasMinMax) {
10507     switch (SetCCOpcode) {
10508     default: break;
10509     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10510     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10511     }
10512
10513     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10514   }
10515
10516   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10517   if (!MinMax && hasSubus) {
10518     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10519     // Op0 u<= Op1:
10520     //   t = psubus Op0, Op1
10521     //   pcmpeq t, <0..0>
10522     switch (SetCCOpcode) {
10523     default: break;
10524     case ISD::SETULT: {
10525       // If the comparison is against a constant we can turn this into a
10526       // setule.  With psubus, setule does not require a swap.  This is
10527       // beneficial because the constant in the register is no longer
10528       // destructed as the destination so it can be hoisted out of a loop.
10529       // Only do this pre-AVX since vpcmp* is no longer destructive.
10530       if (Subtarget->hasAVX())
10531         break;
10532       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10533       if (ULEOp1.getNode()) {
10534         Op1 = ULEOp1;
10535         Subus = true; Invert = false; Swap = false;
10536       }
10537       break;
10538     }
10539     // Psubus is better than flip-sign because it requires no inversion.
10540     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10541     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10542     }
10543
10544     if (Subus) {
10545       Opc = X86ISD::SUBUS;
10546       FlipSigns = false;
10547     }
10548   }
10549
10550   if (Swap)
10551     std::swap(Op0, Op1);
10552
10553   // Check that the operation in question is available (most are plain SSE2,
10554   // but PCMPGTQ and PCMPEQQ have different requirements).
10555   if (VT == MVT::v2i64) {
10556     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10557       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10558
10559       // First cast everything to the right type.
10560       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10561       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10562
10563       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10564       // bits of the inputs before performing those operations. The lower
10565       // compare is always unsigned.
10566       SDValue SB;
10567       if (FlipSigns) {
10568         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10569       } else {
10570         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10571         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10572         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10573                          Sign, Zero, Sign, Zero);
10574       }
10575       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10576       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10577
10578       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10579       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10580       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10581
10582       // Create masks for only the low parts/high parts of the 64 bit integers.
10583       static const int MaskHi[] = { 1, 1, 3, 3 };
10584       static const int MaskLo[] = { 0, 0, 2, 2 };
10585       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10586       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10587       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10588
10589       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10590       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10591
10592       if (Invert)
10593         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10594
10595       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10596     }
10597
10598     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10599       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10600       // pcmpeqd + pshufd + pand.
10601       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10602
10603       // First cast everything to the right type.
10604       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10605       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10606
10607       // Do the compare.
10608       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10609
10610       // Make sure the lower and upper halves are both all-ones.
10611       static const int Mask[] = { 1, 0, 3, 2 };
10612       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10613       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10614
10615       if (Invert)
10616         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10617
10618       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10619     }
10620   }
10621
10622   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10623   // bits of the inputs before performing those operations.
10624   if (FlipSigns) {
10625     EVT EltVT = VT.getVectorElementType();
10626     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10627     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10628     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10629   }
10630
10631   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10632
10633   // If the logical-not of the result is required, perform that now.
10634   if (Invert)
10635     Result = DAG.getNOT(dl, Result, VT);
10636
10637   if (MinMax)
10638     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10639
10640   if (Subus)
10641     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10642                          getZeroVector(VT, Subtarget, DAG, dl));
10643
10644   return Result;
10645 }
10646
10647 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10648
10649   MVT VT = Op.getSimpleValueType();
10650
10651   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10652
10653   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10654          && "SetCC type must be 8-bit or 1-bit integer");
10655   SDValue Op0 = Op.getOperand(0);
10656   SDValue Op1 = Op.getOperand(1);
10657   SDLoc dl(Op);
10658   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10659
10660   // Optimize to BT if possible.
10661   // Lower (X & (1 << N)) == 0 to BT(X, N).
10662   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10663   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10664   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10665       Op1.getOpcode() == ISD::Constant &&
10666       cast<ConstantSDNode>(Op1)->isNullValue() &&
10667       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10668     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10669     if (NewSetCC.getNode())
10670       return NewSetCC;
10671   }
10672
10673   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10674   // these.
10675   if (Op1.getOpcode() == ISD::Constant &&
10676       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10677        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10678       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10679
10680     // If the input is a setcc, then reuse the input setcc or use a new one with
10681     // the inverted condition.
10682     if (Op0.getOpcode() == X86ISD::SETCC) {
10683       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10684       bool Invert = (CC == ISD::SETNE) ^
10685         cast<ConstantSDNode>(Op1)->isNullValue();
10686       if (!Invert)
10687         return Op0;
10688
10689       CCode = X86::GetOppositeBranchCondition(CCode);
10690       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10691                                   DAG.getConstant(CCode, MVT::i8),
10692                                   Op0.getOperand(1));
10693       if (VT == MVT::i1)
10694         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10695       return SetCC;
10696     }
10697   }
10698   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10699       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10700       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10701
10702     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10703     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10704   }
10705
10706   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10707   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10708   if (X86CC == X86::COND_INVALID)
10709     return SDValue();
10710
10711   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10712   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10713   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10714                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10715   if (VT == MVT::i1)
10716     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10717   return SetCC;
10718 }
10719
10720 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10721 static bool isX86LogicalCmp(SDValue Op) {
10722   unsigned Opc = Op.getNode()->getOpcode();
10723   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10724       Opc == X86ISD::SAHF)
10725     return true;
10726   if (Op.getResNo() == 1 &&
10727       (Opc == X86ISD::ADD ||
10728        Opc == X86ISD::SUB ||
10729        Opc == X86ISD::ADC ||
10730        Opc == X86ISD::SBB ||
10731        Opc == X86ISD::SMUL ||
10732        Opc == X86ISD::UMUL ||
10733        Opc == X86ISD::INC ||
10734        Opc == X86ISD::DEC ||
10735        Opc == X86ISD::OR ||
10736        Opc == X86ISD::XOR ||
10737        Opc == X86ISD::AND))
10738     return true;
10739
10740   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10741     return true;
10742
10743   return false;
10744 }
10745
10746 static bool isZero(SDValue V) {
10747   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10748   return C && C->isNullValue();
10749 }
10750
10751 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10752   if (V.getOpcode() != ISD::TRUNCATE)
10753     return false;
10754
10755   SDValue VOp0 = V.getOperand(0);
10756   unsigned InBits = VOp0.getValueSizeInBits();
10757   unsigned Bits = V.getValueSizeInBits();
10758   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10759 }
10760
10761 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10762   bool addTest = true;
10763   SDValue Cond  = Op.getOperand(0);
10764   SDValue Op1 = Op.getOperand(1);
10765   SDValue Op2 = Op.getOperand(2);
10766   SDLoc DL(Op);
10767   EVT VT = Op1.getValueType();
10768   SDValue CC;
10769
10770   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10771   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10772   // sequence later on.
10773   if (Cond.getOpcode() == ISD::SETCC &&
10774       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10775        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10776       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10777     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10778     int SSECC = translateX86FSETCC(
10779         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10780
10781     if (SSECC != 8) {
10782       if (Subtarget->hasAVX512()) {
10783         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10784                                   DAG.getConstant(SSECC, MVT::i8));
10785         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10786       }
10787       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10788                                 DAG.getConstant(SSECC, MVT::i8));
10789       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10790       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10791       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10792     }
10793   }
10794
10795   if (Cond.getOpcode() == ISD::SETCC) {
10796     SDValue NewCond = LowerSETCC(Cond, DAG);
10797     if (NewCond.getNode())
10798       Cond = NewCond;
10799   }
10800
10801   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10802   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10803   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10804   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10805   if (Cond.getOpcode() == X86ISD::SETCC &&
10806       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10807       isZero(Cond.getOperand(1).getOperand(1))) {
10808     SDValue Cmp = Cond.getOperand(1);
10809
10810     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10811
10812     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10813         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10814       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10815
10816       SDValue CmpOp0 = Cmp.getOperand(0);
10817       // Apply further optimizations for special cases
10818       // (select (x != 0), -1, 0) -> neg & sbb
10819       // (select (x == 0), 0, -1) -> neg & sbb
10820       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10821         if (YC->isNullValue() &&
10822             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10823           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10824           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10825                                     DAG.getConstant(0, CmpOp0.getValueType()),
10826                                     CmpOp0);
10827           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10828                                     DAG.getConstant(X86::COND_B, MVT::i8),
10829                                     SDValue(Neg.getNode(), 1));
10830           return Res;
10831         }
10832
10833       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10834                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10835       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10836
10837       SDValue Res =   // Res = 0 or -1.
10838         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10839                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10840
10841       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10842         Res = DAG.getNOT(DL, Res, Res.getValueType());
10843
10844       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10845       if (!N2C || !N2C->isNullValue())
10846         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10847       return Res;
10848     }
10849   }
10850
10851   // Look past (and (setcc_carry (cmp ...)), 1).
10852   if (Cond.getOpcode() == ISD::AND &&
10853       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10854     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10855     if (C && C->getAPIntValue() == 1)
10856       Cond = Cond.getOperand(0);
10857   }
10858
10859   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10860   // setting operand in place of the X86ISD::SETCC.
10861   unsigned CondOpcode = Cond.getOpcode();
10862   if (CondOpcode == X86ISD::SETCC ||
10863       CondOpcode == X86ISD::SETCC_CARRY) {
10864     CC = Cond.getOperand(0);
10865
10866     SDValue Cmp = Cond.getOperand(1);
10867     unsigned Opc = Cmp.getOpcode();
10868     MVT VT = Op.getSimpleValueType();
10869
10870     bool IllegalFPCMov = false;
10871     if (VT.isFloatingPoint() && !VT.isVector() &&
10872         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10873       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10874
10875     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10876         Opc == X86ISD::BT) { // FIXME
10877       Cond = Cmp;
10878       addTest = false;
10879     }
10880   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10881              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10882              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10883               Cond.getOperand(0).getValueType() != MVT::i8)) {
10884     SDValue LHS = Cond.getOperand(0);
10885     SDValue RHS = Cond.getOperand(1);
10886     unsigned X86Opcode;
10887     unsigned X86Cond;
10888     SDVTList VTs;
10889     switch (CondOpcode) {
10890     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10891     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10892     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10893     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10894     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10895     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10896     default: llvm_unreachable("unexpected overflowing operator");
10897     }
10898     if (CondOpcode == ISD::UMULO)
10899       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10900                           MVT::i32);
10901     else
10902       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10903
10904     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10905
10906     if (CondOpcode == ISD::UMULO)
10907       Cond = X86Op.getValue(2);
10908     else
10909       Cond = X86Op.getValue(1);
10910
10911     CC = DAG.getConstant(X86Cond, MVT::i8);
10912     addTest = false;
10913   }
10914
10915   if (addTest) {
10916     // Look pass the truncate if the high bits are known zero.
10917     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10918         Cond = Cond.getOperand(0);
10919
10920     // We know the result of AND is compared against zero. Try to match
10921     // it to BT.
10922     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10923       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10924       if (NewSetCC.getNode()) {
10925         CC = NewSetCC.getOperand(0);
10926         Cond = NewSetCC.getOperand(1);
10927         addTest = false;
10928       }
10929     }
10930   }
10931
10932   if (addTest) {
10933     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10934     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10935   }
10936
10937   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10938   // a <  b ?  0 : -1 -> RES = setcc_carry
10939   // a >= b ? -1 :  0 -> RES = setcc_carry
10940   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10941   if (Cond.getOpcode() == X86ISD::SUB) {
10942     Cond = ConvertCmpIfNecessary(Cond, DAG);
10943     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10944
10945     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10946         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10947       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10948                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10949       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10950         return DAG.getNOT(DL, Res, Res.getValueType());
10951       return Res;
10952     }
10953   }
10954
10955   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10956   // widen the cmov and push the truncate through. This avoids introducing a new
10957   // branch during isel and doesn't add any extensions.
10958   if (Op.getValueType() == MVT::i8 &&
10959       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10960     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10961     if (T1.getValueType() == T2.getValueType() &&
10962         // Blacklist CopyFromReg to avoid partial register stalls.
10963         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10964       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10965       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10966       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10967     }
10968   }
10969
10970   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10971   // condition is true.
10972   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10973   SDValue Ops[] = { Op2, Op1, CC, Cond };
10974   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10975 }
10976
10977 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10978   MVT VT = Op->getSimpleValueType(0);
10979   SDValue In = Op->getOperand(0);
10980   MVT InVT = In.getSimpleValueType();
10981   SDLoc dl(Op);
10982
10983   unsigned int NumElts = VT.getVectorNumElements();
10984   if (NumElts != 8 && NumElts != 16)
10985     return SDValue();
10986
10987   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10988     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10989
10990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10991   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10992
10993   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10994   Constant *C = ConstantInt::get(*DAG.getContext(),
10995     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10996
10997   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10998   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10999   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11000                           MachinePointerInfo::getConstantPool(),
11001                           false, false, false, Alignment);
11002   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11003   if (VT.is512BitVector())
11004     return Brcst;
11005   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11006 }
11007
11008 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11009                                 SelectionDAG &DAG) {
11010   MVT VT = Op->getSimpleValueType(0);
11011   SDValue In = Op->getOperand(0);
11012   MVT InVT = In.getSimpleValueType();
11013   SDLoc dl(Op);
11014
11015   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11016     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11017
11018   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11019       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11020       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11021     return SDValue();
11022
11023   if (Subtarget->hasInt256())
11024     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11025
11026   // Optimize vectors in AVX mode
11027   // Sign extend  v8i16 to v8i32 and
11028   //              v4i32 to v4i64
11029   //
11030   // Divide input vector into two parts
11031   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11032   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11033   // concat the vectors to original VT
11034
11035   unsigned NumElems = InVT.getVectorNumElements();
11036   SDValue Undef = DAG.getUNDEF(InVT);
11037
11038   SmallVector<int,8> ShufMask1(NumElems, -1);
11039   for (unsigned i = 0; i != NumElems/2; ++i)
11040     ShufMask1[i] = i;
11041
11042   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11043
11044   SmallVector<int,8> ShufMask2(NumElems, -1);
11045   for (unsigned i = 0; i != NumElems/2; ++i)
11046     ShufMask2[i] = i + NumElems/2;
11047
11048   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11049
11050   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11051                                 VT.getVectorNumElements()/2);
11052
11053   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11054   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11055
11056   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11057 }
11058
11059 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11060 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11061 // from the AND / OR.
11062 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11063   Opc = Op.getOpcode();
11064   if (Opc != ISD::OR && Opc != ISD::AND)
11065     return false;
11066   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11067           Op.getOperand(0).hasOneUse() &&
11068           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11069           Op.getOperand(1).hasOneUse());
11070 }
11071
11072 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11073 // 1 and that the SETCC node has a single use.
11074 static bool isXor1OfSetCC(SDValue Op) {
11075   if (Op.getOpcode() != ISD::XOR)
11076     return false;
11077   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11078   if (N1C && N1C->getAPIntValue() == 1) {
11079     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11080       Op.getOperand(0).hasOneUse();
11081   }
11082   return false;
11083 }
11084
11085 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11086   bool addTest = true;
11087   SDValue Chain = Op.getOperand(0);
11088   SDValue Cond  = Op.getOperand(1);
11089   SDValue Dest  = Op.getOperand(2);
11090   SDLoc dl(Op);
11091   SDValue CC;
11092   bool Inverted = false;
11093
11094   if (Cond.getOpcode() == ISD::SETCC) {
11095     // Check for setcc([su]{add,sub,mul}o == 0).
11096     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11097         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11098         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11099         Cond.getOperand(0).getResNo() == 1 &&
11100         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11101          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11102          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11103          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11104          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11105          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11106       Inverted = true;
11107       Cond = Cond.getOperand(0);
11108     } else {
11109       SDValue NewCond = LowerSETCC(Cond, DAG);
11110       if (NewCond.getNode())
11111         Cond = NewCond;
11112     }
11113   }
11114 #if 0
11115   // FIXME: LowerXALUO doesn't handle these!!
11116   else if (Cond.getOpcode() == X86ISD::ADD  ||
11117            Cond.getOpcode() == X86ISD::SUB  ||
11118            Cond.getOpcode() == X86ISD::SMUL ||
11119            Cond.getOpcode() == X86ISD::UMUL)
11120     Cond = LowerXALUO(Cond, DAG);
11121 #endif
11122
11123   // Look pass (and (setcc_carry (cmp ...)), 1).
11124   if (Cond.getOpcode() == ISD::AND &&
11125       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11126     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11127     if (C && C->getAPIntValue() == 1)
11128       Cond = Cond.getOperand(0);
11129   }
11130
11131   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11132   // setting operand in place of the X86ISD::SETCC.
11133   unsigned CondOpcode = Cond.getOpcode();
11134   if (CondOpcode == X86ISD::SETCC ||
11135       CondOpcode == X86ISD::SETCC_CARRY) {
11136     CC = Cond.getOperand(0);
11137
11138     SDValue Cmp = Cond.getOperand(1);
11139     unsigned Opc = Cmp.getOpcode();
11140     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11141     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11142       Cond = Cmp;
11143       addTest = false;
11144     } else {
11145       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11146       default: break;
11147       case X86::COND_O:
11148       case X86::COND_B:
11149         // These can only come from an arithmetic instruction with overflow,
11150         // e.g. SADDO, UADDO.
11151         Cond = Cond.getNode()->getOperand(1);
11152         addTest = false;
11153         break;
11154       }
11155     }
11156   }
11157   CondOpcode = Cond.getOpcode();
11158   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11159       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11160       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11161        Cond.getOperand(0).getValueType() != MVT::i8)) {
11162     SDValue LHS = Cond.getOperand(0);
11163     SDValue RHS = Cond.getOperand(1);
11164     unsigned X86Opcode;
11165     unsigned X86Cond;
11166     SDVTList VTs;
11167     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11168     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11169     // X86ISD::INC).
11170     switch (CondOpcode) {
11171     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11172     case ISD::SADDO:
11173       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11174         if (C->isOne()) {
11175           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11176           break;
11177         }
11178       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11179     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11180     case ISD::SSUBO:
11181       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11182         if (C->isOne()) {
11183           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11184           break;
11185         }
11186       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11187     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11188     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11189     default: llvm_unreachable("unexpected overflowing operator");
11190     }
11191     if (Inverted)
11192       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11193     if (CondOpcode == ISD::UMULO)
11194       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11195                           MVT::i32);
11196     else
11197       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11198
11199     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11200
11201     if (CondOpcode == ISD::UMULO)
11202       Cond = X86Op.getValue(2);
11203     else
11204       Cond = X86Op.getValue(1);
11205
11206     CC = DAG.getConstant(X86Cond, MVT::i8);
11207     addTest = false;
11208   } else {
11209     unsigned CondOpc;
11210     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11211       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11212       if (CondOpc == ISD::OR) {
11213         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11214         // two branches instead of an explicit OR instruction with a
11215         // separate test.
11216         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11217             isX86LogicalCmp(Cmp)) {
11218           CC = Cond.getOperand(0).getOperand(0);
11219           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11220                               Chain, Dest, CC, Cmp);
11221           CC = Cond.getOperand(1).getOperand(0);
11222           Cond = Cmp;
11223           addTest = false;
11224         }
11225       } else { // ISD::AND
11226         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11227         // two branches instead of an explicit AND instruction with a
11228         // separate test. However, we only do this if this block doesn't
11229         // have a fall-through edge, because this requires an explicit
11230         // jmp when the condition is false.
11231         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11232             isX86LogicalCmp(Cmp) &&
11233             Op.getNode()->hasOneUse()) {
11234           X86::CondCode CCode =
11235             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11236           CCode = X86::GetOppositeBranchCondition(CCode);
11237           CC = DAG.getConstant(CCode, MVT::i8);
11238           SDNode *User = *Op.getNode()->use_begin();
11239           // Look for an unconditional branch following this conditional branch.
11240           // We need this because we need to reverse the successors in order
11241           // to implement FCMP_OEQ.
11242           if (User->getOpcode() == ISD::BR) {
11243             SDValue FalseBB = User->getOperand(1);
11244             SDNode *NewBR =
11245               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11246             assert(NewBR == User);
11247             (void)NewBR;
11248             Dest = FalseBB;
11249
11250             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11251                                 Chain, Dest, CC, Cmp);
11252             X86::CondCode CCode =
11253               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11254             CCode = X86::GetOppositeBranchCondition(CCode);
11255             CC = DAG.getConstant(CCode, MVT::i8);
11256             Cond = Cmp;
11257             addTest = false;
11258           }
11259         }
11260       }
11261     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11262       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11263       // It should be transformed during dag combiner except when the condition
11264       // is set by a arithmetics with overflow node.
11265       X86::CondCode CCode =
11266         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11267       CCode = X86::GetOppositeBranchCondition(CCode);
11268       CC = DAG.getConstant(CCode, MVT::i8);
11269       Cond = Cond.getOperand(0).getOperand(1);
11270       addTest = false;
11271     } else if (Cond.getOpcode() == ISD::SETCC &&
11272                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11273       // For FCMP_OEQ, we can emit
11274       // two branches instead of an explicit AND instruction with a
11275       // separate test. However, we only do this if this block doesn't
11276       // have a fall-through edge, because this requires an explicit
11277       // jmp when the condition is false.
11278       if (Op.getNode()->hasOneUse()) {
11279         SDNode *User = *Op.getNode()->use_begin();
11280         // Look for an unconditional branch following this conditional branch.
11281         // We need this because we need to reverse the successors in order
11282         // to implement FCMP_OEQ.
11283         if (User->getOpcode() == ISD::BR) {
11284           SDValue FalseBB = User->getOperand(1);
11285           SDNode *NewBR =
11286             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11287           assert(NewBR == User);
11288           (void)NewBR;
11289           Dest = FalseBB;
11290
11291           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11292                                     Cond.getOperand(0), Cond.getOperand(1));
11293           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11294           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11295           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11296                               Chain, Dest, CC, Cmp);
11297           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11298           Cond = Cmp;
11299           addTest = false;
11300         }
11301       }
11302     } else if (Cond.getOpcode() == ISD::SETCC &&
11303                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11304       // For FCMP_UNE, we can emit
11305       // two branches instead of an explicit AND instruction with a
11306       // separate test. However, we only do this if this block doesn't
11307       // have a fall-through edge, because this requires an explicit
11308       // jmp when the condition is false.
11309       if (Op.getNode()->hasOneUse()) {
11310         SDNode *User = *Op.getNode()->use_begin();
11311         // Look for an unconditional branch following this conditional branch.
11312         // We need this because we need to reverse the successors in order
11313         // to implement FCMP_UNE.
11314         if (User->getOpcode() == ISD::BR) {
11315           SDValue FalseBB = User->getOperand(1);
11316           SDNode *NewBR =
11317             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11318           assert(NewBR == User);
11319           (void)NewBR;
11320
11321           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11322                                     Cond.getOperand(0), Cond.getOperand(1));
11323           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11324           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11325           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11326                               Chain, Dest, CC, Cmp);
11327           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11328           Cond = Cmp;
11329           addTest = false;
11330           Dest = FalseBB;
11331         }
11332       }
11333     }
11334   }
11335
11336   if (addTest) {
11337     // Look pass the truncate if the high bits are known zero.
11338     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11339         Cond = Cond.getOperand(0);
11340
11341     // We know the result of AND is compared against zero. Try to match
11342     // it to BT.
11343     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11344       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11345       if (NewSetCC.getNode()) {
11346         CC = NewSetCC.getOperand(0);
11347         Cond = NewSetCC.getOperand(1);
11348         addTest = false;
11349       }
11350     }
11351   }
11352
11353   if (addTest) {
11354     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11355     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11356   }
11357   Cond = ConvertCmpIfNecessary(Cond, DAG);
11358   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11359                      Chain, Dest, CC, Cond);
11360 }
11361
11362 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11363 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11364 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11365 // that the guard pages used by the OS virtual memory manager are allocated in
11366 // correct sequence.
11367 SDValue
11368 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11369                                            SelectionDAG &DAG) const {
11370   MachineFunction &MF = DAG.getMachineFunction();
11371   bool SplitStack = MF.shouldSplitStack();
11372   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11373                SplitStack;
11374   SDLoc dl(Op);
11375
11376   if (!Lower) {
11377     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11378     SDNode* Node = Op.getNode();
11379
11380     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11381     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11382         " not tell us which reg is the stack pointer!");
11383     EVT VT = Node->getValueType(0);
11384     SDValue Tmp1 = SDValue(Node, 0);
11385     SDValue Tmp2 = SDValue(Node, 1);
11386     SDValue Tmp3 = Node->getOperand(2);
11387     SDValue Chain = Tmp1.getOperand(0);
11388
11389     // Chain the dynamic stack allocation so that it doesn't modify the stack
11390     // pointer when other instructions are using the stack.
11391     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11392         SDLoc(Node));
11393
11394     SDValue Size = Tmp2.getOperand(1);
11395     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11396     Chain = SP.getValue(1);
11397     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11398     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11399     unsigned StackAlign = TFI.getStackAlignment();
11400     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11401     if (Align > StackAlign)
11402       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11403           DAG.getConstant(-(uint64_t)Align, VT));
11404     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11405
11406     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11407         DAG.getIntPtrConstant(0, true), SDValue(),
11408         SDLoc(Node));
11409
11410     SDValue Ops[2] = { Tmp1, Tmp2 };
11411     return DAG.getMergeValues(Ops, dl);
11412   }
11413
11414   // Get the inputs.
11415   SDValue Chain = Op.getOperand(0);
11416   SDValue Size  = Op.getOperand(1);
11417   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11418   EVT VT = Op.getNode()->getValueType(0);
11419
11420   bool Is64Bit = Subtarget->is64Bit();
11421   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11422
11423   if (SplitStack) {
11424     MachineRegisterInfo &MRI = MF.getRegInfo();
11425
11426     if (Is64Bit) {
11427       // The 64 bit implementation of segmented stacks needs to clobber both r10
11428       // r11. This makes it impossible to use it along with nested parameters.
11429       const Function *F = MF.getFunction();
11430
11431       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11432            I != E; ++I)
11433         if (I->hasNestAttr())
11434           report_fatal_error("Cannot use segmented stacks with functions that "
11435                              "have nested arguments.");
11436     }
11437
11438     const TargetRegisterClass *AddrRegClass =
11439       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11440     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11441     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11442     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11443                                 DAG.getRegister(Vreg, SPTy));
11444     SDValue Ops1[2] = { Value, Chain };
11445     return DAG.getMergeValues(Ops1, dl);
11446   } else {
11447     SDValue Flag;
11448     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11449
11450     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11451     Flag = Chain.getValue(1);
11452     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11453
11454     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11455
11456     const X86RegisterInfo *RegInfo =
11457       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11458     unsigned SPReg = RegInfo->getStackRegister();
11459     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11460     Chain = SP.getValue(1);
11461
11462     if (Align) {
11463       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11464                        DAG.getConstant(-(uint64_t)Align, VT));
11465       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11466     }
11467
11468     SDValue Ops1[2] = { SP, Chain };
11469     return DAG.getMergeValues(Ops1, dl);
11470   }
11471 }
11472
11473 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11474   MachineFunction &MF = DAG.getMachineFunction();
11475   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11476
11477   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11478   SDLoc DL(Op);
11479
11480   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11481     // vastart just stores the address of the VarArgsFrameIndex slot into the
11482     // memory location argument.
11483     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11484                                    getPointerTy());
11485     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11486                         MachinePointerInfo(SV), false, false, 0);
11487   }
11488
11489   // __va_list_tag:
11490   //   gp_offset         (0 - 6 * 8)
11491   //   fp_offset         (48 - 48 + 8 * 16)
11492   //   overflow_arg_area (point to parameters coming in memory).
11493   //   reg_save_area
11494   SmallVector<SDValue, 8> MemOps;
11495   SDValue FIN = Op.getOperand(1);
11496   // Store gp_offset
11497   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11498                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11499                                                MVT::i32),
11500                                FIN, MachinePointerInfo(SV), false, false, 0);
11501   MemOps.push_back(Store);
11502
11503   // Store fp_offset
11504   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11505                     FIN, DAG.getIntPtrConstant(4));
11506   Store = DAG.getStore(Op.getOperand(0), DL,
11507                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11508                                        MVT::i32),
11509                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11510   MemOps.push_back(Store);
11511
11512   // Store ptr to overflow_arg_area
11513   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11514                     FIN, DAG.getIntPtrConstant(4));
11515   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11516                                     getPointerTy());
11517   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11518                        MachinePointerInfo(SV, 8),
11519                        false, false, 0);
11520   MemOps.push_back(Store);
11521
11522   // Store ptr to reg_save_area.
11523   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11524                     FIN, DAG.getIntPtrConstant(8));
11525   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11526                                     getPointerTy());
11527   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11528                        MachinePointerInfo(SV, 16), false, false, 0);
11529   MemOps.push_back(Store);
11530   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11531 }
11532
11533 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11534   assert(Subtarget->is64Bit() &&
11535          "LowerVAARG only handles 64-bit va_arg!");
11536   assert((Subtarget->isTargetLinux() ||
11537           Subtarget->isTargetDarwin()) &&
11538           "Unhandled target in LowerVAARG");
11539   assert(Op.getNode()->getNumOperands() == 4);
11540   SDValue Chain = Op.getOperand(0);
11541   SDValue SrcPtr = Op.getOperand(1);
11542   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11543   unsigned Align = Op.getConstantOperandVal(3);
11544   SDLoc dl(Op);
11545
11546   EVT ArgVT = Op.getNode()->getValueType(0);
11547   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11548   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11549   uint8_t ArgMode;
11550
11551   // Decide which area this value should be read from.
11552   // TODO: Implement the AMD64 ABI in its entirety. This simple
11553   // selection mechanism works only for the basic types.
11554   if (ArgVT == MVT::f80) {
11555     llvm_unreachable("va_arg for f80 not yet implemented");
11556   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11557     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11558   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11559     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11560   } else {
11561     llvm_unreachable("Unhandled argument type in LowerVAARG");
11562   }
11563
11564   if (ArgMode == 2) {
11565     // Sanity Check: Make sure using fp_offset makes sense.
11566     assert(!getTargetMachine().Options.UseSoftFloat &&
11567            !(DAG.getMachineFunction()
11568                 .getFunction()->getAttributes()
11569                 .hasAttribute(AttributeSet::FunctionIndex,
11570                               Attribute::NoImplicitFloat)) &&
11571            Subtarget->hasSSE1());
11572   }
11573
11574   // Insert VAARG_64 node into the DAG
11575   // VAARG_64 returns two values: Variable Argument Address, Chain
11576   SmallVector<SDValue, 11> InstOps;
11577   InstOps.push_back(Chain);
11578   InstOps.push_back(SrcPtr);
11579   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11580   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11581   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11582   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11583   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11584                                           VTs, InstOps, MVT::i64,
11585                                           MachinePointerInfo(SV),
11586                                           /*Align=*/0,
11587                                           /*Volatile=*/false,
11588                                           /*ReadMem=*/true,
11589                                           /*WriteMem=*/true);
11590   Chain = VAARG.getValue(1);
11591
11592   // Load the next argument and return it
11593   return DAG.getLoad(ArgVT, dl,
11594                      Chain,
11595                      VAARG,
11596                      MachinePointerInfo(),
11597                      false, false, false, 0);
11598 }
11599
11600 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11601                            SelectionDAG &DAG) {
11602   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11603   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11604   SDValue Chain = Op.getOperand(0);
11605   SDValue DstPtr = Op.getOperand(1);
11606   SDValue SrcPtr = Op.getOperand(2);
11607   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11608   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11609   SDLoc DL(Op);
11610
11611   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11612                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11613                        false,
11614                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11615 }
11616
11617 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11618 // amount is a constant. Takes immediate version of shift as input.
11619 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11620                                           SDValue SrcOp, uint64_t ShiftAmt,
11621                                           SelectionDAG &DAG) {
11622   MVT ElementType = VT.getVectorElementType();
11623
11624   // Fold this packed shift into its first operand if ShiftAmt is 0.
11625   if (ShiftAmt == 0)
11626     return SrcOp;
11627
11628   // Check for ShiftAmt >= element width
11629   if (ShiftAmt >= ElementType.getSizeInBits()) {
11630     if (Opc == X86ISD::VSRAI)
11631       ShiftAmt = ElementType.getSizeInBits() - 1;
11632     else
11633       return DAG.getConstant(0, VT);
11634   }
11635
11636   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11637          && "Unknown target vector shift-by-constant node");
11638
11639   // Fold this packed vector shift into a build vector if SrcOp is a
11640   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11641   if (VT == SrcOp.getSimpleValueType() &&
11642       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11643     SmallVector<SDValue, 8> Elts;
11644     unsigned NumElts = SrcOp->getNumOperands();
11645     ConstantSDNode *ND;
11646
11647     switch(Opc) {
11648     default: llvm_unreachable(nullptr);
11649     case X86ISD::VSHLI:
11650       for (unsigned i=0; i!=NumElts; ++i) {
11651         SDValue CurrentOp = SrcOp->getOperand(i);
11652         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11653           Elts.push_back(CurrentOp);
11654           continue;
11655         }
11656         ND = cast<ConstantSDNode>(CurrentOp);
11657         const APInt &C = ND->getAPIntValue();
11658         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11659       }
11660       break;
11661     case X86ISD::VSRLI:
11662       for (unsigned i=0; i!=NumElts; ++i) {
11663         SDValue CurrentOp = SrcOp->getOperand(i);
11664         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11665           Elts.push_back(CurrentOp);
11666           continue;
11667         }
11668         ND = cast<ConstantSDNode>(CurrentOp);
11669         const APInt &C = ND->getAPIntValue();
11670         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11671       }
11672       break;
11673     case X86ISD::VSRAI:
11674       for (unsigned i=0; i!=NumElts; ++i) {
11675         SDValue CurrentOp = SrcOp->getOperand(i);
11676         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11677           Elts.push_back(CurrentOp);
11678           continue;
11679         }
11680         ND = cast<ConstantSDNode>(CurrentOp);
11681         const APInt &C = ND->getAPIntValue();
11682         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11683       }
11684       break;
11685     }
11686
11687     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11688   }
11689
11690   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11691 }
11692
11693 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11694 // may or may not be a constant. Takes immediate version of shift as input.
11695 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11696                                    SDValue SrcOp, SDValue ShAmt,
11697                                    SelectionDAG &DAG) {
11698   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11699
11700   // Catch shift-by-constant.
11701   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11702     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11703                                       CShAmt->getZExtValue(), DAG);
11704
11705   // Change opcode to non-immediate version
11706   switch (Opc) {
11707     default: llvm_unreachable("Unknown target vector shift node");
11708     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11709     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11710     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11711   }
11712
11713   // Need to build a vector containing shift amount
11714   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11715   SDValue ShOps[4];
11716   ShOps[0] = ShAmt;
11717   ShOps[1] = DAG.getConstant(0, MVT::i32);
11718   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11719   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11720
11721   // The return type has to be a 128-bit type with the same element
11722   // type as the input type.
11723   MVT EltVT = VT.getVectorElementType();
11724   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11725
11726   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11727   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11728 }
11729
11730 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11731   SDLoc dl(Op);
11732   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11733   switch (IntNo) {
11734   default: return SDValue();    // Don't custom lower most intrinsics.
11735   // Comparison intrinsics.
11736   case Intrinsic::x86_sse_comieq_ss:
11737   case Intrinsic::x86_sse_comilt_ss:
11738   case Intrinsic::x86_sse_comile_ss:
11739   case Intrinsic::x86_sse_comigt_ss:
11740   case Intrinsic::x86_sse_comige_ss:
11741   case Intrinsic::x86_sse_comineq_ss:
11742   case Intrinsic::x86_sse_ucomieq_ss:
11743   case Intrinsic::x86_sse_ucomilt_ss:
11744   case Intrinsic::x86_sse_ucomile_ss:
11745   case Intrinsic::x86_sse_ucomigt_ss:
11746   case Intrinsic::x86_sse_ucomige_ss:
11747   case Intrinsic::x86_sse_ucomineq_ss:
11748   case Intrinsic::x86_sse2_comieq_sd:
11749   case Intrinsic::x86_sse2_comilt_sd:
11750   case Intrinsic::x86_sse2_comile_sd:
11751   case Intrinsic::x86_sse2_comigt_sd:
11752   case Intrinsic::x86_sse2_comige_sd:
11753   case Intrinsic::x86_sse2_comineq_sd:
11754   case Intrinsic::x86_sse2_ucomieq_sd:
11755   case Intrinsic::x86_sse2_ucomilt_sd:
11756   case Intrinsic::x86_sse2_ucomile_sd:
11757   case Intrinsic::x86_sse2_ucomigt_sd:
11758   case Intrinsic::x86_sse2_ucomige_sd:
11759   case Intrinsic::x86_sse2_ucomineq_sd: {
11760     unsigned Opc;
11761     ISD::CondCode CC;
11762     switch (IntNo) {
11763     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11764     case Intrinsic::x86_sse_comieq_ss:
11765     case Intrinsic::x86_sse2_comieq_sd:
11766       Opc = X86ISD::COMI;
11767       CC = ISD::SETEQ;
11768       break;
11769     case Intrinsic::x86_sse_comilt_ss:
11770     case Intrinsic::x86_sse2_comilt_sd:
11771       Opc = X86ISD::COMI;
11772       CC = ISD::SETLT;
11773       break;
11774     case Intrinsic::x86_sse_comile_ss:
11775     case Intrinsic::x86_sse2_comile_sd:
11776       Opc = X86ISD::COMI;
11777       CC = ISD::SETLE;
11778       break;
11779     case Intrinsic::x86_sse_comigt_ss:
11780     case Intrinsic::x86_sse2_comigt_sd:
11781       Opc = X86ISD::COMI;
11782       CC = ISD::SETGT;
11783       break;
11784     case Intrinsic::x86_sse_comige_ss:
11785     case Intrinsic::x86_sse2_comige_sd:
11786       Opc = X86ISD::COMI;
11787       CC = ISD::SETGE;
11788       break;
11789     case Intrinsic::x86_sse_comineq_ss:
11790     case Intrinsic::x86_sse2_comineq_sd:
11791       Opc = X86ISD::COMI;
11792       CC = ISD::SETNE;
11793       break;
11794     case Intrinsic::x86_sse_ucomieq_ss:
11795     case Intrinsic::x86_sse2_ucomieq_sd:
11796       Opc = X86ISD::UCOMI;
11797       CC = ISD::SETEQ;
11798       break;
11799     case Intrinsic::x86_sse_ucomilt_ss:
11800     case Intrinsic::x86_sse2_ucomilt_sd:
11801       Opc = X86ISD::UCOMI;
11802       CC = ISD::SETLT;
11803       break;
11804     case Intrinsic::x86_sse_ucomile_ss:
11805     case Intrinsic::x86_sse2_ucomile_sd:
11806       Opc = X86ISD::UCOMI;
11807       CC = ISD::SETLE;
11808       break;
11809     case Intrinsic::x86_sse_ucomigt_ss:
11810     case Intrinsic::x86_sse2_ucomigt_sd:
11811       Opc = X86ISD::UCOMI;
11812       CC = ISD::SETGT;
11813       break;
11814     case Intrinsic::x86_sse_ucomige_ss:
11815     case Intrinsic::x86_sse2_ucomige_sd:
11816       Opc = X86ISD::UCOMI;
11817       CC = ISD::SETGE;
11818       break;
11819     case Intrinsic::x86_sse_ucomineq_ss:
11820     case Intrinsic::x86_sse2_ucomineq_sd:
11821       Opc = X86ISD::UCOMI;
11822       CC = ISD::SETNE;
11823       break;
11824     }
11825
11826     SDValue LHS = Op.getOperand(1);
11827     SDValue RHS = Op.getOperand(2);
11828     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11829     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11830     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11831     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11832                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11833     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11834   }
11835
11836   // Arithmetic intrinsics.
11837   case Intrinsic::x86_sse2_pmulu_dq:
11838   case Intrinsic::x86_avx2_pmulu_dq:
11839     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11840                        Op.getOperand(1), Op.getOperand(2));
11841
11842   case Intrinsic::x86_sse41_pmuldq:
11843   case Intrinsic::x86_avx2_pmul_dq:
11844     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11845                        Op.getOperand(1), Op.getOperand(2));
11846
11847   case Intrinsic::x86_sse2_pmulhu_w:
11848   case Intrinsic::x86_avx2_pmulhu_w:
11849     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11850                        Op.getOperand(1), Op.getOperand(2));
11851
11852   case Intrinsic::x86_sse2_pmulh_w:
11853   case Intrinsic::x86_avx2_pmulh_w:
11854     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11855                        Op.getOperand(1), Op.getOperand(2));
11856
11857   // SSE2/AVX2 sub with unsigned saturation intrinsics
11858   case Intrinsic::x86_sse2_psubus_b:
11859   case Intrinsic::x86_sse2_psubus_w:
11860   case Intrinsic::x86_avx2_psubus_b:
11861   case Intrinsic::x86_avx2_psubus_w:
11862     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11863                        Op.getOperand(1), Op.getOperand(2));
11864
11865   // SSE3/AVX horizontal add/sub intrinsics
11866   case Intrinsic::x86_sse3_hadd_ps:
11867   case Intrinsic::x86_sse3_hadd_pd:
11868   case Intrinsic::x86_avx_hadd_ps_256:
11869   case Intrinsic::x86_avx_hadd_pd_256:
11870   case Intrinsic::x86_sse3_hsub_ps:
11871   case Intrinsic::x86_sse3_hsub_pd:
11872   case Intrinsic::x86_avx_hsub_ps_256:
11873   case Intrinsic::x86_avx_hsub_pd_256:
11874   case Intrinsic::x86_ssse3_phadd_w_128:
11875   case Intrinsic::x86_ssse3_phadd_d_128:
11876   case Intrinsic::x86_avx2_phadd_w:
11877   case Intrinsic::x86_avx2_phadd_d:
11878   case Intrinsic::x86_ssse3_phsub_w_128:
11879   case Intrinsic::x86_ssse3_phsub_d_128:
11880   case Intrinsic::x86_avx2_phsub_w:
11881   case Intrinsic::x86_avx2_phsub_d: {
11882     unsigned Opcode;
11883     switch (IntNo) {
11884     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11885     case Intrinsic::x86_sse3_hadd_ps:
11886     case Intrinsic::x86_sse3_hadd_pd:
11887     case Intrinsic::x86_avx_hadd_ps_256:
11888     case Intrinsic::x86_avx_hadd_pd_256:
11889       Opcode = X86ISD::FHADD;
11890       break;
11891     case Intrinsic::x86_sse3_hsub_ps:
11892     case Intrinsic::x86_sse3_hsub_pd:
11893     case Intrinsic::x86_avx_hsub_ps_256:
11894     case Intrinsic::x86_avx_hsub_pd_256:
11895       Opcode = X86ISD::FHSUB;
11896       break;
11897     case Intrinsic::x86_ssse3_phadd_w_128:
11898     case Intrinsic::x86_ssse3_phadd_d_128:
11899     case Intrinsic::x86_avx2_phadd_w:
11900     case Intrinsic::x86_avx2_phadd_d:
11901       Opcode = X86ISD::HADD;
11902       break;
11903     case Intrinsic::x86_ssse3_phsub_w_128:
11904     case Intrinsic::x86_ssse3_phsub_d_128:
11905     case Intrinsic::x86_avx2_phsub_w:
11906     case Intrinsic::x86_avx2_phsub_d:
11907       Opcode = X86ISD::HSUB;
11908       break;
11909     }
11910     return DAG.getNode(Opcode, dl, Op.getValueType(),
11911                        Op.getOperand(1), Op.getOperand(2));
11912   }
11913
11914   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11915   case Intrinsic::x86_sse2_pmaxu_b:
11916   case Intrinsic::x86_sse41_pmaxuw:
11917   case Intrinsic::x86_sse41_pmaxud:
11918   case Intrinsic::x86_avx2_pmaxu_b:
11919   case Intrinsic::x86_avx2_pmaxu_w:
11920   case Intrinsic::x86_avx2_pmaxu_d:
11921   case Intrinsic::x86_sse2_pminu_b:
11922   case Intrinsic::x86_sse41_pminuw:
11923   case Intrinsic::x86_sse41_pminud:
11924   case Intrinsic::x86_avx2_pminu_b:
11925   case Intrinsic::x86_avx2_pminu_w:
11926   case Intrinsic::x86_avx2_pminu_d:
11927   case Intrinsic::x86_sse41_pmaxsb:
11928   case Intrinsic::x86_sse2_pmaxs_w:
11929   case Intrinsic::x86_sse41_pmaxsd:
11930   case Intrinsic::x86_avx2_pmaxs_b:
11931   case Intrinsic::x86_avx2_pmaxs_w:
11932   case Intrinsic::x86_avx2_pmaxs_d:
11933   case Intrinsic::x86_sse41_pminsb:
11934   case Intrinsic::x86_sse2_pmins_w:
11935   case Intrinsic::x86_sse41_pminsd:
11936   case Intrinsic::x86_avx2_pmins_b:
11937   case Intrinsic::x86_avx2_pmins_w:
11938   case Intrinsic::x86_avx2_pmins_d: {
11939     unsigned Opcode;
11940     switch (IntNo) {
11941     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11942     case Intrinsic::x86_sse2_pmaxu_b:
11943     case Intrinsic::x86_sse41_pmaxuw:
11944     case Intrinsic::x86_sse41_pmaxud:
11945     case Intrinsic::x86_avx2_pmaxu_b:
11946     case Intrinsic::x86_avx2_pmaxu_w:
11947     case Intrinsic::x86_avx2_pmaxu_d:
11948       Opcode = X86ISD::UMAX;
11949       break;
11950     case Intrinsic::x86_sse2_pminu_b:
11951     case Intrinsic::x86_sse41_pminuw:
11952     case Intrinsic::x86_sse41_pminud:
11953     case Intrinsic::x86_avx2_pminu_b:
11954     case Intrinsic::x86_avx2_pminu_w:
11955     case Intrinsic::x86_avx2_pminu_d:
11956       Opcode = X86ISD::UMIN;
11957       break;
11958     case Intrinsic::x86_sse41_pmaxsb:
11959     case Intrinsic::x86_sse2_pmaxs_w:
11960     case Intrinsic::x86_sse41_pmaxsd:
11961     case Intrinsic::x86_avx2_pmaxs_b:
11962     case Intrinsic::x86_avx2_pmaxs_w:
11963     case Intrinsic::x86_avx2_pmaxs_d:
11964       Opcode = X86ISD::SMAX;
11965       break;
11966     case Intrinsic::x86_sse41_pminsb:
11967     case Intrinsic::x86_sse2_pmins_w:
11968     case Intrinsic::x86_sse41_pminsd:
11969     case Intrinsic::x86_avx2_pmins_b:
11970     case Intrinsic::x86_avx2_pmins_w:
11971     case Intrinsic::x86_avx2_pmins_d:
11972       Opcode = X86ISD::SMIN;
11973       break;
11974     }
11975     return DAG.getNode(Opcode, dl, Op.getValueType(),
11976                        Op.getOperand(1), Op.getOperand(2));
11977   }
11978
11979   // SSE/SSE2/AVX floating point max/min intrinsics.
11980   case Intrinsic::x86_sse_max_ps:
11981   case Intrinsic::x86_sse2_max_pd:
11982   case Intrinsic::x86_avx_max_ps_256:
11983   case Intrinsic::x86_avx_max_pd_256:
11984   case Intrinsic::x86_sse_min_ps:
11985   case Intrinsic::x86_sse2_min_pd:
11986   case Intrinsic::x86_avx_min_ps_256:
11987   case Intrinsic::x86_avx_min_pd_256: {
11988     unsigned Opcode;
11989     switch (IntNo) {
11990     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11991     case Intrinsic::x86_sse_max_ps:
11992     case Intrinsic::x86_sse2_max_pd:
11993     case Intrinsic::x86_avx_max_ps_256:
11994     case Intrinsic::x86_avx_max_pd_256:
11995       Opcode = X86ISD::FMAX;
11996       break;
11997     case Intrinsic::x86_sse_min_ps:
11998     case Intrinsic::x86_sse2_min_pd:
11999     case Intrinsic::x86_avx_min_ps_256:
12000     case Intrinsic::x86_avx_min_pd_256:
12001       Opcode = X86ISD::FMIN;
12002       break;
12003     }
12004     return DAG.getNode(Opcode, dl, Op.getValueType(),
12005                        Op.getOperand(1), Op.getOperand(2));
12006   }
12007
12008   // AVX2 variable shift intrinsics
12009   case Intrinsic::x86_avx2_psllv_d:
12010   case Intrinsic::x86_avx2_psllv_q:
12011   case Intrinsic::x86_avx2_psllv_d_256:
12012   case Intrinsic::x86_avx2_psllv_q_256:
12013   case Intrinsic::x86_avx2_psrlv_d:
12014   case Intrinsic::x86_avx2_psrlv_q:
12015   case Intrinsic::x86_avx2_psrlv_d_256:
12016   case Intrinsic::x86_avx2_psrlv_q_256:
12017   case Intrinsic::x86_avx2_psrav_d:
12018   case Intrinsic::x86_avx2_psrav_d_256: {
12019     unsigned Opcode;
12020     switch (IntNo) {
12021     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12022     case Intrinsic::x86_avx2_psllv_d:
12023     case Intrinsic::x86_avx2_psllv_q:
12024     case Intrinsic::x86_avx2_psllv_d_256:
12025     case Intrinsic::x86_avx2_psllv_q_256:
12026       Opcode = ISD::SHL;
12027       break;
12028     case Intrinsic::x86_avx2_psrlv_d:
12029     case Intrinsic::x86_avx2_psrlv_q:
12030     case Intrinsic::x86_avx2_psrlv_d_256:
12031     case Intrinsic::x86_avx2_psrlv_q_256:
12032       Opcode = ISD::SRL;
12033       break;
12034     case Intrinsic::x86_avx2_psrav_d:
12035     case Intrinsic::x86_avx2_psrav_d_256:
12036       Opcode = ISD::SRA;
12037       break;
12038     }
12039     return DAG.getNode(Opcode, dl, Op.getValueType(),
12040                        Op.getOperand(1), Op.getOperand(2));
12041   }
12042
12043   case Intrinsic::x86_ssse3_pshuf_b_128:
12044   case Intrinsic::x86_avx2_pshuf_b:
12045     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12046                        Op.getOperand(1), Op.getOperand(2));
12047
12048   case Intrinsic::x86_ssse3_psign_b_128:
12049   case Intrinsic::x86_ssse3_psign_w_128:
12050   case Intrinsic::x86_ssse3_psign_d_128:
12051   case Intrinsic::x86_avx2_psign_b:
12052   case Intrinsic::x86_avx2_psign_w:
12053   case Intrinsic::x86_avx2_psign_d:
12054     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12055                        Op.getOperand(1), Op.getOperand(2));
12056
12057   case Intrinsic::x86_sse41_insertps:
12058     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12059                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12060
12061   case Intrinsic::x86_avx_vperm2f128_ps_256:
12062   case Intrinsic::x86_avx_vperm2f128_pd_256:
12063   case Intrinsic::x86_avx_vperm2f128_si_256:
12064   case Intrinsic::x86_avx2_vperm2i128:
12065     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12066                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12067
12068   case Intrinsic::x86_avx2_permd:
12069   case Intrinsic::x86_avx2_permps:
12070     // Operands intentionally swapped. Mask is last operand to intrinsic,
12071     // but second operand for node/instruction.
12072     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12073                        Op.getOperand(2), Op.getOperand(1));
12074
12075   case Intrinsic::x86_sse_sqrt_ps:
12076   case Intrinsic::x86_sse2_sqrt_pd:
12077   case Intrinsic::x86_avx_sqrt_ps_256:
12078   case Intrinsic::x86_avx_sqrt_pd_256:
12079     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12080
12081   // ptest and testp intrinsics. The intrinsic these come from are designed to
12082   // return an integer value, not just an instruction so lower it to the ptest
12083   // or testp pattern and a setcc for the result.
12084   case Intrinsic::x86_sse41_ptestz:
12085   case Intrinsic::x86_sse41_ptestc:
12086   case Intrinsic::x86_sse41_ptestnzc:
12087   case Intrinsic::x86_avx_ptestz_256:
12088   case Intrinsic::x86_avx_ptestc_256:
12089   case Intrinsic::x86_avx_ptestnzc_256:
12090   case Intrinsic::x86_avx_vtestz_ps:
12091   case Intrinsic::x86_avx_vtestc_ps:
12092   case Intrinsic::x86_avx_vtestnzc_ps:
12093   case Intrinsic::x86_avx_vtestz_pd:
12094   case Intrinsic::x86_avx_vtestc_pd:
12095   case Intrinsic::x86_avx_vtestnzc_pd:
12096   case Intrinsic::x86_avx_vtestz_ps_256:
12097   case Intrinsic::x86_avx_vtestc_ps_256:
12098   case Intrinsic::x86_avx_vtestnzc_ps_256:
12099   case Intrinsic::x86_avx_vtestz_pd_256:
12100   case Intrinsic::x86_avx_vtestc_pd_256:
12101   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12102     bool IsTestPacked = false;
12103     unsigned X86CC;
12104     switch (IntNo) {
12105     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12106     case Intrinsic::x86_avx_vtestz_ps:
12107     case Intrinsic::x86_avx_vtestz_pd:
12108     case Intrinsic::x86_avx_vtestz_ps_256:
12109     case Intrinsic::x86_avx_vtestz_pd_256:
12110       IsTestPacked = true; // Fallthrough
12111     case Intrinsic::x86_sse41_ptestz:
12112     case Intrinsic::x86_avx_ptestz_256:
12113       // ZF = 1
12114       X86CC = X86::COND_E;
12115       break;
12116     case Intrinsic::x86_avx_vtestc_ps:
12117     case Intrinsic::x86_avx_vtestc_pd:
12118     case Intrinsic::x86_avx_vtestc_ps_256:
12119     case Intrinsic::x86_avx_vtestc_pd_256:
12120       IsTestPacked = true; // Fallthrough
12121     case Intrinsic::x86_sse41_ptestc:
12122     case Intrinsic::x86_avx_ptestc_256:
12123       // CF = 1
12124       X86CC = X86::COND_B;
12125       break;
12126     case Intrinsic::x86_avx_vtestnzc_ps:
12127     case Intrinsic::x86_avx_vtestnzc_pd:
12128     case Intrinsic::x86_avx_vtestnzc_ps_256:
12129     case Intrinsic::x86_avx_vtestnzc_pd_256:
12130       IsTestPacked = true; // Fallthrough
12131     case Intrinsic::x86_sse41_ptestnzc:
12132     case Intrinsic::x86_avx_ptestnzc_256:
12133       // ZF and CF = 0
12134       X86CC = X86::COND_A;
12135       break;
12136     }
12137
12138     SDValue LHS = Op.getOperand(1);
12139     SDValue RHS = Op.getOperand(2);
12140     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12141     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12142     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12143     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12144     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12145   }
12146   case Intrinsic::x86_avx512_kortestz_w:
12147   case Intrinsic::x86_avx512_kortestc_w: {
12148     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12149     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12150     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12151     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12152     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12153     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12154     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12155   }
12156
12157   // SSE/AVX shift intrinsics
12158   case Intrinsic::x86_sse2_psll_w:
12159   case Intrinsic::x86_sse2_psll_d:
12160   case Intrinsic::x86_sse2_psll_q:
12161   case Intrinsic::x86_avx2_psll_w:
12162   case Intrinsic::x86_avx2_psll_d:
12163   case Intrinsic::x86_avx2_psll_q:
12164   case Intrinsic::x86_sse2_psrl_w:
12165   case Intrinsic::x86_sse2_psrl_d:
12166   case Intrinsic::x86_sse2_psrl_q:
12167   case Intrinsic::x86_avx2_psrl_w:
12168   case Intrinsic::x86_avx2_psrl_d:
12169   case Intrinsic::x86_avx2_psrl_q:
12170   case Intrinsic::x86_sse2_psra_w:
12171   case Intrinsic::x86_sse2_psra_d:
12172   case Intrinsic::x86_avx2_psra_w:
12173   case Intrinsic::x86_avx2_psra_d: {
12174     unsigned Opcode;
12175     switch (IntNo) {
12176     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12177     case Intrinsic::x86_sse2_psll_w:
12178     case Intrinsic::x86_sse2_psll_d:
12179     case Intrinsic::x86_sse2_psll_q:
12180     case Intrinsic::x86_avx2_psll_w:
12181     case Intrinsic::x86_avx2_psll_d:
12182     case Intrinsic::x86_avx2_psll_q:
12183       Opcode = X86ISD::VSHL;
12184       break;
12185     case Intrinsic::x86_sse2_psrl_w:
12186     case Intrinsic::x86_sse2_psrl_d:
12187     case Intrinsic::x86_sse2_psrl_q:
12188     case Intrinsic::x86_avx2_psrl_w:
12189     case Intrinsic::x86_avx2_psrl_d:
12190     case Intrinsic::x86_avx2_psrl_q:
12191       Opcode = X86ISD::VSRL;
12192       break;
12193     case Intrinsic::x86_sse2_psra_w:
12194     case Intrinsic::x86_sse2_psra_d:
12195     case Intrinsic::x86_avx2_psra_w:
12196     case Intrinsic::x86_avx2_psra_d:
12197       Opcode = X86ISD::VSRA;
12198       break;
12199     }
12200     return DAG.getNode(Opcode, dl, Op.getValueType(),
12201                        Op.getOperand(1), Op.getOperand(2));
12202   }
12203
12204   // SSE/AVX immediate shift intrinsics
12205   case Intrinsic::x86_sse2_pslli_w:
12206   case Intrinsic::x86_sse2_pslli_d:
12207   case Intrinsic::x86_sse2_pslli_q:
12208   case Intrinsic::x86_avx2_pslli_w:
12209   case Intrinsic::x86_avx2_pslli_d:
12210   case Intrinsic::x86_avx2_pslli_q:
12211   case Intrinsic::x86_sse2_psrli_w:
12212   case Intrinsic::x86_sse2_psrli_d:
12213   case Intrinsic::x86_sse2_psrli_q:
12214   case Intrinsic::x86_avx2_psrli_w:
12215   case Intrinsic::x86_avx2_psrli_d:
12216   case Intrinsic::x86_avx2_psrli_q:
12217   case Intrinsic::x86_sse2_psrai_w:
12218   case Intrinsic::x86_sse2_psrai_d:
12219   case Intrinsic::x86_avx2_psrai_w:
12220   case Intrinsic::x86_avx2_psrai_d: {
12221     unsigned Opcode;
12222     switch (IntNo) {
12223     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12224     case Intrinsic::x86_sse2_pslli_w:
12225     case Intrinsic::x86_sse2_pslli_d:
12226     case Intrinsic::x86_sse2_pslli_q:
12227     case Intrinsic::x86_avx2_pslli_w:
12228     case Intrinsic::x86_avx2_pslli_d:
12229     case Intrinsic::x86_avx2_pslli_q:
12230       Opcode = X86ISD::VSHLI;
12231       break;
12232     case Intrinsic::x86_sse2_psrli_w:
12233     case Intrinsic::x86_sse2_psrli_d:
12234     case Intrinsic::x86_sse2_psrli_q:
12235     case Intrinsic::x86_avx2_psrli_w:
12236     case Intrinsic::x86_avx2_psrli_d:
12237     case Intrinsic::x86_avx2_psrli_q:
12238       Opcode = X86ISD::VSRLI;
12239       break;
12240     case Intrinsic::x86_sse2_psrai_w:
12241     case Intrinsic::x86_sse2_psrai_d:
12242     case Intrinsic::x86_avx2_psrai_w:
12243     case Intrinsic::x86_avx2_psrai_d:
12244       Opcode = X86ISD::VSRAI;
12245       break;
12246     }
12247     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12248                                Op.getOperand(1), Op.getOperand(2), DAG);
12249   }
12250
12251   case Intrinsic::x86_sse42_pcmpistria128:
12252   case Intrinsic::x86_sse42_pcmpestria128:
12253   case Intrinsic::x86_sse42_pcmpistric128:
12254   case Intrinsic::x86_sse42_pcmpestric128:
12255   case Intrinsic::x86_sse42_pcmpistrio128:
12256   case Intrinsic::x86_sse42_pcmpestrio128:
12257   case Intrinsic::x86_sse42_pcmpistris128:
12258   case Intrinsic::x86_sse42_pcmpestris128:
12259   case Intrinsic::x86_sse42_pcmpistriz128:
12260   case Intrinsic::x86_sse42_pcmpestriz128: {
12261     unsigned Opcode;
12262     unsigned X86CC;
12263     switch (IntNo) {
12264     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12265     case Intrinsic::x86_sse42_pcmpistria128:
12266       Opcode = X86ISD::PCMPISTRI;
12267       X86CC = X86::COND_A;
12268       break;
12269     case Intrinsic::x86_sse42_pcmpestria128:
12270       Opcode = X86ISD::PCMPESTRI;
12271       X86CC = X86::COND_A;
12272       break;
12273     case Intrinsic::x86_sse42_pcmpistric128:
12274       Opcode = X86ISD::PCMPISTRI;
12275       X86CC = X86::COND_B;
12276       break;
12277     case Intrinsic::x86_sse42_pcmpestric128:
12278       Opcode = X86ISD::PCMPESTRI;
12279       X86CC = X86::COND_B;
12280       break;
12281     case Intrinsic::x86_sse42_pcmpistrio128:
12282       Opcode = X86ISD::PCMPISTRI;
12283       X86CC = X86::COND_O;
12284       break;
12285     case Intrinsic::x86_sse42_pcmpestrio128:
12286       Opcode = X86ISD::PCMPESTRI;
12287       X86CC = X86::COND_O;
12288       break;
12289     case Intrinsic::x86_sse42_pcmpistris128:
12290       Opcode = X86ISD::PCMPISTRI;
12291       X86CC = X86::COND_S;
12292       break;
12293     case Intrinsic::x86_sse42_pcmpestris128:
12294       Opcode = X86ISD::PCMPESTRI;
12295       X86CC = X86::COND_S;
12296       break;
12297     case Intrinsic::x86_sse42_pcmpistriz128:
12298       Opcode = X86ISD::PCMPISTRI;
12299       X86CC = X86::COND_E;
12300       break;
12301     case Intrinsic::x86_sse42_pcmpestriz128:
12302       Opcode = X86ISD::PCMPESTRI;
12303       X86CC = X86::COND_E;
12304       break;
12305     }
12306     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12307     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12308     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12309     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12310                                 DAG.getConstant(X86CC, MVT::i8),
12311                                 SDValue(PCMP.getNode(), 1));
12312     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12313   }
12314
12315   case Intrinsic::x86_sse42_pcmpistri128:
12316   case Intrinsic::x86_sse42_pcmpestri128: {
12317     unsigned Opcode;
12318     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12319       Opcode = X86ISD::PCMPISTRI;
12320     else
12321       Opcode = X86ISD::PCMPESTRI;
12322
12323     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12324     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12325     return DAG.getNode(Opcode, dl, VTs, NewOps);
12326   }
12327   case Intrinsic::x86_fma_vfmadd_ps:
12328   case Intrinsic::x86_fma_vfmadd_pd:
12329   case Intrinsic::x86_fma_vfmsub_ps:
12330   case Intrinsic::x86_fma_vfmsub_pd:
12331   case Intrinsic::x86_fma_vfnmadd_ps:
12332   case Intrinsic::x86_fma_vfnmadd_pd:
12333   case Intrinsic::x86_fma_vfnmsub_ps:
12334   case Intrinsic::x86_fma_vfnmsub_pd:
12335   case Intrinsic::x86_fma_vfmaddsub_ps:
12336   case Intrinsic::x86_fma_vfmaddsub_pd:
12337   case Intrinsic::x86_fma_vfmsubadd_ps:
12338   case Intrinsic::x86_fma_vfmsubadd_pd:
12339   case Intrinsic::x86_fma_vfmadd_ps_256:
12340   case Intrinsic::x86_fma_vfmadd_pd_256:
12341   case Intrinsic::x86_fma_vfmsub_ps_256:
12342   case Intrinsic::x86_fma_vfmsub_pd_256:
12343   case Intrinsic::x86_fma_vfnmadd_ps_256:
12344   case Intrinsic::x86_fma_vfnmadd_pd_256:
12345   case Intrinsic::x86_fma_vfnmsub_ps_256:
12346   case Intrinsic::x86_fma_vfnmsub_pd_256:
12347   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12348   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12349   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12350   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12351   case Intrinsic::x86_fma_vfmadd_ps_512:
12352   case Intrinsic::x86_fma_vfmadd_pd_512:
12353   case Intrinsic::x86_fma_vfmsub_ps_512:
12354   case Intrinsic::x86_fma_vfmsub_pd_512:
12355   case Intrinsic::x86_fma_vfnmadd_ps_512:
12356   case Intrinsic::x86_fma_vfnmadd_pd_512:
12357   case Intrinsic::x86_fma_vfnmsub_ps_512:
12358   case Intrinsic::x86_fma_vfnmsub_pd_512:
12359   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12360   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12361   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12362   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12363     unsigned Opc;
12364     switch (IntNo) {
12365     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12366     case Intrinsic::x86_fma_vfmadd_ps:
12367     case Intrinsic::x86_fma_vfmadd_pd:
12368     case Intrinsic::x86_fma_vfmadd_ps_256:
12369     case Intrinsic::x86_fma_vfmadd_pd_256:
12370     case Intrinsic::x86_fma_vfmadd_ps_512:
12371     case Intrinsic::x86_fma_vfmadd_pd_512:
12372       Opc = X86ISD::FMADD;
12373       break;
12374     case Intrinsic::x86_fma_vfmsub_ps:
12375     case Intrinsic::x86_fma_vfmsub_pd:
12376     case Intrinsic::x86_fma_vfmsub_ps_256:
12377     case Intrinsic::x86_fma_vfmsub_pd_256:
12378     case Intrinsic::x86_fma_vfmsub_ps_512:
12379     case Intrinsic::x86_fma_vfmsub_pd_512:
12380       Opc = X86ISD::FMSUB;
12381       break;
12382     case Intrinsic::x86_fma_vfnmadd_ps:
12383     case Intrinsic::x86_fma_vfnmadd_pd:
12384     case Intrinsic::x86_fma_vfnmadd_ps_256:
12385     case Intrinsic::x86_fma_vfnmadd_pd_256:
12386     case Intrinsic::x86_fma_vfnmadd_ps_512:
12387     case Intrinsic::x86_fma_vfnmadd_pd_512:
12388       Opc = X86ISD::FNMADD;
12389       break;
12390     case Intrinsic::x86_fma_vfnmsub_ps:
12391     case Intrinsic::x86_fma_vfnmsub_pd:
12392     case Intrinsic::x86_fma_vfnmsub_ps_256:
12393     case Intrinsic::x86_fma_vfnmsub_pd_256:
12394     case Intrinsic::x86_fma_vfnmsub_ps_512:
12395     case Intrinsic::x86_fma_vfnmsub_pd_512:
12396       Opc = X86ISD::FNMSUB;
12397       break;
12398     case Intrinsic::x86_fma_vfmaddsub_ps:
12399     case Intrinsic::x86_fma_vfmaddsub_pd:
12400     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12401     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12402     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12403     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12404       Opc = X86ISD::FMADDSUB;
12405       break;
12406     case Intrinsic::x86_fma_vfmsubadd_ps:
12407     case Intrinsic::x86_fma_vfmsubadd_pd:
12408     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12409     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12410     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12411     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12412       Opc = X86ISD::FMSUBADD;
12413       break;
12414     }
12415
12416     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12417                        Op.getOperand(2), Op.getOperand(3));
12418   }
12419   }
12420 }
12421
12422 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12423                              SDValue Base, SDValue Index,
12424                              SDValue ScaleOp, SDValue Chain,
12425                              const X86Subtarget * Subtarget) {
12426   SDLoc dl(Op);
12427   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12428   assert(C && "Invalid scale type");
12429   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12430   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12431   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12432                              Index.getSimpleValueType().getVectorNumElements());
12433   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12434   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12435   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12436   SDValue Segment = DAG.getRegister(0, MVT::i32);
12437   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12438   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12439   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12440   return DAG.getMergeValues(RetOps, dl);
12441 }
12442
12443 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12444                               SDValue Src, SDValue Mask, SDValue Base,
12445                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12446                               const X86Subtarget * Subtarget) {
12447   SDLoc dl(Op);
12448   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12449   assert(C && "Invalid scale type");
12450   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12451   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12452                              Index.getSimpleValueType().getVectorNumElements());
12453   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12454   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12455   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12456   SDValue Segment = DAG.getRegister(0, MVT::i32);
12457   if (Src.getOpcode() == ISD::UNDEF)
12458     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12459   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12460   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12461   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12462   return DAG.getMergeValues(RetOps, dl);
12463 }
12464
12465 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12466                               SDValue Src, SDValue Base, SDValue Index,
12467                               SDValue ScaleOp, SDValue Chain) {
12468   SDLoc dl(Op);
12469   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12470   assert(C && "Invalid scale type");
12471   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12472   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12473   SDValue Segment = DAG.getRegister(0, MVT::i32);
12474   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12475                              Index.getSimpleValueType().getVectorNumElements());
12476   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12477   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12478   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12479   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12480   return SDValue(Res, 1);
12481 }
12482
12483 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12484                                SDValue Src, SDValue Mask, SDValue Base,
12485                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12486   SDLoc dl(Op);
12487   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12488   assert(C && "Invalid scale type");
12489   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12490   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12491   SDValue Segment = DAG.getRegister(0, MVT::i32);
12492   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12493                              Index.getSimpleValueType().getVectorNumElements());
12494   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12495   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12496   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12497   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12498   return SDValue(Res, 1);
12499 }
12500
12501 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12502 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12503 // also used to custom lower READCYCLECOUNTER nodes.
12504 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12505                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12506                               SmallVectorImpl<SDValue> &Results) {
12507   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12508   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12509   SDValue LO, HI;
12510
12511   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12512   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12513   // and the EAX register is loaded with the low-order 32 bits.
12514   if (Subtarget->is64Bit()) {
12515     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12516     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12517                             LO.getValue(2));
12518   } else {
12519     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12520     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12521                             LO.getValue(2));
12522   }
12523   SDValue Chain = HI.getValue(1);
12524
12525   if (Opcode == X86ISD::RDTSCP_DAG) {
12526     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12527
12528     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12529     // the ECX register. Add 'ecx' explicitly to the chain.
12530     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12531                                      HI.getValue(2));
12532     // Explicitly store the content of ECX at the location passed in input
12533     // to the 'rdtscp' intrinsic.
12534     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12535                          MachinePointerInfo(), false, false, 0);
12536   }
12537
12538   if (Subtarget->is64Bit()) {
12539     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12540     // the EAX register is loaded with the low-order 32 bits.
12541     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12542                               DAG.getConstant(32, MVT::i8));
12543     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12544     Results.push_back(Chain);
12545     return;
12546   }
12547
12548   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12549   SDValue Ops[] = { LO, HI };
12550   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12551   Results.push_back(Pair);
12552   Results.push_back(Chain);
12553 }
12554
12555 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12556                                      SelectionDAG &DAG) {
12557   SmallVector<SDValue, 2> Results;
12558   SDLoc DL(Op);
12559   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12560                           Results);
12561   return DAG.getMergeValues(Results, DL);
12562 }
12563
12564 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12565                                       SelectionDAG &DAG) {
12566   SDLoc dl(Op);
12567   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12568   switch (IntNo) {
12569   default: return SDValue();    // Don't custom lower most intrinsics.
12570
12571   // RDRAND/RDSEED intrinsics.
12572   case Intrinsic::x86_rdrand_16:
12573   case Intrinsic::x86_rdrand_32:
12574   case Intrinsic::x86_rdrand_64:
12575   case Intrinsic::x86_rdseed_16:
12576   case Intrinsic::x86_rdseed_32:
12577   case Intrinsic::x86_rdseed_64: {
12578     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12579                        IntNo == Intrinsic::x86_rdseed_32 ||
12580                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12581                                                             X86ISD::RDRAND;
12582     // Emit the node with the right value type.
12583     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12584     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12585
12586     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12587     // Otherwise return the value from Rand, which is always 0, casted to i32.
12588     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12589                       DAG.getConstant(1, Op->getValueType(1)),
12590                       DAG.getConstant(X86::COND_B, MVT::i32),
12591                       SDValue(Result.getNode(), 1) };
12592     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12593                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12594                                   Ops);
12595
12596     // Return { result, isValid, chain }.
12597     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12598                        SDValue(Result.getNode(), 2));
12599   }
12600   //int_gather(index, base, scale);
12601   case Intrinsic::x86_avx512_gather_qpd_512:
12602   case Intrinsic::x86_avx512_gather_qps_512:
12603   case Intrinsic::x86_avx512_gather_dpd_512:
12604   case Intrinsic::x86_avx512_gather_qpi_512:
12605   case Intrinsic::x86_avx512_gather_qpq_512:
12606   case Intrinsic::x86_avx512_gather_dpq_512:
12607   case Intrinsic::x86_avx512_gather_dps_512:
12608   case Intrinsic::x86_avx512_gather_dpi_512: {
12609     unsigned Opc;
12610     switch (IntNo) {
12611     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12612     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12613     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12614     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12615     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12616     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12617     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12618     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12619     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12620     }
12621     SDValue Chain = Op.getOperand(0);
12622     SDValue Index = Op.getOperand(2);
12623     SDValue Base  = Op.getOperand(3);
12624     SDValue Scale = Op.getOperand(4);
12625     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12626   }
12627   //int_gather_mask(v1, mask, index, base, scale);
12628   case Intrinsic::x86_avx512_gather_qps_mask_512:
12629   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12630   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12631   case Intrinsic::x86_avx512_gather_dps_mask_512:
12632   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12633   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12634   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12635   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12636     unsigned Opc;
12637     switch (IntNo) {
12638     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12639     case Intrinsic::x86_avx512_gather_qps_mask_512:
12640       Opc = X86::VGATHERQPSZrm; break;
12641     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12642       Opc = X86::VGATHERQPDZrm; break;
12643     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12644       Opc = X86::VGATHERDPDZrm; break;
12645     case Intrinsic::x86_avx512_gather_dps_mask_512:
12646       Opc = X86::VGATHERDPSZrm; break;
12647     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12648       Opc = X86::VPGATHERQDZrm; break;
12649     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12650       Opc = X86::VPGATHERQQZrm; break;
12651     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12652       Opc = X86::VPGATHERDDZrm; break;
12653     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12654       Opc = X86::VPGATHERDQZrm; break;
12655     }
12656     SDValue Chain = Op.getOperand(0);
12657     SDValue Src   = Op.getOperand(2);
12658     SDValue Mask  = Op.getOperand(3);
12659     SDValue Index = Op.getOperand(4);
12660     SDValue Base  = Op.getOperand(5);
12661     SDValue Scale = Op.getOperand(6);
12662     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12663                           Subtarget);
12664   }
12665   //int_scatter(base, index, v1, scale);
12666   case Intrinsic::x86_avx512_scatter_qpd_512:
12667   case Intrinsic::x86_avx512_scatter_qps_512:
12668   case Intrinsic::x86_avx512_scatter_dpd_512:
12669   case Intrinsic::x86_avx512_scatter_qpi_512:
12670   case Intrinsic::x86_avx512_scatter_qpq_512:
12671   case Intrinsic::x86_avx512_scatter_dpq_512:
12672   case Intrinsic::x86_avx512_scatter_dps_512:
12673   case Intrinsic::x86_avx512_scatter_dpi_512: {
12674     unsigned Opc;
12675     switch (IntNo) {
12676     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12677     case Intrinsic::x86_avx512_scatter_qpd_512:
12678       Opc = X86::VSCATTERQPDZmr; break;
12679     case Intrinsic::x86_avx512_scatter_qps_512:
12680       Opc = X86::VSCATTERQPSZmr; break;
12681     case Intrinsic::x86_avx512_scatter_dpd_512:
12682       Opc = X86::VSCATTERDPDZmr; break;
12683     case Intrinsic::x86_avx512_scatter_dps_512:
12684       Opc = X86::VSCATTERDPSZmr; break;
12685     case Intrinsic::x86_avx512_scatter_qpi_512:
12686       Opc = X86::VPSCATTERQDZmr; break;
12687     case Intrinsic::x86_avx512_scatter_qpq_512:
12688       Opc = X86::VPSCATTERQQZmr; break;
12689     case Intrinsic::x86_avx512_scatter_dpq_512:
12690       Opc = X86::VPSCATTERDQZmr; break;
12691     case Intrinsic::x86_avx512_scatter_dpi_512:
12692       Opc = X86::VPSCATTERDDZmr; break;
12693     }
12694     SDValue Chain = Op.getOperand(0);
12695     SDValue Base  = Op.getOperand(2);
12696     SDValue Index = Op.getOperand(3);
12697     SDValue Src   = Op.getOperand(4);
12698     SDValue Scale = Op.getOperand(5);
12699     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12700   }
12701   //int_scatter_mask(base, mask, index, v1, scale);
12702   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12703   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12704   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12705   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12706   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12707   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12708   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12709   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12710     unsigned Opc;
12711     switch (IntNo) {
12712     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12713     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12714       Opc = X86::VSCATTERQPDZmr; break;
12715     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12716       Opc = X86::VSCATTERQPSZmr; break;
12717     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12718       Opc = X86::VSCATTERDPDZmr; break;
12719     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12720       Opc = X86::VSCATTERDPSZmr; break;
12721     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12722       Opc = X86::VPSCATTERQDZmr; break;
12723     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12724       Opc = X86::VPSCATTERQQZmr; break;
12725     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12726       Opc = X86::VPSCATTERDQZmr; break;
12727     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12728       Opc = X86::VPSCATTERDDZmr; break;
12729     }
12730     SDValue Chain = Op.getOperand(0);
12731     SDValue Base  = Op.getOperand(2);
12732     SDValue Mask  = Op.getOperand(3);
12733     SDValue Index = Op.getOperand(4);
12734     SDValue Src   = Op.getOperand(5);
12735     SDValue Scale = Op.getOperand(6);
12736     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12737   }
12738   // Read Time Stamp Counter (RDTSC).
12739   case Intrinsic::x86_rdtsc:
12740   // Read Time Stamp Counter and Processor ID (RDTSCP).
12741   case Intrinsic::x86_rdtscp: {
12742     unsigned Opc;
12743     switch (IntNo) {
12744     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12745     case Intrinsic::x86_rdtsc:
12746       Opc = X86ISD::RDTSC_DAG; break;
12747     case Intrinsic::x86_rdtscp:
12748       Opc = X86ISD::RDTSCP_DAG; break;
12749     }
12750     SmallVector<SDValue, 2> Results;
12751     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12752     return DAG.getMergeValues(Results, dl);
12753   }
12754   // XTEST intrinsics.
12755   case Intrinsic::x86_xtest: {
12756     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12757     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12758     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12759                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12760                                 InTrans);
12761     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12762     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12763                        Ret, SDValue(InTrans.getNode(), 1));
12764   }
12765   }
12766 }
12767
12768 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12769                                            SelectionDAG &DAG) const {
12770   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12771   MFI->setReturnAddressIsTaken(true);
12772
12773   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12774     return SDValue();
12775
12776   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12777   SDLoc dl(Op);
12778   EVT PtrVT = getPointerTy();
12779
12780   if (Depth > 0) {
12781     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12782     const X86RegisterInfo *RegInfo =
12783       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12784     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12785     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12786                        DAG.getNode(ISD::ADD, dl, PtrVT,
12787                                    FrameAddr, Offset),
12788                        MachinePointerInfo(), false, false, false, 0);
12789   }
12790
12791   // Just load the return address.
12792   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12793   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12794                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12795 }
12796
12797 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12798   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12799   MFI->setFrameAddressIsTaken(true);
12800
12801   EVT VT = Op.getValueType();
12802   SDLoc dl(Op);  // FIXME probably not meaningful
12803   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12804   const X86RegisterInfo *RegInfo =
12805     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12806   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12807   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12808           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12809          "Invalid Frame Register!");
12810   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12811   while (Depth--)
12812     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12813                             MachinePointerInfo(),
12814                             false, false, false, 0);
12815   return FrameAddr;
12816 }
12817
12818 // FIXME? Maybe this could be a TableGen attribute on some registers and
12819 // this table could be generated automatically from RegInfo.
12820 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12821                                               EVT VT) const {
12822   unsigned Reg = StringSwitch<unsigned>(RegName)
12823                        .Case("esp", X86::ESP)
12824                        .Case("rsp", X86::RSP)
12825                        .Default(0);
12826   if (Reg)
12827     return Reg;
12828   report_fatal_error("Invalid register name global variable");
12829 }
12830
12831 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12832                                                      SelectionDAG &DAG) const {
12833   const X86RegisterInfo *RegInfo =
12834     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12835   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12836 }
12837
12838 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12839   SDValue Chain     = Op.getOperand(0);
12840   SDValue Offset    = Op.getOperand(1);
12841   SDValue Handler   = Op.getOperand(2);
12842   SDLoc dl      (Op);
12843
12844   EVT PtrVT = getPointerTy();
12845   const X86RegisterInfo *RegInfo =
12846     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12847   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12848   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12849           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12850          "Invalid Frame Register!");
12851   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12852   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12853
12854   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12855                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12856   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12857   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12858                        false, false, 0);
12859   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12860
12861   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12862                      DAG.getRegister(StoreAddrReg, PtrVT));
12863 }
12864
12865 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12866                                                SelectionDAG &DAG) const {
12867   SDLoc DL(Op);
12868   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12869                      DAG.getVTList(MVT::i32, MVT::Other),
12870                      Op.getOperand(0), Op.getOperand(1));
12871 }
12872
12873 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12874                                                 SelectionDAG &DAG) const {
12875   SDLoc DL(Op);
12876   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12877                      Op.getOperand(0), Op.getOperand(1));
12878 }
12879
12880 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12881   return Op.getOperand(0);
12882 }
12883
12884 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12885                                                 SelectionDAG &DAG) const {
12886   SDValue Root = Op.getOperand(0);
12887   SDValue Trmp = Op.getOperand(1); // trampoline
12888   SDValue FPtr = Op.getOperand(2); // nested function
12889   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12890   SDLoc dl (Op);
12891
12892   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12893   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12894
12895   if (Subtarget->is64Bit()) {
12896     SDValue OutChains[6];
12897
12898     // Large code-model.
12899     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12900     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12901
12902     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12903     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12904
12905     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12906
12907     // Load the pointer to the nested function into R11.
12908     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12909     SDValue Addr = Trmp;
12910     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12911                                 Addr, MachinePointerInfo(TrmpAddr),
12912                                 false, false, 0);
12913
12914     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12915                        DAG.getConstant(2, MVT::i64));
12916     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12917                                 MachinePointerInfo(TrmpAddr, 2),
12918                                 false, false, 2);
12919
12920     // Load the 'nest' parameter value into R10.
12921     // R10 is specified in X86CallingConv.td
12922     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12923     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12924                        DAG.getConstant(10, MVT::i64));
12925     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12926                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12927                                 false, false, 0);
12928
12929     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12930                        DAG.getConstant(12, MVT::i64));
12931     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12932                                 MachinePointerInfo(TrmpAddr, 12),
12933                                 false, false, 2);
12934
12935     // Jump to the nested function.
12936     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12937     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12938                        DAG.getConstant(20, MVT::i64));
12939     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12940                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12941                                 false, false, 0);
12942
12943     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12944     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12945                        DAG.getConstant(22, MVT::i64));
12946     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12947                                 MachinePointerInfo(TrmpAddr, 22),
12948                                 false, false, 0);
12949
12950     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12951   } else {
12952     const Function *Func =
12953       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12954     CallingConv::ID CC = Func->getCallingConv();
12955     unsigned NestReg;
12956
12957     switch (CC) {
12958     default:
12959       llvm_unreachable("Unsupported calling convention");
12960     case CallingConv::C:
12961     case CallingConv::X86_StdCall: {
12962       // Pass 'nest' parameter in ECX.
12963       // Must be kept in sync with X86CallingConv.td
12964       NestReg = X86::ECX;
12965
12966       // Check that ECX wasn't needed by an 'inreg' parameter.
12967       FunctionType *FTy = Func->getFunctionType();
12968       const AttributeSet &Attrs = Func->getAttributes();
12969
12970       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12971         unsigned InRegCount = 0;
12972         unsigned Idx = 1;
12973
12974         for (FunctionType::param_iterator I = FTy->param_begin(),
12975              E = FTy->param_end(); I != E; ++I, ++Idx)
12976           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12977             // FIXME: should only count parameters that are lowered to integers.
12978             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12979
12980         if (InRegCount > 2) {
12981           report_fatal_error("Nest register in use - reduce number of inreg"
12982                              " parameters!");
12983         }
12984       }
12985       break;
12986     }
12987     case CallingConv::X86_FastCall:
12988     case CallingConv::X86_ThisCall:
12989     case CallingConv::Fast:
12990       // Pass 'nest' parameter in EAX.
12991       // Must be kept in sync with X86CallingConv.td
12992       NestReg = X86::EAX;
12993       break;
12994     }
12995
12996     SDValue OutChains[4];
12997     SDValue Addr, Disp;
12998
12999     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13000                        DAG.getConstant(10, MVT::i32));
13001     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13002
13003     // This is storing the opcode for MOV32ri.
13004     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13005     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13006     OutChains[0] = DAG.getStore(Root, dl,
13007                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13008                                 Trmp, MachinePointerInfo(TrmpAddr),
13009                                 false, false, 0);
13010
13011     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13012                        DAG.getConstant(1, MVT::i32));
13013     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13014                                 MachinePointerInfo(TrmpAddr, 1),
13015                                 false, false, 1);
13016
13017     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13018     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13019                        DAG.getConstant(5, MVT::i32));
13020     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13021                                 MachinePointerInfo(TrmpAddr, 5),
13022                                 false, false, 1);
13023
13024     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13025                        DAG.getConstant(6, MVT::i32));
13026     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13027                                 MachinePointerInfo(TrmpAddr, 6),
13028                                 false, false, 1);
13029
13030     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13031   }
13032 }
13033
13034 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13035                                             SelectionDAG &DAG) const {
13036   /*
13037    The rounding mode is in bits 11:10 of FPSR, and has the following
13038    settings:
13039      00 Round to nearest
13040      01 Round to -inf
13041      10 Round to +inf
13042      11 Round to 0
13043
13044   FLT_ROUNDS, on the other hand, expects the following:
13045     -1 Undefined
13046      0 Round to 0
13047      1 Round to nearest
13048      2 Round to +inf
13049      3 Round to -inf
13050
13051   To perform the conversion, we do:
13052     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13053   */
13054
13055   MachineFunction &MF = DAG.getMachineFunction();
13056   const TargetMachine &TM = MF.getTarget();
13057   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13058   unsigned StackAlignment = TFI.getStackAlignment();
13059   MVT VT = Op.getSimpleValueType();
13060   SDLoc DL(Op);
13061
13062   // Save FP Control Word to stack slot
13063   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13064   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13065
13066   MachineMemOperand *MMO =
13067    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13068                            MachineMemOperand::MOStore, 2, 2);
13069
13070   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13071   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13072                                           DAG.getVTList(MVT::Other),
13073                                           Ops, MVT::i16, MMO);
13074
13075   // Load FP Control Word from stack slot
13076   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13077                             MachinePointerInfo(), false, false, false, 0);
13078
13079   // Transform as necessary
13080   SDValue CWD1 =
13081     DAG.getNode(ISD::SRL, DL, MVT::i16,
13082                 DAG.getNode(ISD::AND, DL, MVT::i16,
13083                             CWD, DAG.getConstant(0x800, MVT::i16)),
13084                 DAG.getConstant(11, MVT::i8));
13085   SDValue CWD2 =
13086     DAG.getNode(ISD::SRL, DL, MVT::i16,
13087                 DAG.getNode(ISD::AND, DL, MVT::i16,
13088                             CWD, DAG.getConstant(0x400, MVT::i16)),
13089                 DAG.getConstant(9, MVT::i8));
13090
13091   SDValue RetVal =
13092     DAG.getNode(ISD::AND, DL, MVT::i16,
13093                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13094                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13095                             DAG.getConstant(1, MVT::i16)),
13096                 DAG.getConstant(3, MVT::i16));
13097
13098   return DAG.getNode((VT.getSizeInBits() < 16 ?
13099                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13100 }
13101
13102 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13103   MVT VT = Op.getSimpleValueType();
13104   EVT OpVT = VT;
13105   unsigned NumBits = VT.getSizeInBits();
13106   SDLoc dl(Op);
13107
13108   Op = Op.getOperand(0);
13109   if (VT == MVT::i8) {
13110     // Zero extend to i32 since there is not an i8 bsr.
13111     OpVT = MVT::i32;
13112     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13113   }
13114
13115   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13116   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13117   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13118
13119   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13120   SDValue Ops[] = {
13121     Op,
13122     DAG.getConstant(NumBits+NumBits-1, OpVT),
13123     DAG.getConstant(X86::COND_E, MVT::i8),
13124     Op.getValue(1)
13125   };
13126   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13127
13128   // Finally xor with NumBits-1.
13129   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13130
13131   if (VT == MVT::i8)
13132     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13133   return Op;
13134 }
13135
13136 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13137   MVT VT = Op.getSimpleValueType();
13138   EVT OpVT = VT;
13139   unsigned NumBits = VT.getSizeInBits();
13140   SDLoc dl(Op);
13141
13142   Op = Op.getOperand(0);
13143   if (VT == MVT::i8) {
13144     // Zero extend to i32 since there is not an i8 bsr.
13145     OpVT = MVT::i32;
13146     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13147   }
13148
13149   // Issue a bsr (scan bits in reverse).
13150   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13151   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13152
13153   // And xor with NumBits-1.
13154   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13155
13156   if (VT == MVT::i8)
13157     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13158   return Op;
13159 }
13160
13161 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13162   MVT VT = Op.getSimpleValueType();
13163   unsigned NumBits = VT.getSizeInBits();
13164   SDLoc dl(Op);
13165   Op = Op.getOperand(0);
13166
13167   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13168   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13169   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13170
13171   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13172   SDValue Ops[] = {
13173     Op,
13174     DAG.getConstant(NumBits, VT),
13175     DAG.getConstant(X86::COND_E, MVT::i8),
13176     Op.getValue(1)
13177   };
13178   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13179 }
13180
13181 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13182 // ones, and then concatenate the result back.
13183 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13184   MVT VT = Op.getSimpleValueType();
13185
13186   assert(VT.is256BitVector() && VT.isInteger() &&
13187          "Unsupported value type for operation");
13188
13189   unsigned NumElems = VT.getVectorNumElements();
13190   SDLoc dl(Op);
13191
13192   // Extract the LHS vectors
13193   SDValue LHS = Op.getOperand(0);
13194   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13195   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13196
13197   // Extract the RHS vectors
13198   SDValue RHS = Op.getOperand(1);
13199   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13200   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13201
13202   MVT EltVT = VT.getVectorElementType();
13203   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13204
13205   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13206                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13207                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13208 }
13209
13210 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13211   assert(Op.getSimpleValueType().is256BitVector() &&
13212          Op.getSimpleValueType().isInteger() &&
13213          "Only handle AVX 256-bit vector integer operation");
13214   return Lower256IntArith(Op, DAG);
13215 }
13216
13217 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13218   assert(Op.getSimpleValueType().is256BitVector() &&
13219          Op.getSimpleValueType().isInteger() &&
13220          "Only handle AVX 256-bit vector integer operation");
13221   return Lower256IntArith(Op, DAG);
13222 }
13223
13224 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13225                         SelectionDAG &DAG) {
13226   SDLoc dl(Op);
13227   MVT VT = Op.getSimpleValueType();
13228
13229   // Decompose 256-bit ops into smaller 128-bit ops.
13230   if (VT.is256BitVector() && !Subtarget->hasInt256())
13231     return Lower256IntArith(Op, DAG);
13232
13233   SDValue A = Op.getOperand(0);
13234   SDValue B = Op.getOperand(1);
13235
13236   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13237   if (VT == MVT::v4i32) {
13238     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13239            "Should not custom lower when pmuldq is available!");
13240
13241     // Extract the odd parts.
13242     static const int UnpackMask[] = { 1, -1, 3, -1 };
13243     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13244     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13245
13246     // Multiply the even parts.
13247     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13248     // Now multiply odd parts.
13249     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13250
13251     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13252     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13253
13254     // Merge the two vectors back together with a shuffle. This expands into 2
13255     // shuffles.
13256     static const int ShufMask[] = { 0, 4, 2, 6 };
13257     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13258   }
13259
13260   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13261          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13262
13263   //  Ahi = psrlqi(a, 32);
13264   //  Bhi = psrlqi(b, 32);
13265   //
13266   //  AloBlo = pmuludq(a, b);
13267   //  AloBhi = pmuludq(a, Bhi);
13268   //  AhiBlo = pmuludq(Ahi, b);
13269
13270   //  AloBhi = psllqi(AloBhi, 32);
13271   //  AhiBlo = psllqi(AhiBlo, 32);
13272   //  return AloBlo + AloBhi + AhiBlo;
13273
13274   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13275   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13276
13277   // Bit cast to 32-bit vectors for MULUDQ
13278   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13279                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13280   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13281   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13282   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13283   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13284
13285   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13286   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13287   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13288
13289   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13290   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13291
13292   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13293   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13294 }
13295
13296 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13297   assert(Subtarget->isTargetWin64() && "Unexpected target");
13298   EVT VT = Op.getValueType();
13299   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13300          "Unexpected return type for lowering");
13301
13302   RTLIB::Libcall LC;
13303   bool isSigned;
13304   switch (Op->getOpcode()) {
13305   default: llvm_unreachable("Unexpected request for libcall!");
13306   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13307   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13308   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13309   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13310   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13311   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13312   }
13313
13314   SDLoc dl(Op);
13315   SDValue InChain = DAG.getEntryNode();
13316
13317   TargetLowering::ArgListTy Args;
13318   TargetLowering::ArgListEntry Entry;
13319   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13320     EVT ArgVT = Op->getOperand(i).getValueType();
13321     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13322            "Unexpected argument type for lowering");
13323     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13324     Entry.Node = StackPtr;
13325     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13326                            false, false, 16);
13327     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13328     Entry.Ty = PointerType::get(ArgTy,0);
13329     Entry.isSExt = false;
13330     Entry.isZExt = false;
13331     Args.push_back(Entry);
13332   }
13333
13334   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13335                                          getPointerTy());
13336
13337   TargetLowering::CallLoweringInfo CLI(
13338       InChain, static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13339       isSigned, !isSigned, false, true, 0, getLibcallCallingConv(LC),
13340       /*isTailCall=*/false,
13341       /*doesNotReturn=*/false, /*isReturnValueUsed=*/true, Callee, Args, DAG,
13342       dl);
13343   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13344
13345   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13346 }
13347
13348 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13349                              SelectionDAG &DAG) {
13350   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13351   EVT VT = Op0.getValueType();
13352   SDLoc dl(Op);
13353
13354   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13355          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13356
13357   // Get the high parts.
13358   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13359   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13360   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13361
13362   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13363   // ints.
13364   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13365   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13366   unsigned Opcode =
13367       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13368   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13369                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13370   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13371                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13372
13373   // Shuffle it back into the right order.
13374   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13375   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13376   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13377   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13378
13379   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13380   // unsigned multiply.
13381   if (IsSigned && !Subtarget->hasSSE41()) {
13382     SDValue ShAmt =
13383         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13384     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13385                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13386     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13387                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13388
13389     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13390     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13391   }
13392
13393   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13394 }
13395
13396 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13397                                          const X86Subtarget *Subtarget) {
13398   MVT VT = Op.getSimpleValueType();
13399   SDLoc dl(Op);
13400   SDValue R = Op.getOperand(0);
13401   SDValue Amt = Op.getOperand(1);
13402
13403   // Optimize shl/srl/sra with constant shift amount.
13404   if (isSplatVector(Amt.getNode())) {
13405     SDValue SclrAmt = Amt->getOperand(0);
13406     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13407       uint64_t ShiftAmt = C->getZExtValue();
13408
13409       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13410           (Subtarget->hasInt256() &&
13411            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13412           (Subtarget->hasAVX512() &&
13413            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13414         if (Op.getOpcode() == ISD::SHL)
13415           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13416                                             DAG);
13417         if (Op.getOpcode() == ISD::SRL)
13418           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13419                                             DAG);
13420         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13421           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13422                                             DAG);
13423       }
13424
13425       if (VT == MVT::v16i8) {
13426         if (Op.getOpcode() == ISD::SHL) {
13427           // Make a large shift.
13428           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13429                                                    MVT::v8i16, R, ShiftAmt,
13430                                                    DAG);
13431           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13432           // Zero out the rightmost bits.
13433           SmallVector<SDValue, 16> V(16,
13434                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13435                                                      MVT::i8));
13436           return DAG.getNode(ISD::AND, dl, VT, SHL,
13437                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13438         }
13439         if (Op.getOpcode() == ISD::SRL) {
13440           // Make a large shift.
13441           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13442                                                    MVT::v8i16, R, ShiftAmt,
13443                                                    DAG);
13444           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13445           // Zero out the leftmost bits.
13446           SmallVector<SDValue, 16> V(16,
13447                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13448                                                      MVT::i8));
13449           return DAG.getNode(ISD::AND, dl, VT, SRL,
13450                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13451         }
13452         if (Op.getOpcode() == ISD::SRA) {
13453           if (ShiftAmt == 7) {
13454             // R s>> 7  ===  R s< 0
13455             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13456             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13457           }
13458
13459           // R s>> a === ((R u>> a) ^ m) - m
13460           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13461           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13462                                                          MVT::i8));
13463           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13464           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13465           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13466           return Res;
13467         }
13468         llvm_unreachable("Unknown shift opcode.");
13469       }
13470
13471       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13472         if (Op.getOpcode() == ISD::SHL) {
13473           // Make a large shift.
13474           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13475                                                    MVT::v16i16, R, ShiftAmt,
13476                                                    DAG);
13477           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13478           // Zero out the rightmost bits.
13479           SmallVector<SDValue, 32> V(32,
13480                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13481                                                      MVT::i8));
13482           return DAG.getNode(ISD::AND, dl, VT, SHL,
13483                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13484         }
13485         if (Op.getOpcode() == ISD::SRL) {
13486           // Make a large shift.
13487           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13488                                                    MVT::v16i16, R, ShiftAmt,
13489                                                    DAG);
13490           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13491           // Zero out the leftmost bits.
13492           SmallVector<SDValue, 32> V(32,
13493                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13494                                                      MVT::i8));
13495           return DAG.getNode(ISD::AND, dl, VT, SRL,
13496                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13497         }
13498         if (Op.getOpcode() == ISD::SRA) {
13499           if (ShiftAmt == 7) {
13500             // R s>> 7  ===  R s< 0
13501             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13502             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13503           }
13504
13505           // R s>> a === ((R u>> a) ^ m) - m
13506           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13507           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13508                                                          MVT::i8));
13509           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13510           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13511           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13512           return Res;
13513         }
13514         llvm_unreachable("Unknown shift opcode.");
13515       }
13516     }
13517   }
13518
13519   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13520   if (!Subtarget->is64Bit() &&
13521       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13522       Amt.getOpcode() == ISD::BITCAST &&
13523       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13524     Amt = Amt.getOperand(0);
13525     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13526                      VT.getVectorNumElements();
13527     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13528     uint64_t ShiftAmt = 0;
13529     for (unsigned i = 0; i != Ratio; ++i) {
13530       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13531       if (!C)
13532         return SDValue();
13533       // 6 == Log2(64)
13534       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13535     }
13536     // Check remaining shift amounts.
13537     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13538       uint64_t ShAmt = 0;
13539       for (unsigned j = 0; j != Ratio; ++j) {
13540         ConstantSDNode *C =
13541           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13542         if (!C)
13543           return SDValue();
13544         // 6 == Log2(64)
13545         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13546       }
13547       if (ShAmt != ShiftAmt)
13548         return SDValue();
13549     }
13550     switch (Op.getOpcode()) {
13551     default:
13552       llvm_unreachable("Unknown shift opcode!");
13553     case ISD::SHL:
13554       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13555                                         DAG);
13556     case ISD::SRL:
13557       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13558                                         DAG);
13559     case ISD::SRA:
13560       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13561                                         DAG);
13562     }
13563   }
13564
13565   return SDValue();
13566 }
13567
13568 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13569                                         const X86Subtarget* Subtarget) {
13570   MVT VT = Op.getSimpleValueType();
13571   SDLoc dl(Op);
13572   SDValue R = Op.getOperand(0);
13573   SDValue Amt = Op.getOperand(1);
13574
13575   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13576       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13577       (Subtarget->hasInt256() &&
13578        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13579         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13580        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13581     SDValue BaseShAmt;
13582     EVT EltVT = VT.getVectorElementType();
13583
13584     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13585       unsigned NumElts = VT.getVectorNumElements();
13586       unsigned i, j;
13587       for (i = 0; i != NumElts; ++i) {
13588         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13589           continue;
13590         break;
13591       }
13592       for (j = i; j != NumElts; ++j) {
13593         SDValue Arg = Amt.getOperand(j);
13594         if (Arg.getOpcode() == ISD::UNDEF) continue;
13595         if (Arg != Amt.getOperand(i))
13596           break;
13597       }
13598       if (i != NumElts && j == NumElts)
13599         BaseShAmt = Amt.getOperand(i);
13600     } else {
13601       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13602         Amt = Amt.getOperand(0);
13603       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13604                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13605         SDValue InVec = Amt.getOperand(0);
13606         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13607           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13608           unsigned i = 0;
13609           for (; i != NumElts; ++i) {
13610             SDValue Arg = InVec.getOperand(i);
13611             if (Arg.getOpcode() == ISD::UNDEF) continue;
13612             BaseShAmt = Arg;
13613             break;
13614           }
13615         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13616            if (ConstantSDNode *C =
13617                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13618              unsigned SplatIdx =
13619                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13620              if (C->getZExtValue() == SplatIdx)
13621                BaseShAmt = InVec.getOperand(1);
13622            }
13623         }
13624         if (!BaseShAmt.getNode())
13625           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13626                                   DAG.getIntPtrConstant(0));
13627       }
13628     }
13629
13630     if (BaseShAmt.getNode()) {
13631       if (EltVT.bitsGT(MVT::i32))
13632         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13633       else if (EltVT.bitsLT(MVT::i32))
13634         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13635
13636       switch (Op.getOpcode()) {
13637       default:
13638         llvm_unreachable("Unknown shift opcode!");
13639       case ISD::SHL:
13640         switch (VT.SimpleTy) {
13641         default: return SDValue();
13642         case MVT::v2i64:
13643         case MVT::v4i32:
13644         case MVT::v8i16:
13645         case MVT::v4i64:
13646         case MVT::v8i32:
13647         case MVT::v16i16:
13648         case MVT::v16i32:
13649         case MVT::v8i64:
13650           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13651         }
13652       case ISD::SRA:
13653         switch (VT.SimpleTy) {
13654         default: return SDValue();
13655         case MVT::v4i32:
13656         case MVT::v8i16:
13657         case MVT::v8i32:
13658         case MVT::v16i16:
13659         case MVT::v16i32:
13660         case MVT::v8i64:
13661           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13662         }
13663       case ISD::SRL:
13664         switch (VT.SimpleTy) {
13665         default: return SDValue();
13666         case MVT::v2i64:
13667         case MVT::v4i32:
13668         case MVT::v8i16:
13669         case MVT::v4i64:
13670         case MVT::v8i32:
13671         case MVT::v16i16:
13672         case MVT::v16i32:
13673         case MVT::v8i64:
13674           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13675         }
13676       }
13677     }
13678   }
13679
13680   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13681   if (!Subtarget->is64Bit() &&
13682       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13683       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13684       Amt.getOpcode() == ISD::BITCAST &&
13685       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13686     Amt = Amt.getOperand(0);
13687     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13688                      VT.getVectorNumElements();
13689     std::vector<SDValue> Vals(Ratio);
13690     for (unsigned i = 0; i != Ratio; ++i)
13691       Vals[i] = Amt.getOperand(i);
13692     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13693       for (unsigned j = 0; j != Ratio; ++j)
13694         if (Vals[j] != Amt.getOperand(i + j))
13695           return SDValue();
13696     }
13697     switch (Op.getOpcode()) {
13698     default:
13699       llvm_unreachable("Unknown shift opcode!");
13700     case ISD::SHL:
13701       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13702     case ISD::SRL:
13703       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13704     case ISD::SRA:
13705       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13706     }
13707   }
13708
13709   return SDValue();
13710 }
13711
13712 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13713                           SelectionDAG &DAG) {
13714
13715   MVT VT = Op.getSimpleValueType();
13716   SDLoc dl(Op);
13717   SDValue R = Op.getOperand(0);
13718   SDValue Amt = Op.getOperand(1);
13719   SDValue V;
13720
13721   if (!Subtarget->hasSSE2())
13722     return SDValue();
13723
13724   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13725   if (V.getNode())
13726     return V;
13727
13728   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13729   if (V.getNode())
13730       return V;
13731
13732   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13733     return Op;
13734   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13735   if (Subtarget->hasInt256()) {
13736     if (Op.getOpcode() == ISD::SRL &&
13737         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13738          VT == MVT::v4i64 || VT == MVT::v8i32))
13739       return Op;
13740     if (Op.getOpcode() == ISD::SHL &&
13741         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13742          VT == MVT::v4i64 || VT == MVT::v8i32))
13743       return Op;
13744     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13745       return Op;
13746   }
13747
13748   // If possible, lower this packed shift into a vector multiply instead of
13749   // expanding it into a sequence of scalar shifts.
13750   // Do this only if the vector shift count is a constant build_vector.
13751   if (Op.getOpcode() == ISD::SHL && 
13752       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13753        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13754       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13755     SmallVector<SDValue, 8> Elts;
13756     EVT SVT = VT.getScalarType();
13757     unsigned SVTBits = SVT.getSizeInBits();
13758     const APInt &One = APInt(SVTBits, 1);
13759     unsigned NumElems = VT.getVectorNumElements();
13760
13761     for (unsigned i=0; i !=NumElems; ++i) {
13762       SDValue Op = Amt->getOperand(i);
13763       if (Op->getOpcode() == ISD::UNDEF) {
13764         Elts.push_back(Op);
13765         continue;
13766       }
13767
13768       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13769       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13770       uint64_t ShAmt = C.getZExtValue();
13771       if (ShAmt >= SVTBits) {
13772         Elts.push_back(DAG.getUNDEF(SVT));
13773         continue;
13774       }
13775       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13776     }
13777     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13778     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13779   }
13780
13781   // Lower SHL with variable shift amount.
13782   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13783     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13784
13785     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13786     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13787     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13788     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13789   }
13790
13791   // If possible, lower this shift as a sequence of two shifts by
13792   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13793   // Example:
13794   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13795   //
13796   // Could be rewritten as:
13797   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13798   //
13799   // The advantage is that the two shifts from the example would be
13800   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13801   // the vector shift into four scalar shifts plus four pairs of vector
13802   // insert/extract.
13803   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13804       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13805     unsigned TargetOpcode = X86ISD::MOVSS;
13806     bool CanBeSimplified;
13807     // The splat value for the first packed shift (the 'X' from the example).
13808     SDValue Amt1 = Amt->getOperand(0);
13809     // The splat value for the second packed shift (the 'Y' from the example).
13810     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13811                                         Amt->getOperand(2);
13812
13813     // See if it is possible to replace this node with a sequence of
13814     // two shifts followed by a MOVSS/MOVSD
13815     if (VT == MVT::v4i32) {
13816       // Check if it is legal to use a MOVSS.
13817       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13818                         Amt2 == Amt->getOperand(3);
13819       if (!CanBeSimplified) {
13820         // Otherwise, check if we can still simplify this node using a MOVSD.
13821         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13822                           Amt->getOperand(2) == Amt->getOperand(3);
13823         TargetOpcode = X86ISD::MOVSD;
13824         Amt2 = Amt->getOperand(2);
13825       }
13826     } else {
13827       // Do similar checks for the case where the machine value type
13828       // is MVT::v8i16.
13829       CanBeSimplified = Amt1 == Amt->getOperand(1);
13830       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13831         CanBeSimplified = Amt2 == Amt->getOperand(i);
13832
13833       if (!CanBeSimplified) {
13834         TargetOpcode = X86ISD::MOVSD;
13835         CanBeSimplified = true;
13836         Amt2 = Amt->getOperand(4);
13837         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13838           CanBeSimplified = Amt1 == Amt->getOperand(i);
13839         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13840           CanBeSimplified = Amt2 == Amt->getOperand(j);
13841       }
13842     }
13843     
13844     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13845         isa<ConstantSDNode>(Amt2)) {
13846       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13847       EVT CastVT = MVT::v4i32;
13848       SDValue Splat1 = 
13849         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13850       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13851       SDValue Splat2 = 
13852         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13853       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13854       if (TargetOpcode == X86ISD::MOVSD)
13855         CastVT = MVT::v2i64;
13856       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13857       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13858       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13859                                             BitCast1, DAG);
13860       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13861     }
13862   }
13863
13864   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13865     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13866
13867     // a = a << 5;
13868     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13869     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13870
13871     // Turn 'a' into a mask suitable for VSELECT
13872     SDValue VSelM = DAG.getConstant(0x80, VT);
13873     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13874     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13875
13876     SDValue CM1 = DAG.getConstant(0x0f, VT);
13877     SDValue CM2 = DAG.getConstant(0x3f, VT);
13878
13879     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13880     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13881     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13882     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13883     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13884
13885     // a += a
13886     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13887     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13888     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13889
13890     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13891     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13892     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13893     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13894     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13895
13896     // a += a
13897     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13898     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13899     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13900
13901     // return VSELECT(r, r+r, a);
13902     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13903                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13904     return R;
13905   }
13906
13907   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13908   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13909   // solution better.
13910   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13911     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13912     unsigned ExtOpc =
13913         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13914     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13915     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13916     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13917                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13918     }
13919
13920   // Decompose 256-bit shifts into smaller 128-bit shifts.
13921   if (VT.is256BitVector()) {
13922     unsigned NumElems = VT.getVectorNumElements();
13923     MVT EltVT = VT.getVectorElementType();
13924     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13925
13926     // Extract the two vectors
13927     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13928     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13929
13930     // Recreate the shift amount vectors
13931     SDValue Amt1, Amt2;
13932     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13933       // Constant shift amount
13934       SmallVector<SDValue, 4> Amt1Csts;
13935       SmallVector<SDValue, 4> Amt2Csts;
13936       for (unsigned i = 0; i != NumElems/2; ++i)
13937         Amt1Csts.push_back(Amt->getOperand(i));
13938       for (unsigned i = NumElems/2; i != NumElems; ++i)
13939         Amt2Csts.push_back(Amt->getOperand(i));
13940
13941       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13942       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13943     } else {
13944       // Variable shift amount
13945       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13946       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13947     }
13948
13949     // Issue new vector shifts for the smaller types
13950     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13951     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13952
13953     // Concatenate the result back
13954     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13955   }
13956
13957   return SDValue();
13958 }
13959
13960 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13961   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13962   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13963   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13964   // has only one use.
13965   SDNode *N = Op.getNode();
13966   SDValue LHS = N->getOperand(0);
13967   SDValue RHS = N->getOperand(1);
13968   unsigned BaseOp = 0;
13969   unsigned Cond = 0;
13970   SDLoc DL(Op);
13971   switch (Op.getOpcode()) {
13972   default: llvm_unreachable("Unknown ovf instruction!");
13973   case ISD::SADDO:
13974     // A subtract of one will be selected as a INC. Note that INC doesn't
13975     // set CF, so we can't do this for UADDO.
13976     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13977       if (C->isOne()) {
13978         BaseOp = X86ISD::INC;
13979         Cond = X86::COND_O;
13980         break;
13981       }
13982     BaseOp = X86ISD::ADD;
13983     Cond = X86::COND_O;
13984     break;
13985   case ISD::UADDO:
13986     BaseOp = X86ISD::ADD;
13987     Cond = X86::COND_B;
13988     break;
13989   case ISD::SSUBO:
13990     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13991     // set CF, so we can't do this for USUBO.
13992     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13993       if (C->isOne()) {
13994         BaseOp = X86ISD::DEC;
13995         Cond = X86::COND_O;
13996         break;
13997       }
13998     BaseOp = X86ISD::SUB;
13999     Cond = X86::COND_O;
14000     break;
14001   case ISD::USUBO:
14002     BaseOp = X86ISD::SUB;
14003     Cond = X86::COND_B;
14004     break;
14005   case ISD::SMULO:
14006     BaseOp = X86ISD::SMUL;
14007     Cond = X86::COND_O;
14008     break;
14009   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14010     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14011                                  MVT::i32);
14012     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14013
14014     SDValue SetCC =
14015       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14016                   DAG.getConstant(X86::COND_O, MVT::i32),
14017                   SDValue(Sum.getNode(), 2));
14018
14019     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14020   }
14021   }
14022
14023   // Also sets EFLAGS.
14024   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14025   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14026
14027   SDValue SetCC =
14028     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14029                 DAG.getConstant(Cond, MVT::i32),
14030                 SDValue(Sum.getNode(), 1));
14031
14032   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14033 }
14034
14035 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14036                                                   SelectionDAG &DAG) const {
14037   SDLoc dl(Op);
14038   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14039   MVT VT = Op.getSimpleValueType();
14040
14041   if (!Subtarget->hasSSE2() || !VT.isVector())
14042     return SDValue();
14043
14044   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14045                       ExtraVT.getScalarType().getSizeInBits();
14046
14047   switch (VT.SimpleTy) {
14048     default: return SDValue();
14049     case MVT::v8i32:
14050     case MVT::v16i16:
14051       if (!Subtarget->hasFp256())
14052         return SDValue();
14053       if (!Subtarget->hasInt256()) {
14054         // needs to be split
14055         unsigned NumElems = VT.getVectorNumElements();
14056
14057         // Extract the LHS vectors
14058         SDValue LHS = Op.getOperand(0);
14059         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14060         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14061
14062         MVT EltVT = VT.getVectorElementType();
14063         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14064
14065         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14066         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14067         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14068                                    ExtraNumElems/2);
14069         SDValue Extra = DAG.getValueType(ExtraVT);
14070
14071         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14072         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14073
14074         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14075       }
14076       // fall through
14077     case MVT::v4i32:
14078     case MVT::v8i16: {
14079       SDValue Op0 = Op.getOperand(0);
14080       SDValue Op00 = Op0.getOperand(0);
14081       SDValue Tmp1;
14082       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14083       if (Op0.getOpcode() == ISD::BITCAST &&
14084           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14085         // (sext (vzext x)) -> (vsext x)
14086         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14087         if (Tmp1.getNode()) {
14088           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14089           // This folding is only valid when the in-reg type is a vector of i8,
14090           // i16, or i32.
14091           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14092               ExtraEltVT == MVT::i32) {
14093             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14094             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14095                    "This optimization is invalid without a VZEXT.");
14096             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14097           }
14098           Op0 = Tmp1;
14099         }
14100       }
14101
14102       // If the above didn't work, then just use Shift-Left + Shift-Right.
14103       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14104                                         DAG);
14105       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14106                                         DAG);
14107     }
14108   }
14109 }
14110
14111 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14112                                  SelectionDAG &DAG) {
14113   SDLoc dl(Op);
14114   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14115     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14116   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14117     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14118
14119   // The only fence that needs an instruction is a sequentially-consistent
14120   // cross-thread fence.
14121   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14122     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14123     // no-sse2). There isn't any reason to disable it if the target processor
14124     // supports it.
14125     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14126       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14127
14128     SDValue Chain = Op.getOperand(0);
14129     SDValue Zero = DAG.getConstant(0, MVT::i32);
14130     SDValue Ops[] = {
14131       DAG.getRegister(X86::ESP, MVT::i32), // Base
14132       DAG.getTargetConstant(1, MVT::i8),   // Scale
14133       DAG.getRegister(0, MVT::i32),        // Index
14134       DAG.getTargetConstant(0, MVT::i32),  // Disp
14135       DAG.getRegister(0, MVT::i32),        // Segment.
14136       Zero,
14137       Chain
14138     };
14139     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14140     return SDValue(Res, 0);
14141   }
14142
14143   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14144   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14145 }
14146
14147 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14148                              SelectionDAG &DAG) {
14149   MVT T = Op.getSimpleValueType();
14150   SDLoc DL(Op);
14151   unsigned Reg = 0;
14152   unsigned size = 0;
14153   switch(T.SimpleTy) {
14154   default: llvm_unreachable("Invalid value type!");
14155   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14156   case MVT::i16: Reg = X86::AX;  size = 2; break;
14157   case MVT::i32: Reg = X86::EAX; size = 4; break;
14158   case MVT::i64:
14159     assert(Subtarget->is64Bit() && "Node not type legal!");
14160     Reg = X86::RAX; size = 8;
14161     break;
14162   }
14163   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14164                                     Op.getOperand(2), SDValue());
14165   SDValue Ops[] = { cpIn.getValue(0),
14166                     Op.getOperand(1),
14167                     Op.getOperand(3),
14168                     DAG.getTargetConstant(size, MVT::i8),
14169                     cpIn.getValue(1) };
14170   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14171   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14172   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14173                                            Ops, T, MMO);
14174   SDValue cpOut =
14175     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14176   return cpOut;
14177 }
14178
14179 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14180                             SelectionDAG &DAG) {
14181   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14182   MVT DstVT = Op.getSimpleValueType();
14183
14184   if (SrcVT == MVT::v2i32) {
14185     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14186     if (DstVT != MVT::f64)
14187       // This conversion needs to be expanded.
14188       return SDValue();
14189
14190     SDLoc dl(Op);
14191     SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14192                                Op->getOperand(0), DAG.getIntPtrConstant(0));
14193     SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14194                                Op->getOperand(0), DAG.getIntPtrConstant(1));
14195     SDValue Elts[] = {Elt0, Elt1, Elt0, Elt0};
14196     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Elts);
14197     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14198     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14199                        DAG.getIntPtrConstant(0));
14200   }
14201
14202   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14203          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14204   assert((DstVT == MVT::i64 ||
14205           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14206          "Unexpected custom BITCAST");
14207   // i64 <=> MMX conversions are Legal.
14208   if (SrcVT==MVT::i64 && DstVT.isVector())
14209     return Op;
14210   if (DstVT==MVT::i64 && SrcVT.isVector())
14211     return Op;
14212   // MMX <=> MMX conversions are Legal.
14213   if (SrcVT.isVector() && DstVT.isVector())
14214     return Op;
14215   // All other conversions need to be expanded.
14216   return SDValue();
14217 }
14218
14219 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14220   SDNode *Node = Op.getNode();
14221   SDLoc dl(Node);
14222   EVT T = Node->getValueType(0);
14223   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14224                               DAG.getConstant(0, T), Node->getOperand(2));
14225   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14226                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14227                        Node->getOperand(0),
14228                        Node->getOperand(1), negOp,
14229                        cast<AtomicSDNode>(Node)->getMemOperand(),
14230                        cast<AtomicSDNode>(Node)->getOrdering(),
14231                        cast<AtomicSDNode>(Node)->getSynchScope());
14232 }
14233
14234 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14235   SDNode *Node = Op.getNode();
14236   SDLoc dl(Node);
14237   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14238
14239   // Convert seq_cst store -> xchg
14240   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14241   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14242   //        (The only way to get a 16-byte store is cmpxchg16b)
14243   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14244   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14245       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14246     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14247                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14248                                  Node->getOperand(0),
14249                                  Node->getOperand(1), Node->getOperand(2),
14250                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14251                                  cast<AtomicSDNode>(Node)->getOrdering(),
14252                                  cast<AtomicSDNode>(Node)->getSynchScope());
14253     return Swap.getValue(1);
14254   }
14255   // Other atomic stores have a simple pattern.
14256   return Op;
14257 }
14258
14259 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14260   EVT VT = Op.getNode()->getSimpleValueType(0);
14261
14262   // Let legalize expand this if it isn't a legal type yet.
14263   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14264     return SDValue();
14265
14266   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14267
14268   unsigned Opc;
14269   bool ExtraOp = false;
14270   switch (Op.getOpcode()) {
14271   default: llvm_unreachable("Invalid code");
14272   case ISD::ADDC: Opc = X86ISD::ADD; break;
14273   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14274   case ISD::SUBC: Opc = X86ISD::SUB; break;
14275   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14276   }
14277
14278   if (!ExtraOp)
14279     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14280                        Op.getOperand(1));
14281   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14282                      Op.getOperand(1), Op.getOperand(2));
14283 }
14284
14285 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14286                             SelectionDAG &DAG) {
14287   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14288
14289   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14290   // which returns the values as { float, float } (in XMM0) or
14291   // { double, double } (which is returned in XMM0, XMM1).
14292   SDLoc dl(Op);
14293   SDValue Arg = Op.getOperand(0);
14294   EVT ArgVT = Arg.getValueType();
14295   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14296
14297   TargetLowering::ArgListTy Args;
14298   TargetLowering::ArgListEntry Entry;
14299
14300   Entry.Node = Arg;
14301   Entry.Ty = ArgTy;
14302   Entry.isSExt = false;
14303   Entry.isZExt = false;
14304   Args.push_back(Entry);
14305
14306   bool isF64 = ArgVT == MVT::f64;
14307   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14308   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14309   // the results are returned via SRet in memory.
14310   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14312   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14313
14314   Type *RetTy = isF64
14315     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14316     : (Type*)VectorType::get(ArgTy, 4);
14317   TargetLowering::
14318     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14319                          false, false, false, false, 0,
14320                          CallingConv::C, /*isTaillCall=*/false,
14321                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14322                          Callee, Args, DAG, dl);
14323   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14324
14325   if (isF64)
14326     // Returned in xmm0 and xmm1.
14327     return CallResult.first;
14328
14329   // Returned in bits 0:31 and 32:64 xmm0.
14330   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14331                                CallResult.first, DAG.getIntPtrConstant(0));
14332   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14333                                CallResult.first, DAG.getIntPtrConstant(1));
14334   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14335   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14336 }
14337
14338 /// LowerOperation - Provide custom lowering hooks for some operations.
14339 ///
14340 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14341   switch (Op.getOpcode()) {
14342   default: llvm_unreachable("Should not custom lower this!");
14343   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14344   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14345   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14346   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14347   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14348   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14349   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14350   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14351   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14352   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14353   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14354   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14355   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14356   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14357   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14358   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14359   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14360   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14361   case ISD::SHL_PARTS:
14362   case ISD::SRA_PARTS:
14363   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14364   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14365   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14366   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14367   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14368   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14369   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14370   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14371   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14372   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14373   case ISD::FABS:               return LowerFABS(Op, DAG);
14374   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14375   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14376   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14377   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14378   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14379   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14380   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14381   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14382   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14383   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14384   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14385   case ISD::INTRINSIC_VOID:
14386   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14387   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14388   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14389   case ISD::FRAME_TO_ARGS_OFFSET:
14390                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14391   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14392   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14393   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14394   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14395   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14396   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14397   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14398   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14399   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14400   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14401   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14402   case ISD::UMUL_LOHI:
14403   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14404   case ISD::SRA:
14405   case ISD::SRL:
14406   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14407   case ISD::SADDO:
14408   case ISD::UADDO:
14409   case ISD::SSUBO:
14410   case ISD::USUBO:
14411   case ISD::SMULO:
14412   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14413   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14414   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14415   case ISD::ADDC:
14416   case ISD::ADDE:
14417   case ISD::SUBC:
14418   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14419   case ISD::ADD:                return LowerADD(Op, DAG);
14420   case ISD::SUB:                return LowerSUB(Op, DAG);
14421   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14422   }
14423 }
14424
14425 static void ReplaceATOMIC_LOAD(SDNode *Node,
14426                                   SmallVectorImpl<SDValue> &Results,
14427                                   SelectionDAG &DAG) {
14428   SDLoc dl(Node);
14429   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14430
14431   // Convert wide load -> cmpxchg8b/cmpxchg16b
14432   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14433   //        (The only way to get a 16-byte load is cmpxchg16b)
14434   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14435   SDValue Zero = DAG.getConstant(0, VT);
14436   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14437                                Node->getOperand(0),
14438                                Node->getOperand(1), Zero, Zero,
14439                                cast<AtomicSDNode>(Node)->getMemOperand(),
14440                                cast<AtomicSDNode>(Node)->getOrdering(),
14441                                cast<AtomicSDNode>(Node)->getOrdering(),
14442                                cast<AtomicSDNode>(Node)->getSynchScope());
14443   Results.push_back(Swap.getValue(0));
14444   Results.push_back(Swap.getValue(1));
14445 }
14446
14447 static void
14448 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14449                         SelectionDAG &DAG, unsigned NewOp) {
14450   SDLoc dl(Node);
14451   assert (Node->getValueType(0) == MVT::i64 &&
14452           "Only know how to expand i64 atomics");
14453
14454   SDValue Chain = Node->getOperand(0);
14455   SDValue In1 = Node->getOperand(1);
14456   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14457                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14458   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14459                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14460   SDValue Ops[] = { Chain, In1, In2L, In2H };
14461   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14462   SDValue Result =
14463     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14464                             cast<MemSDNode>(Node)->getMemOperand());
14465   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14466   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14467   Results.push_back(Result.getValue(2));
14468 }
14469
14470 /// ReplaceNodeResults - Replace a node with an illegal result type
14471 /// with a new node built out of custom code.
14472 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14473                                            SmallVectorImpl<SDValue>&Results,
14474                                            SelectionDAG &DAG) const {
14475   SDLoc dl(N);
14476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14477   switch (N->getOpcode()) {
14478   default:
14479     llvm_unreachable("Do not know how to custom type legalize this operation!");
14480   case ISD::SIGN_EXTEND_INREG:
14481   case ISD::ADDC:
14482   case ISD::ADDE:
14483   case ISD::SUBC:
14484   case ISD::SUBE:
14485     // We don't want to expand or promote these.
14486     return;
14487   case ISD::SDIV:
14488   case ISD::UDIV:
14489   case ISD::SREM:
14490   case ISD::UREM:
14491   case ISD::SDIVREM:
14492   case ISD::UDIVREM: {
14493     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14494     Results.push_back(V);
14495     return;
14496   }
14497   case ISD::FP_TO_SINT:
14498   case ISD::FP_TO_UINT: {
14499     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14500
14501     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14502       return;
14503
14504     std::pair<SDValue,SDValue> Vals =
14505         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14506     SDValue FIST = Vals.first, StackSlot = Vals.second;
14507     if (FIST.getNode()) {
14508       EVT VT = N->getValueType(0);
14509       // Return a load from the stack slot.
14510       if (StackSlot.getNode())
14511         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14512                                       MachinePointerInfo(),
14513                                       false, false, false, 0));
14514       else
14515         Results.push_back(FIST);
14516     }
14517     return;
14518   }
14519   case ISD::UINT_TO_FP: {
14520     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14521     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14522         N->getValueType(0) != MVT::v2f32)
14523       return;
14524     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14525                                  N->getOperand(0));
14526     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14527                                      MVT::f64);
14528     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14529     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14530                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14531     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14532     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14533     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14534     return;
14535   }
14536   case ISD::FP_ROUND: {
14537     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14538         return;
14539     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14540     Results.push_back(V);
14541     return;
14542   }
14543   case ISD::INTRINSIC_W_CHAIN: {
14544     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14545     switch (IntNo) {
14546     default : llvm_unreachable("Do not know how to custom type "
14547                                "legalize this intrinsic operation!");
14548     case Intrinsic::x86_rdtsc:
14549       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14550                                      Results);
14551     case Intrinsic::x86_rdtscp:
14552       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14553                                      Results);
14554     }
14555   }
14556   case ISD::READCYCLECOUNTER: {
14557     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14558                                    Results);
14559   }
14560   case ISD::ATOMIC_CMP_SWAP: {
14561     EVT T = N->getValueType(0);
14562     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14563     bool Regs64bit = T == MVT::i128;
14564     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14565     SDValue cpInL, cpInH;
14566     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14567                         DAG.getConstant(0, HalfT));
14568     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14569                         DAG.getConstant(1, HalfT));
14570     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14571                              Regs64bit ? X86::RAX : X86::EAX,
14572                              cpInL, SDValue());
14573     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14574                              Regs64bit ? X86::RDX : X86::EDX,
14575                              cpInH, cpInL.getValue(1));
14576     SDValue swapInL, swapInH;
14577     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14578                           DAG.getConstant(0, HalfT));
14579     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14580                           DAG.getConstant(1, HalfT));
14581     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14582                                Regs64bit ? X86::RBX : X86::EBX,
14583                                swapInL, cpInH.getValue(1));
14584     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14585                                Regs64bit ? X86::RCX : X86::ECX,
14586                                swapInH, swapInL.getValue(1));
14587     SDValue Ops[] = { swapInH.getValue(0),
14588                       N->getOperand(1),
14589                       swapInH.getValue(1) };
14590     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14591     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14592     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14593                                   X86ISD::LCMPXCHG8_DAG;
14594     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14595     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14596                                         Regs64bit ? X86::RAX : X86::EAX,
14597                                         HalfT, Result.getValue(1));
14598     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14599                                         Regs64bit ? X86::RDX : X86::EDX,
14600                                         HalfT, cpOutL.getValue(2));
14601     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14602     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14603     Results.push_back(cpOutH.getValue(1));
14604     return;
14605   }
14606   case ISD::ATOMIC_LOAD_ADD:
14607   case ISD::ATOMIC_LOAD_AND:
14608   case ISD::ATOMIC_LOAD_NAND:
14609   case ISD::ATOMIC_LOAD_OR:
14610   case ISD::ATOMIC_LOAD_SUB:
14611   case ISD::ATOMIC_LOAD_XOR:
14612   case ISD::ATOMIC_LOAD_MAX:
14613   case ISD::ATOMIC_LOAD_MIN:
14614   case ISD::ATOMIC_LOAD_UMAX:
14615   case ISD::ATOMIC_LOAD_UMIN:
14616   case ISD::ATOMIC_SWAP: {
14617     unsigned Opc;
14618     switch (N->getOpcode()) {
14619     default: llvm_unreachable("Unexpected opcode");
14620     case ISD::ATOMIC_LOAD_ADD:
14621       Opc = X86ISD::ATOMADD64_DAG;
14622       break;
14623     case ISD::ATOMIC_LOAD_AND:
14624       Opc = X86ISD::ATOMAND64_DAG;
14625       break;
14626     case ISD::ATOMIC_LOAD_NAND:
14627       Opc = X86ISD::ATOMNAND64_DAG;
14628       break;
14629     case ISD::ATOMIC_LOAD_OR:
14630       Opc = X86ISD::ATOMOR64_DAG;
14631       break;
14632     case ISD::ATOMIC_LOAD_SUB:
14633       Opc = X86ISD::ATOMSUB64_DAG;
14634       break;
14635     case ISD::ATOMIC_LOAD_XOR:
14636       Opc = X86ISD::ATOMXOR64_DAG;
14637       break;
14638     case ISD::ATOMIC_LOAD_MAX:
14639       Opc = X86ISD::ATOMMAX64_DAG;
14640       break;
14641     case ISD::ATOMIC_LOAD_MIN:
14642       Opc = X86ISD::ATOMMIN64_DAG;
14643       break;
14644     case ISD::ATOMIC_LOAD_UMAX:
14645       Opc = X86ISD::ATOMUMAX64_DAG;
14646       break;
14647     case ISD::ATOMIC_LOAD_UMIN:
14648       Opc = X86ISD::ATOMUMIN64_DAG;
14649       break;
14650     case ISD::ATOMIC_SWAP:
14651       Opc = X86ISD::ATOMSWAP64_DAG;
14652       break;
14653     }
14654     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14655     return;
14656   }
14657   case ISD::ATOMIC_LOAD: {
14658     ReplaceATOMIC_LOAD(N, Results, DAG);
14659     return;
14660   }
14661   case ISD::BITCAST: {
14662     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14663     EVT DstVT = N->getValueType(0);
14664     EVT SrcVT = N->getOperand(0)->getValueType(0);
14665
14666     if (SrcVT == MVT::f64 && DstVT == MVT::v2i32) {
14667       SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14668                                      MVT::v2f64, N->getOperand(0));
14669       SDValue ToV4I32 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Expanded);
14670       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14671                                  ToV4I32, DAG.getIntPtrConstant(0));
14672       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
14673                                  ToV4I32, DAG.getIntPtrConstant(1));
14674       SDValue Elts[] = {Elt0, Elt1};
14675       Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Elts));
14676     }
14677   }
14678   }
14679 }
14680
14681 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14682   switch (Opcode) {
14683   default: return nullptr;
14684   case X86ISD::BSF:                return "X86ISD::BSF";
14685   case X86ISD::BSR:                return "X86ISD::BSR";
14686   case X86ISD::SHLD:               return "X86ISD::SHLD";
14687   case X86ISD::SHRD:               return "X86ISD::SHRD";
14688   case X86ISD::FAND:               return "X86ISD::FAND";
14689   case X86ISD::FANDN:              return "X86ISD::FANDN";
14690   case X86ISD::FOR:                return "X86ISD::FOR";
14691   case X86ISD::FXOR:               return "X86ISD::FXOR";
14692   case X86ISD::FSRL:               return "X86ISD::FSRL";
14693   case X86ISD::FILD:               return "X86ISD::FILD";
14694   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14695   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14696   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14697   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14698   case X86ISD::FLD:                return "X86ISD::FLD";
14699   case X86ISD::FST:                return "X86ISD::FST";
14700   case X86ISD::CALL:               return "X86ISD::CALL";
14701   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14702   case X86ISD::BT:                 return "X86ISD::BT";
14703   case X86ISD::CMP:                return "X86ISD::CMP";
14704   case X86ISD::COMI:               return "X86ISD::COMI";
14705   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14706   case X86ISD::CMPM:               return "X86ISD::CMPM";
14707   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14708   case X86ISD::SETCC:              return "X86ISD::SETCC";
14709   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14710   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14711   case X86ISD::CMOV:               return "X86ISD::CMOV";
14712   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14713   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14714   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14715   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14716   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14717   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14718   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14719   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14720   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14721   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14722   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14723   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14724   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14725   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14726   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14727   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14728   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14729   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14730   case X86ISD::HADD:               return "X86ISD::HADD";
14731   case X86ISD::HSUB:               return "X86ISD::HSUB";
14732   case X86ISD::FHADD:              return "X86ISD::FHADD";
14733   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14734   case X86ISD::UMAX:               return "X86ISD::UMAX";
14735   case X86ISD::UMIN:               return "X86ISD::UMIN";
14736   case X86ISD::SMAX:               return "X86ISD::SMAX";
14737   case X86ISD::SMIN:               return "X86ISD::SMIN";
14738   case X86ISD::FMAX:               return "X86ISD::FMAX";
14739   case X86ISD::FMIN:               return "X86ISD::FMIN";
14740   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14741   case X86ISD::FMINC:              return "X86ISD::FMINC";
14742   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14743   case X86ISD::FRCP:               return "X86ISD::FRCP";
14744   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14745   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14746   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14747   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14748   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14749   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14750   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14751   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14752   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14753   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14754   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14755   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14756   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14757   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14758   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14759   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14760   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14761   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14762   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14763   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14764   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14765   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14766   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14767   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14768   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14769   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14770   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14771   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14772   case X86ISD::VSHL:               return "X86ISD::VSHL";
14773   case X86ISD::VSRL:               return "X86ISD::VSRL";
14774   case X86ISD::VSRA:               return "X86ISD::VSRA";
14775   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14776   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14777   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14778   case X86ISD::CMPP:               return "X86ISD::CMPP";
14779   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14780   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14781   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14782   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14783   case X86ISD::ADD:                return "X86ISD::ADD";
14784   case X86ISD::SUB:                return "X86ISD::SUB";
14785   case X86ISD::ADC:                return "X86ISD::ADC";
14786   case X86ISD::SBB:                return "X86ISD::SBB";
14787   case X86ISD::SMUL:               return "X86ISD::SMUL";
14788   case X86ISD::UMUL:               return "X86ISD::UMUL";
14789   case X86ISD::INC:                return "X86ISD::INC";
14790   case X86ISD::DEC:                return "X86ISD::DEC";
14791   case X86ISD::OR:                 return "X86ISD::OR";
14792   case X86ISD::XOR:                return "X86ISD::XOR";
14793   case X86ISD::AND:                return "X86ISD::AND";
14794   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14795   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14796   case X86ISD::PTEST:              return "X86ISD::PTEST";
14797   case X86ISD::TESTP:              return "X86ISD::TESTP";
14798   case X86ISD::TESTM:              return "X86ISD::TESTM";
14799   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14800   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14801   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14802   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14803   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14804   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14805   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14806   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14807   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14808   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14809   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14810   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14811   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14812   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14813   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14814   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14815   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14816   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14817   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14818   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14819   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14820   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14821   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14822   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14823   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14824   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14825   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14826   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14827   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14828   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14829   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14830   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14831   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14832   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14833   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14834   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14835   case X86ISD::SAHF:               return "X86ISD::SAHF";
14836   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14837   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14838   case X86ISD::FMADD:              return "X86ISD::FMADD";
14839   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14840   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14841   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14842   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14843   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14844   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14845   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14846   case X86ISD::XTEST:              return "X86ISD::XTEST";
14847   }
14848 }
14849
14850 // isLegalAddressingMode - Return true if the addressing mode represented
14851 // by AM is legal for this target, for a load/store of the specified type.
14852 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14853                                               Type *Ty) const {
14854   // X86 supports extremely general addressing modes.
14855   CodeModel::Model M = getTargetMachine().getCodeModel();
14856   Reloc::Model R = getTargetMachine().getRelocationModel();
14857
14858   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14859   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14860     return false;
14861
14862   if (AM.BaseGV) {
14863     unsigned GVFlags =
14864       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14865
14866     // If a reference to this global requires an extra load, we can't fold it.
14867     if (isGlobalStubReference(GVFlags))
14868       return false;
14869
14870     // If BaseGV requires a register for the PIC base, we cannot also have a
14871     // BaseReg specified.
14872     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14873       return false;
14874
14875     // If lower 4G is not available, then we must use rip-relative addressing.
14876     if ((M != CodeModel::Small || R != Reloc::Static) &&
14877         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14878       return false;
14879   }
14880
14881   switch (AM.Scale) {
14882   case 0:
14883   case 1:
14884   case 2:
14885   case 4:
14886   case 8:
14887     // These scales always work.
14888     break;
14889   case 3:
14890   case 5:
14891   case 9:
14892     // These scales are formed with basereg+scalereg.  Only accept if there is
14893     // no basereg yet.
14894     if (AM.HasBaseReg)
14895       return false;
14896     break;
14897   default:  // Other stuff never works.
14898     return false;
14899   }
14900
14901   return true;
14902 }
14903
14904 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14905   unsigned Bits = Ty->getScalarSizeInBits();
14906
14907   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14908   // particularly cheaper than those without.
14909   if (Bits == 8)
14910     return false;
14911
14912   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14913   // variable shifts just as cheap as scalar ones.
14914   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14915     return false;
14916
14917   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14918   // fully general vector.
14919   return true;
14920 }
14921
14922 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14923   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14924     return false;
14925   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14926   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14927   return NumBits1 > NumBits2;
14928 }
14929
14930 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14931   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14932     return false;
14933
14934   if (!isTypeLegal(EVT::getEVT(Ty1)))
14935     return false;
14936
14937   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14938
14939   // Assuming the caller doesn't have a zeroext or signext return parameter,
14940   // truncation all the way down to i1 is valid.
14941   return true;
14942 }
14943
14944 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14945   return isInt<32>(Imm);
14946 }
14947
14948 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14949   // Can also use sub to handle negated immediates.
14950   return isInt<32>(Imm);
14951 }
14952
14953 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14954   if (!VT1.isInteger() || !VT2.isInteger())
14955     return false;
14956   unsigned NumBits1 = VT1.getSizeInBits();
14957   unsigned NumBits2 = VT2.getSizeInBits();
14958   return NumBits1 > NumBits2;
14959 }
14960
14961 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14962   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14963   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14964 }
14965
14966 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14967   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14968   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14969 }
14970
14971 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14972   EVT VT1 = Val.getValueType();
14973   if (isZExtFree(VT1, VT2))
14974     return true;
14975
14976   if (Val.getOpcode() != ISD::LOAD)
14977     return false;
14978
14979   if (!VT1.isSimple() || !VT1.isInteger() ||
14980       !VT2.isSimple() || !VT2.isInteger())
14981     return false;
14982
14983   switch (VT1.getSimpleVT().SimpleTy) {
14984   default: break;
14985   case MVT::i8:
14986   case MVT::i16:
14987   case MVT::i32:
14988     // X86 has 8, 16, and 32-bit zero-extending loads.
14989     return true;
14990   }
14991
14992   return false;
14993 }
14994
14995 bool
14996 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14997   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14998     return false;
14999
15000   VT = VT.getScalarType();
15001
15002   if (!VT.isSimple())
15003     return false;
15004
15005   switch (VT.getSimpleVT().SimpleTy) {
15006   case MVT::f32:
15007   case MVT::f64:
15008     return true;
15009   default:
15010     break;
15011   }
15012
15013   return false;
15014 }
15015
15016 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15017   // i16 instructions are longer (0x66 prefix) and potentially slower.
15018   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15019 }
15020
15021 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15022 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15023 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15024 /// are assumed to be legal.
15025 bool
15026 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15027                                       EVT VT) const {
15028   if (!VT.isSimple())
15029     return false;
15030
15031   MVT SVT = VT.getSimpleVT();
15032
15033   // Very little shuffling can be done for 64-bit vectors right now.
15034   if (VT.getSizeInBits() == 64)
15035     return false;
15036
15037   // FIXME: pshufb, blends, shifts.
15038   return (SVT.getVectorNumElements() == 2 ||
15039           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15040           isMOVLMask(M, SVT) ||
15041           isSHUFPMask(M, SVT) ||
15042           isPSHUFDMask(M, SVT) ||
15043           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15044           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15045           isPALIGNRMask(M, SVT, Subtarget) ||
15046           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15047           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15048           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15049           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
15050 }
15051
15052 bool
15053 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15054                                           EVT VT) const {
15055   if (!VT.isSimple())
15056     return false;
15057
15058   MVT SVT = VT.getSimpleVT();
15059   unsigned NumElts = SVT.getVectorNumElements();
15060   // FIXME: This collection of masks seems suspect.
15061   if (NumElts == 2)
15062     return true;
15063   if (NumElts == 4 && SVT.is128BitVector()) {
15064     return (isMOVLMask(Mask, SVT)  ||
15065             isCommutedMOVLMask(Mask, SVT, true) ||
15066             isSHUFPMask(Mask, SVT) ||
15067             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15068   }
15069   return false;
15070 }
15071
15072 //===----------------------------------------------------------------------===//
15073 //                           X86 Scheduler Hooks
15074 //===----------------------------------------------------------------------===//
15075
15076 /// Utility function to emit xbegin specifying the start of an RTM region.
15077 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15078                                      const TargetInstrInfo *TII) {
15079   DebugLoc DL = MI->getDebugLoc();
15080
15081   const BasicBlock *BB = MBB->getBasicBlock();
15082   MachineFunction::iterator I = MBB;
15083   ++I;
15084
15085   // For the v = xbegin(), we generate
15086   //
15087   // thisMBB:
15088   //  xbegin sinkMBB
15089   //
15090   // mainMBB:
15091   //  eax = -1
15092   //
15093   // sinkMBB:
15094   //  v = eax
15095
15096   MachineBasicBlock *thisMBB = MBB;
15097   MachineFunction *MF = MBB->getParent();
15098   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15099   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15100   MF->insert(I, mainMBB);
15101   MF->insert(I, sinkMBB);
15102
15103   // Transfer the remainder of BB and its successor edges to sinkMBB.
15104   sinkMBB->splice(sinkMBB->begin(), MBB,
15105                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15106   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15107
15108   // thisMBB:
15109   //  xbegin sinkMBB
15110   //  # fallthrough to mainMBB
15111   //  # abortion to sinkMBB
15112   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15113   thisMBB->addSuccessor(mainMBB);
15114   thisMBB->addSuccessor(sinkMBB);
15115
15116   // mainMBB:
15117   //  EAX = -1
15118   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15119   mainMBB->addSuccessor(sinkMBB);
15120
15121   // sinkMBB:
15122   // EAX is live into the sinkMBB
15123   sinkMBB->addLiveIn(X86::EAX);
15124   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15125           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15126     .addReg(X86::EAX);
15127
15128   MI->eraseFromParent();
15129   return sinkMBB;
15130 }
15131
15132 // Get CMPXCHG opcode for the specified data type.
15133 static unsigned getCmpXChgOpcode(EVT VT) {
15134   switch (VT.getSimpleVT().SimpleTy) {
15135   case MVT::i8:  return X86::LCMPXCHG8;
15136   case MVT::i16: return X86::LCMPXCHG16;
15137   case MVT::i32: return X86::LCMPXCHG32;
15138   case MVT::i64: return X86::LCMPXCHG64;
15139   default:
15140     break;
15141   }
15142   llvm_unreachable("Invalid operand size!");
15143 }
15144
15145 // Get LOAD opcode for the specified data type.
15146 static unsigned getLoadOpcode(EVT VT) {
15147   switch (VT.getSimpleVT().SimpleTy) {
15148   case MVT::i8:  return X86::MOV8rm;
15149   case MVT::i16: return X86::MOV16rm;
15150   case MVT::i32: return X86::MOV32rm;
15151   case MVT::i64: return X86::MOV64rm;
15152   default:
15153     break;
15154   }
15155   llvm_unreachable("Invalid operand size!");
15156 }
15157
15158 // Get opcode of the non-atomic one from the specified atomic instruction.
15159 static unsigned getNonAtomicOpcode(unsigned Opc) {
15160   switch (Opc) {
15161   case X86::ATOMAND8:  return X86::AND8rr;
15162   case X86::ATOMAND16: return X86::AND16rr;
15163   case X86::ATOMAND32: return X86::AND32rr;
15164   case X86::ATOMAND64: return X86::AND64rr;
15165   case X86::ATOMOR8:   return X86::OR8rr;
15166   case X86::ATOMOR16:  return X86::OR16rr;
15167   case X86::ATOMOR32:  return X86::OR32rr;
15168   case X86::ATOMOR64:  return X86::OR64rr;
15169   case X86::ATOMXOR8:  return X86::XOR8rr;
15170   case X86::ATOMXOR16: return X86::XOR16rr;
15171   case X86::ATOMXOR32: return X86::XOR32rr;
15172   case X86::ATOMXOR64: return X86::XOR64rr;
15173   }
15174   llvm_unreachable("Unhandled atomic-load-op opcode!");
15175 }
15176
15177 // Get opcode of the non-atomic one from the specified atomic instruction with
15178 // extra opcode.
15179 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15180                                                unsigned &ExtraOpc) {
15181   switch (Opc) {
15182   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15183   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15184   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15185   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15186   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15187   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15188   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15189   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15190   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15191   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15192   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15193   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15194   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15195   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15196   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15197   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15198   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15199   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15200   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15201   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15202   }
15203   llvm_unreachable("Unhandled atomic-load-op opcode!");
15204 }
15205
15206 // Get opcode of the non-atomic one from the specified atomic instruction for
15207 // 64-bit data type on 32-bit target.
15208 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15209   switch (Opc) {
15210   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15211   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15212   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15213   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15214   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15215   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15216   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15217   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15218   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15219   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15220   }
15221   llvm_unreachable("Unhandled atomic-load-op opcode!");
15222 }
15223
15224 // Get opcode of the non-atomic one from the specified atomic instruction for
15225 // 64-bit data type on 32-bit target with extra opcode.
15226 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15227                                                    unsigned &HiOpc,
15228                                                    unsigned &ExtraOpc) {
15229   switch (Opc) {
15230   case X86::ATOMNAND6432:
15231     ExtraOpc = X86::NOT32r;
15232     HiOpc = X86::AND32rr;
15233     return X86::AND32rr;
15234   }
15235   llvm_unreachable("Unhandled atomic-load-op opcode!");
15236 }
15237
15238 // Get pseudo CMOV opcode from the specified data type.
15239 static unsigned getPseudoCMOVOpc(EVT VT) {
15240   switch (VT.getSimpleVT().SimpleTy) {
15241   case MVT::i8:  return X86::CMOV_GR8;
15242   case MVT::i16: return X86::CMOV_GR16;
15243   case MVT::i32: return X86::CMOV_GR32;
15244   default:
15245     break;
15246   }
15247   llvm_unreachable("Unknown CMOV opcode!");
15248 }
15249
15250 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15251 // They will be translated into a spin-loop or compare-exchange loop from
15252 //
15253 //    ...
15254 //    dst = atomic-fetch-op MI.addr, MI.val
15255 //    ...
15256 //
15257 // to
15258 //
15259 //    ...
15260 //    t1 = LOAD MI.addr
15261 // loop:
15262 //    t4 = phi(t1, t3 / loop)
15263 //    t2 = OP MI.val, t4
15264 //    EAX = t4
15265 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15266 //    t3 = EAX
15267 //    JNE loop
15268 // sink:
15269 //    dst = t3
15270 //    ...
15271 MachineBasicBlock *
15272 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15273                                        MachineBasicBlock *MBB) const {
15274   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15275   DebugLoc DL = MI->getDebugLoc();
15276
15277   MachineFunction *MF = MBB->getParent();
15278   MachineRegisterInfo &MRI = MF->getRegInfo();
15279
15280   const BasicBlock *BB = MBB->getBasicBlock();
15281   MachineFunction::iterator I = MBB;
15282   ++I;
15283
15284   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15285          "Unexpected number of operands");
15286
15287   assert(MI->hasOneMemOperand() &&
15288          "Expected atomic-load-op to have one memoperand");
15289
15290   // Memory Reference
15291   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15292   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15293
15294   unsigned DstReg, SrcReg;
15295   unsigned MemOpndSlot;
15296
15297   unsigned CurOp = 0;
15298
15299   DstReg = MI->getOperand(CurOp++).getReg();
15300   MemOpndSlot = CurOp;
15301   CurOp += X86::AddrNumOperands;
15302   SrcReg = MI->getOperand(CurOp++).getReg();
15303
15304   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15305   MVT::SimpleValueType VT = *RC->vt_begin();
15306   unsigned t1 = MRI.createVirtualRegister(RC);
15307   unsigned t2 = MRI.createVirtualRegister(RC);
15308   unsigned t3 = MRI.createVirtualRegister(RC);
15309   unsigned t4 = MRI.createVirtualRegister(RC);
15310   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15311
15312   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15313   unsigned LOADOpc = getLoadOpcode(VT);
15314
15315   // For the atomic load-arith operator, we generate
15316   //
15317   //  thisMBB:
15318   //    t1 = LOAD [MI.addr]
15319   //  mainMBB:
15320   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15321   //    t1 = OP MI.val, EAX
15322   //    EAX = t4
15323   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15324   //    t3 = EAX
15325   //    JNE mainMBB
15326   //  sinkMBB:
15327   //    dst = t3
15328
15329   MachineBasicBlock *thisMBB = MBB;
15330   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15331   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15332   MF->insert(I, mainMBB);
15333   MF->insert(I, sinkMBB);
15334
15335   MachineInstrBuilder MIB;
15336
15337   // Transfer the remainder of BB and its successor edges to sinkMBB.
15338   sinkMBB->splice(sinkMBB->begin(), MBB,
15339                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15340   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15341
15342   // thisMBB:
15343   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15344   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15345     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15346     if (NewMO.isReg())
15347       NewMO.setIsKill(false);
15348     MIB.addOperand(NewMO);
15349   }
15350   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15351     unsigned flags = (*MMOI)->getFlags();
15352     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15353     MachineMemOperand *MMO =
15354       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15355                                (*MMOI)->getSize(),
15356                                (*MMOI)->getBaseAlignment(),
15357                                (*MMOI)->getTBAAInfo(),
15358                                (*MMOI)->getRanges());
15359     MIB.addMemOperand(MMO);
15360   }
15361
15362   thisMBB->addSuccessor(mainMBB);
15363
15364   // mainMBB:
15365   MachineBasicBlock *origMainMBB = mainMBB;
15366
15367   // Add a PHI.
15368   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15369                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15370
15371   unsigned Opc = MI->getOpcode();
15372   switch (Opc) {
15373   default:
15374     llvm_unreachable("Unhandled atomic-load-op opcode!");
15375   case X86::ATOMAND8:
15376   case X86::ATOMAND16:
15377   case X86::ATOMAND32:
15378   case X86::ATOMAND64:
15379   case X86::ATOMOR8:
15380   case X86::ATOMOR16:
15381   case X86::ATOMOR32:
15382   case X86::ATOMOR64:
15383   case X86::ATOMXOR8:
15384   case X86::ATOMXOR16:
15385   case X86::ATOMXOR32:
15386   case X86::ATOMXOR64: {
15387     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15388     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15389       .addReg(t4);
15390     break;
15391   }
15392   case X86::ATOMNAND8:
15393   case X86::ATOMNAND16:
15394   case X86::ATOMNAND32:
15395   case X86::ATOMNAND64: {
15396     unsigned Tmp = MRI.createVirtualRegister(RC);
15397     unsigned NOTOpc;
15398     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15399     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15400       .addReg(t4);
15401     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15402     break;
15403   }
15404   case X86::ATOMMAX8:
15405   case X86::ATOMMAX16:
15406   case X86::ATOMMAX32:
15407   case X86::ATOMMAX64:
15408   case X86::ATOMMIN8:
15409   case X86::ATOMMIN16:
15410   case X86::ATOMMIN32:
15411   case X86::ATOMMIN64:
15412   case X86::ATOMUMAX8:
15413   case X86::ATOMUMAX16:
15414   case X86::ATOMUMAX32:
15415   case X86::ATOMUMAX64:
15416   case X86::ATOMUMIN8:
15417   case X86::ATOMUMIN16:
15418   case X86::ATOMUMIN32:
15419   case X86::ATOMUMIN64: {
15420     unsigned CMPOpc;
15421     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15422
15423     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15424       .addReg(SrcReg)
15425       .addReg(t4);
15426
15427     if (Subtarget->hasCMov()) {
15428       if (VT != MVT::i8) {
15429         // Native support
15430         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15431           .addReg(SrcReg)
15432           .addReg(t4);
15433       } else {
15434         // Promote i8 to i32 to use CMOV32
15435         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15436         const TargetRegisterClass *RC32 =
15437           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15438         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15439         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15440         unsigned Tmp = MRI.createVirtualRegister(RC32);
15441
15442         unsigned Undef = MRI.createVirtualRegister(RC32);
15443         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15444
15445         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15446           .addReg(Undef)
15447           .addReg(SrcReg)
15448           .addImm(X86::sub_8bit);
15449         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15450           .addReg(Undef)
15451           .addReg(t4)
15452           .addImm(X86::sub_8bit);
15453
15454         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15455           .addReg(SrcReg32)
15456           .addReg(AccReg32);
15457
15458         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15459           .addReg(Tmp, 0, X86::sub_8bit);
15460       }
15461     } else {
15462       // Use pseudo select and lower them.
15463       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15464              "Invalid atomic-load-op transformation!");
15465       unsigned SelOpc = getPseudoCMOVOpc(VT);
15466       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15467       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15468       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15469               .addReg(SrcReg).addReg(t4)
15470               .addImm(CC);
15471       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15472       // Replace the original PHI node as mainMBB is changed after CMOV
15473       // lowering.
15474       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15475         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15476       Phi->eraseFromParent();
15477     }
15478     break;
15479   }
15480   }
15481
15482   // Copy PhyReg back from virtual register.
15483   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15484     .addReg(t4);
15485
15486   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15487   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15488     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15489     if (NewMO.isReg())
15490       NewMO.setIsKill(false);
15491     MIB.addOperand(NewMO);
15492   }
15493   MIB.addReg(t2);
15494   MIB.setMemRefs(MMOBegin, MMOEnd);
15495
15496   // Copy PhyReg back to virtual register.
15497   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15498     .addReg(PhyReg);
15499
15500   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15501
15502   mainMBB->addSuccessor(origMainMBB);
15503   mainMBB->addSuccessor(sinkMBB);
15504
15505   // sinkMBB:
15506   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15507           TII->get(TargetOpcode::COPY), DstReg)
15508     .addReg(t3);
15509
15510   MI->eraseFromParent();
15511   return sinkMBB;
15512 }
15513
15514 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15515 // instructions. They will be translated into a spin-loop or compare-exchange
15516 // loop from
15517 //
15518 //    ...
15519 //    dst = atomic-fetch-op MI.addr, MI.val
15520 //    ...
15521 //
15522 // to
15523 //
15524 //    ...
15525 //    t1L = LOAD [MI.addr + 0]
15526 //    t1H = LOAD [MI.addr + 4]
15527 // loop:
15528 //    t4L = phi(t1L, t3L / loop)
15529 //    t4H = phi(t1H, t3H / loop)
15530 //    t2L = OP MI.val.lo, t4L
15531 //    t2H = OP MI.val.hi, t4H
15532 //    EAX = t4L
15533 //    EDX = t4H
15534 //    EBX = t2L
15535 //    ECX = t2H
15536 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15537 //    t3L = EAX
15538 //    t3H = EDX
15539 //    JNE loop
15540 // sink:
15541 //    dstL = t3L
15542 //    dstH = t3H
15543 //    ...
15544 MachineBasicBlock *
15545 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15546                                            MachineBasicBlock *MBB) const {
15547   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15548   DebugLoc DL = MI->getDebugLoc();
15549
15550   MachineFunction *MF = MBB->getParent();
15551   MachineRegisterInfo &MRI = MF->getRegInfo();
15552
15553   const BasicBlock *BB = MBB->getBasicBlock();
15554   MachineFunction::iterator I = MBB;
15555   ++I;
15556
15557   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15558          "Unexpected number of operands");
15559
15560   assert(MI->hasOneMemOperand() &&
15561          "Expected atomic-load-op32 to have one memoperand");
15562
15563   // Memory Reference
15564   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15565   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15566
15567   unsigned DstLoReg, DstHiReg;
15568   unsigned SrcLoReg, SrcHiReg;
15569   unsigned MemOpndSlot;
15570
15571   unsigned CurOp = 0;
15572
15573   DstLoReg = MI->getOperand(CurOp++).getReg();
15574   DstHiReg = MI->getOperand(CurOp++).getReg();
15575   MemOpndSlot = CurOp;
15576   CurOp += X86::AddrNumOperands;
15577   SrcLoReg = MI->getOperand(CurOp++).getReg();
15578   SrcHiReg = MI->getOperand(CurOp++).getReg();
15579
15580   const TargetRegisterClass *RC = &X86::GR32RegClass;
15581   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15582
15583   unsigned t1L = MRI.createVirtualRegister(RC);
15584   unsigned t1H = MRI.createVirtualRegister(RC);
15585   unsigned t2L = MRI.createVirtualRegister(RC);
15586   unsigned t2H = MRI.createVirtualRegister(RC);
15587   unsigned t3L = MRI.createVirtualRegister(RC);
15588   unsigned t3H = MRI.createVirtualRegister(RC);
15589   unsigned t4L = MRI.createVirtualRegister(RC);
15590   unsigned t4H = MRI.createVirtualRegister(RC);
15591
15592   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15593   unsigned LOADOpc = X86::MOV32rm;
15594
15595   // For the atomic load-arith operator, we generate
15596   //
15597   //  thisMBB:
15598   //    t1L = LOAD [MI.addr + 0]
15599   //    t1H = LOAD [MI.addr + 4]
15600   //  mainMBB:
15601   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15602   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15603   //    t2L = OP MI.val.lo, t4L
15604   //    t2H = OP MI.val.hi, t4H
15605   //    EBX = t2L
15606   //    ECX = t2H
15607   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15608   //    t3L = EAX
15609   //    t3H = EDX
15610   //    JNE loop
15611   //  sinkMBB:
15612   //    dstL = t3L
15613   //    dstH = t3H
15614
15615   MachineBasicBlock *thisMBB = MBB;
15616   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15617   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15618   MF->insert(I, mainMBB);
15619   MF->insert(I, sinkMBB);
15620
15621   MachineInstrBuilder MIB;
15622
15623   // Transfer the remainder of BB and its successor edges to sinkMBB.
15624   sinkMBB->splice(sinkMBB->begin(), MBB,
15625                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15626   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15627
15628   // thisMBB:
15629   // Lo
15630   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15631   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15632     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15633     if (NewMO.isReg())
15634       NewMO.setIsKill(false);
15635     MIB.addOperand(NewMO);
15636   }
15637   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15638     unsigned flags = (*MMOI)->getFlags();
15639     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15640     MachineMemOperand *MMO =
15641       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15642                                (*MMOI)->getSize(),
15643                                (*MMOI)->getBaseAlignment(),
15644                                (*MMOI)->getTBAAInfo(),
15645                                (*MMOI)->getRanges());
15646     MIB.addMemOperand(MMO);
15647   };
15648   MachineInstr *LowMI = MIB;
15649
15650   // Hi
15651   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15652   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15653     if (i == X86::AddrDisp) {
15654       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15655     } else {
15656       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15657       if (NewMO.isReg())
15658         NewMO.setIsKill(false);
15659       MIB.addOperand(NewMO);
15660     }
15661   }
15662   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15663
15664   thisMBB->addSuccessor(mainMBB);
15665
15666   // mainMBB:
15667   MachineBasicBlock *origMainMBB = mainMBB;
15668
15669   // Add PHIs.
15670   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15671                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15672   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15673                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15674
15675   unsigned Opc = MI->getOpcode();
15676   switch (Opc) {
15677   default:
15678     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15679   case X86::ATOMAND6432:
15680   case X86::ATOMOR6432:
15681   case X86::ATOMXOR6432:
15682   case X86::ATOMADD6432:
15683   case X86::ATOMSUB6432: {
15684     unsigned HiOpc;
15685     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15686     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15687       .addReg(SrcLoReg);
15688     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15689       .addReg(SrcHiReg);
15690     break;
15691   }
15692   case X86::ATOMNAND6432: {
15693     unsigned HiOpc, NOTOpc;
15694     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15695     unsigned TmpL = MRI.createVirtualRegister(RC);
15696     unsigned TmpH = MRI.createVirtualRegister(RC);
15697     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15698       .addReg(t4L);
15699     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15700       .addReg(t4H);
15701     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15702     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15703     break;
15704   }
15705   case X86::ATOMMAX6432:
15706   case X86::ATOMMIN6432:
15707   case X86::ATOMUMAX6432:
15708   case X86::ATOMUMIN6432: {
15709     unsigned HiOpc;
15710     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15711     unsigned cL = MRI.createVirtualRegister(RC8);
15712     unsigned cH = MRI.createVirtualRegister(RC8);
15713     unsigned cL32 = MRI.createVirtualRegister(RC);
15714     unsigned cH32 = MRI.createVirtualRegister(RC);
15715     unsigned cc = MRI.createVirtualRegister(RC);
15716     // cl := cmp src_lo, lo
15717     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15718       .addReg(SrcLoReg).addReg(t4L);
15719     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15720     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15721     // ch := cmp src_hi, hi
15722     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15723       .addReg(SrcHiReg).addReg(t4H);
15724     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15725     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15726     // cc := if (src_hi == hi) ? cl : ch;
15727     if (Subtarget->hasCMov()) {
15728       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15729         .addReg(cH32).addReg(cL32);
15730     } else {
15731       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15732               .addReg(cH32).addReg(cL32)
15733               .addImm(X86::COND_E);
15734       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15735     }
15736     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15737     if (Subtarget->hasCMov()) {
15738       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15739         .addReg(SrcLoReg).addReg(t4L);
15740       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15741         .addReg(SrcHiReg).addReg(t4H);
15742     } else {
15743       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15744               .addReg(SrcLoReg).addReg(t4L)
15745               .addImm(X86::COND_NE);
15746       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15747       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15748       // 2nd CMOV lowering.
15749       mainMBB->addLiveIn(X86::EFLAGS);
15750       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15751               .addReg(SrcHiReg).addReg(t4H)
15752               .addImm(X86::COND_NE);
15753       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15754       // Replace the original PHI node as mainMBB is changed after CMOV
15755       // lowering.
15756       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15757         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15758       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15759         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15760       PhiL->eraseFromParent();
15761       PhiH->eraseFromParent();
15762     }
15763     break;
15764   }
15765   case X86::ATOMSWAP6432: {
15766     unsigned HiOpc;
15767     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15768     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15769     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15770     break;
15771   }
15772   }
15773
15774   // Copy EDX:EAX back from HiReg:LoReg
15775   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15776   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15777   // Copy ECX:EBX from t1H:t1L
15778   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15779   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15780
15781   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15782   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15783     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15784     if (NewMO.isReg())
15785       NewMO.setIsKill(false);
15786     MIB.addOperand(NewMO);
15787   }
15788   MIB.setMemRefs(MMOBegin, MMOEnd);
15789
15790   // Copy EDX:EAX back to t3H:t3L
15791   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15792   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15793
15794   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15795
15796   mainMBB->addSuccessor(origMainMBB);
15797   mainMBB->addSuccessor(sinkMBB);
15798
15799   // sinkMBB:
15800   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15801           TII->get(TargetOpcode::COPY), DstLoReg)
15802     .addReg(t3L);
15803   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15804           TII->get(TargetOpcode::COPY), DstHiReg)
15805     .addReg(t3H);
15806
15807   MI->eraseFromParent();
15808   return sinkMBB;
15809 }
15810
15811 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15812 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15813 // in the .td file.
15814 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15815                                        const TargetInstrInfo *TII) {
15816   unsigned Opc;
15817   switch (MI->getOpcode()) {
15818   default: llvm_unreachable("illegal opcode!");
15819   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15820   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15821   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15822   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15823   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15824   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15825   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15826   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15827   }
15828
15829   DebugLoc dl = MI->getDebugLoc();
15830   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15831
15832   unsigned NumArgs = MI->getNumOperands();
15833   for (unsigned i = 1; i < NumArgs; ++i) {
15834     MachineOperand &Op = MI->getOperand(i);
15835     if (!(Op.isReg() && Op.isImplicit()))
15836       MIB.addOperand(Op);
15837   }
15838   if (MI->hasOneMemOperand())
15839     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15840
15841   BuildMI(*BB, MI, dl,
15842     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15843     .addReg(X86::XMM0);
15844
15845   MI->eraseFromParent();
15846   return BB;
15847 }
15848
15849 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15850 // defs in an instruction pattern
15851 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15852                                        const TargetInstrInfo *TII) {
15853   unsigned Opc;
15854   switch (MI->getOpcode()) {
15855   default: llvm_unreachable("illegal opcode!");
15856   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15857   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15858   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15859   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15860   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15861   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15862   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15863   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15864   }
15865
15866   DebugLoc dl = MI->getDebugLoc();
15867   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15868
15869   unsigned NumArgs = MI->getNumOperands(); // remove the results
15870   for (unsigned i = 1; i < NumArgs; ++i) {
15871     MachineOperand &Op = MI->getOperand(i);
15872     if (!(Op.isReg() && Op.isImplicit()))
15873       MIB.addOperand(Op);
15874   }
15875   if (MI->hasOneMemOperand())
15876     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15877
15878   BuildMI(*BB, MI, dl,
15879     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15880     .addReg(X86::ECX);
15881
15882   MI->eraseFromParent();
15883   return BB;
15884 }
15885
15886 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15887                                        const TargetInstrInfo *TII,
15888                                        const X86Subtarget* Subtarget) {
15889   DebugLoc dl = MI->getDebugLoc();
15890
15891   // Address into RAX/EAX, other two args into ECX, EDX.
15892   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15893   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15894   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15895   for (int i = 0; i < X86::AddrNumOperands; ++i)
15896     MIB.addOperand(MI->getOperand(i));
15897
15898   unsigned ValOps = X86::AddrNumOperands;
15899   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15900     .addReg(MI->getOperand(ValOps).getReg());
15901   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15902     .addReg(MI->getOperand(ValOps+1).getReg());
15903
15904   // The instruction doesn't actually take any operands though.
15905   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15906
15907   MI->eraseFromParent(); // The pseudo is gone now.
15908   return BB;
15909 }
15910
15911 MachineBasicBlock *
15912 X86TargetLowering::EmitVAARG64WithCustomInserter(
15913                    MachineInstr *MI,
15914                    MachineBasicBlock *MBB) const {
15915   // Emit va_arg instruction on X86-64.
15916
15917   // Operands to this pseudo-instruction:
15918   // 0  ) Output        : destination address (reg)
15919   // 1-5) Input         : va_list address (addr, i64mem)
15920   // 6  ) ArgSize       : Size (in bytes) of vararg type
15921   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15922   // 8  ) Align         : Alignment of type
15923   // 9  ) EFLAGS (implicit-def)
15924
15925   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15926   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15927
15928   unsigned DestReg = MI->getOperand(0).getReg();
15929   MachineOperand &Base = MI->getOperand(1);
15930   MachineOperand &Scale = MI->getOperand(2);
15931   MachineOperand &Index = MI->getOperand(3);
15932   MachineOperand &Disp = MI->getOperand(4);
15933   MachineOperand &Segment = MI->getOperand(5);
15934   unsigned ArgSize = MI->getOperand(6).getImm();
15935   unsigned ArgMode = MI->getOperand(7).getImm();
15936   unsigned Align = MI->getOperand(8).getImm();
15937
15938   // Memory Reference
15939   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15940   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15941   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15942
15943   // Machine Information
15944   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15945   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15946   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15947   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15948   DebugLoc DL = MI->getDebugLoc();
15949
15950   // struct va_list {
15951   //   i32   gp_offset
15952   //   i32   fp_offset
15953   //   i64   overflow_area (address)
15954   //   i64   reg_save_area (address)
15955   // }
15956   // sizeof(va_list) = 24
15957   // alignment(va_list) = 8
15958
15959   unsigned TotalNumIntRegs = 6;
15960   unsigned TotalNumXMMRegs = 8;
15961   bool UseGPOffset = (ArgMode == 1);
15962   bool UseFPOffset = (ArgMode == 2);
15963   unsigned MaxOffset = TotalNumIntRegs * 8 +
15964                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15965
15966   /* Align ArgSize to a multiple of 8 */
15967   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15968   bool NeedsAlign = (Align > 8);
15969
15970   MachineBasicBlock *thisMBB = MBB;
15971   MachineBasicBlock *overflowMBB;
15972   MachineBasicBlock *offsetMBB;
15973   MachineBasicBlock *endMBB;
15974
15975   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15976   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15977   unsigned OffsetReg = 0;
15978
15979   if (!UseGPOffset && !UseFPOffset) {
15980     // If we only pull from the overflow region, we don't create a branch.
15981     // We don't need to alter control flow.
15982     OffsetDestReg = 0; // unused
15983     OverflowDestReg = DestReg;
15984
15985     offsetMBB = nullptr;
15986     overflowMBB = thisMBB;
15987     endMBB = thisMBB;
15988   } else {
15989     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15990     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15991     // If not, pull from overflow_area. (branch to overflowMBB)
15992     //
15993     //       thisMBB
15994     //         |     .
15995     //         |        .
15996     //     offsetMBB   overflowMBB
15997     //         |        .
15998     //         |     .
15999     //        endMBB
16000
16001     // Registers for the PHI in endMBB
16002     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16003     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16004
16005     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16006     MachineFunction *MF = MBB->getParent();
16007     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16008     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16009     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16010
16011     MachineFunction::iterator MBBIter = MBB;
16012     ++MBBIter;
16013
16014     // Insert the new basic blocks
16015     MF->insert(MBBIter, offsetMBB);
16016     MF->insert(MBBIter, overflowMBB);
16017     MF->insert(MBBIter, endMBB);
16018
16019     // Transfer the remainder of MBB and its successor edges to endMBB.
16020     endMBB->splice(endMBB->begin(), thisMBB,
16021                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16022     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16023
16024     // Make offsetMBB and overflowMBB successors of thisMBB
16025     thisMBB->addSuccessor(offsetMBB);
16026     thisMBB->addSuccessor(overflowMBB);
16027
16028     // endMBB is a successor of both offsetMBB and overflowMBB
16029     offsetMBB->addSuccessor(endMBB);
16030     overflowMBB->addSuccessor(endMBB);
16031
16032     // Load the offset value into a register
16033     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16034     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16035       .addOperand(Base)
16036       .addOperand(Scale)
16037       .addOperand(Index)
16038       .addDisp(Disp, UseFPOffset ? 4 : 0)
16039       .addOperand(Segment)
16040       .setMemRefs(MMOBegin, MMOEnd);
16041
16042     // Check if there is enough room left to pull this argument.
16043     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16044       .addReg(OffsetReg)
16045       .addImm(MaxOffset + 8 - ArgSizeA8);
16046
16047     // Branch to "overflowMBB" if offset >= max
16048     // Fall through to "offsetMBB" otherwise
16049     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16050       .addMBB(overflowMBB);
16051   }
16052
16053   // In offsetMBB, emit code to use the reg_save_area.
16054   if (offsetMBB) {
16055     assert(OffsetReg != 0);
16056
16057     // Read the reg_save_area address.
16058     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16059     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16060       .addOperand(Base)
16061       .addOperand(Scale)
16062       .addOperand(Index)
16063       .addDisp(Disp, 16)
16064       .addOperand(Segment)
16065       .setMemRefs(MMOBegin, MMOEnd);
16066
16067     // Zero-extend the offset
16068     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16069       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16070         .addImm(0)
16071         .addReg(OffsetReg)
16072         .addImm(X86::sub_32bit);
16073
16074     // Add the offset to the reg_save_area to get the final address.
16075     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16076       .addReg(OffsetReg64)
16077       .addReg(RegSaveReg);
16078
16079     // Compute the offset for the next argument
16080     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16081     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16082       .addReg(OffsetReg)
16083       .addImm(UseFPOffset ? 16 : 8);
16084
16085     // Store it back into the va_list.
16086     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16087       .addOperand(Base)
16088       .addOperand(Scale)
16089       .addOperand(Index)
16090       .addDisp(Disp, UseFPOffset ? 4 : 0)
16091       .addOperand(Segment)
16092       .addReg(NextOffsetReg)
16093       .setMemRefs(MMOBegin, MMOEnd);
16094
16095     // Jump to endMBB
16096     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16097       .addMBB(endMBB);
16098   }
16099
16100   //
16101   // Emit code to use overflow area
16102   //
16103
16104   // Load the overflow_area address into a register.
16105   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16106   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16107     .addOperand(Base)
16108     .addOperand(Scale)
16109     .addOperand(Index)
16110     .addDisp(Disp, 8)
16111     .addOperand(Segment)
16112     .setMemRefs(MMOBegin, MMOEnd);
16113
16114   // If we need to align it, do so. Otherwise, just copy the address
16115   // to OverflowDestReg.
16116   if (NeedsAlign) {
16117     // Align the overflow address
16118     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16119     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16120
16121     // aligned_addr = (addr + (align-1)) & ~(align-1)
16122     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16123       .addReg(OverflowAddrReg)
16124       .addImm(Align-1);
16125
16126     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16127       .addReg(TmpReg)
16128       .addImm(~(uint64_t)(Align-1));
16129   } else {
16130     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16131       .addReg(OverflowAddrReg);
16132   }
16133
16134   // Compute the next overflow address after this argument.
16135   // (the overflow address should be kept 8-byte aligned)
16136   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16137   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16138     .addReg(OverflowDestReg)
16139     .addImm(ArgSizeA8);
16140
16141   // Store the new overflow address.
16142   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16143     .addOperand(Base)
16144     .addOperand(Scale)
16145     .addOperand(Index)
16146     .addDisp(Disp, 8)
16147     .addOperand(Segment)
16148     .addReg(NextAddrReg)
16149     .setMemRefs(MMOBegin, MMOEnd);
16150
16151   // If we branched, emit the PHI to the front of endMBB.
16152   if (offsetMBB) {
16153     BuildMI(*endMBB, endMBB->begin(), DL,
16154             TII->get(X86::PHI), DestReg)
16155       .addReg(OffsetDestReg).addMBB(offsetMBB)
16156       .addReg(OverflowDestReg).addMBB(overflowMBB);
16157   }
16158
16159   // Erase the pseudo instruction
16160   MI->eraseFromParent();
16161
16162   return endMBB;
16163 }
16164
16165 MachineBasicBlock *
16166 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16167                                                  MachineInstr *MI,
16168                                                  MachineBasicBlock *MBB) const {
16169   // Emit code to save XMM registers to the stack. The ABI says that the
16170   // number of registers to save is given in %al, so it's theoretically
16171   // possible to do an indirect jump trick to avoid saving all of them,
16172   // however this code takes a simpler approach and just executes all
16173   // of the stores if %al is non-zero. It's less code, and it's probably
16174   // easier on the hardware branch predictor, and stores aren't all that
16175   // expensive anyway.
16176
16177   // Create the new basic blocks. One block contains all the XMM stores,
16178   // and one block is the final destination regardless of whether any
16179   // stores were performed.
16180   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16181   MachineFunction *F = MBB->getParent();
16182   MachineFunction::iterator MBBIter = MBB;
16183   ++MBBIter;
16184   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16185   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16186   F->insert(MBBIter, XMMSaveMBB);
16187   F->insert(MBBIter, EndMBB);
16188
16189   // Transfer the remainder of MBB and its successor edges to EndMBB.
16190   EndMBB->splice(EndMBB->begin(), MBB,
16191                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16192   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16193
16194   // The original block will now fall through to the XMM save block.
16195   MBB->addSuccessor(XMMSaveMBB);
16196   // The XMMSaveMBB will fall through to the end block.
16197   XMMSaveMBB->addSuccessor(EndMBB);
16198
16199   // Now add the instructions.
16200   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16201   DebugLoc DL = MI->getDebugLoc();
16202
16203   unsigned CountReg = MI->getOperand(0).getReg();
16204   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16205   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16206
16207   if (!Subtarget->isTargetWin64()) {
16208     // If %al is 0, branch around the XMM save block.
16209     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16210     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16211     MBB->addSuccessor(EndMBB);
16212   }
16213
16214   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16215   // that was just emitted, but clearly shouldn't be "saved".
16216   assert((MI->getNumOperands() <= 3 ||
16217           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16218           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16219          && "Expected last argument to be EFLAGS");
16220   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16221   // In the XMM save block, save all the XMM argument registers.
16222   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16223     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16224     MachineMemOperand *MMO =
16225       F->getMachineMemOperand(
16226           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16227         MachineMemOperand::MOStore,
16228         /*Size=*/16, /*Align=*/16);
16229     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16230       .addFrameIndex(RegSaveFrameIndex)
16231       .addImm(/*Scale=*/1)
16232       .addReg(/*IndexReg=*/0)
16233       .addImm(/*Disp=*/Offset)
16234       .addReg(/*Segment=*/0)
16235       .addReg(MI->getOperand(i).getReg())
16236       .addMemOperand(MMO);
16237   }
16238
16239   MI->eraseFromParent();   // The pseudo instruction is gone now.
16240
16241   return EndMBB;
16242 }
16243
16244 // The EFLAGS operand of SelectItr might be missing a kill marker
16245 // because there were multiple uses of EFLAGS, and ISel didn't know
16246 // which to mark. Figure out whether SelectItr should have had a
16247 // kill marker, and set it if it should. Returns the correct kill
16248 // marker value.
16249 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16250                                      MachineBasicBlock* BB,
16251                                      const TargetRegisterInfo* TRI) {
16252   // Scan forward through BB for a use/def of EFLAGS.
16253   MachineBasicBlock::iterator miI(std::next(SelectItr));
16254   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16255     const MachineInstr& mi = *miI;
16256     if (mi.readsRegister(X86::EFLAGS))
16257       return false;
16258     if (mi.definesRegister(X86::EFLAGS))
16259       break; // Should have kill-flag - update below.
16260   }
16261
16262   // If we hit the end of the block, check whether EFLAGS is live into a
16263   // successor.
16264   if (miI == BB->end()) {
16265     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16266                                           sEnd = BB->succ_end();
16267          sItr != sEnd; ++sItr) {
16268       MachineBasicBlock* succ = *sItr;
16269       if (succ->isLiveIn(X86::EFLAGS))
16270         return false;
16271     }
16272   }
16273
16274   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16275   // out. SelectMI should have a kill flag on EFLAGS.
16276   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16277   return true;
16278 }
16279
16280 MachineBasicBlock *
16281 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16282                                      MachineBasicBlock *BB) const {
16283   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16284   DebugLoc DL = MI->getDebugLoc();
16285
16286   // To "insert" a SELECT_CC instruction, we actually have to insert the
16287   // diamond control-flow pattern.  The incoming instruction knows the
16288   // destination vreg to set, the condition code register to branch on, the
16289   // true/false values to select between, and a branch opcode to use.
16290   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16291   MachineFunction::iterator It = BB;
16292   ++It;
16293
16294   //  thisMBB:
16295   //  ...
16296   //   TrueVal = ...
16297   //   cmpTY ccX, r1, r2
16298   //   bCC copy1MBB
16299   //   fallthrough --> copy0MBB
16300   MachineBasicBlock *thisMBB = BB;
16301   MachineFunction *F = BB->getParent();
16302   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16303   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16304   F->insert(It, copy0MBB);
16305   F->insert(It, sinkMBB);
16306
16307   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16308   // live into the sink and copy blocks.
16309   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16310   if (!MI->killsRegister(X86::EFLAGS) &&
16311       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16312     copy0MBB->addLiveIn(X86::EFLAGS);
16313     sinkMBB->addLiveIn(X86::EFLAGS);
16314   }
16315
16316   // Transfer the remainder of BB and its successor edges to sinkMBB.
16317   sinkMBB->splice(sinkMBB->begin(), BB,
16318                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16319   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16320
16321   // Add the true and fallthrough blocks as its successors.
16322   BB->addSuccessor(copy0MBB);
16323   BB->addSuccessor(sinkMBB);
16324
16325   // Create the conditional branch instruction.
16326   unsigned Opc =
16327     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16328   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16329
16330   //  copy0MBB:
16331   //   %FalseValue = ...
16332   //   # fallthrough to sinkMBB
16333   copy0MBB->addSuccessor(sinkMBB);
16334
16335   //  sinkMBB:
16336   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16337   //  ...
16338   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16339           TII->get(X86::PHI), MI->getOperand(0).getReg())
16340     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16341     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16342
16343   MI->eraseFromParent();   // The pseudo instruction is gone now.
16344   return sinkMBB;
16345 }
16346
16347 MachineBasicBlock *
16348 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16349                                         bool Is64Bit) const {
16350   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16351   DebugLoc DL = MI->getDebugLoc();
16352   MachineFunction *MF = BB->getParent();
16353   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16354
16355   assert(MF->shouldSplitStack());
16356
16357   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16358   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16359
16360   // BB:
16361   //  ... [Till the alloca]
16362   // If stacklet is not large enough, jump to mallocMBB
16363   //
16364   // bumpMBB:
16365   //  Allocate by subtracting from RSP
16366   //  Jump to continueMBB
16367   //
16368   // mallocMBB:
16369   //  Allocate by call to runtime
16370   //
16371   // continueMBB:
16372   //  ...
16373   //  [rest of original BB]
16374   //
16375
16376   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16377   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16378   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16379
16380   MachineRegisterInfo &MRI = MF->getRegInfo();
16381   const TargetRegisterClass *AddrRegClass =
16382     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16383
16384   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16385     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16386     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16387     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16388     sizeVReg = MI->getOperand(1).getReg(),
16389     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16390
16391   MachineFunction::iterator MBBIter = BB;
16392   ++MBBIter;
16393
16394   MF->insert(MBBIter, bumpMBB);
16395   MF->insert(MBBIter, mallocMBB);
16396   MF->insert(MBBIter, continueMBB);
16397
16398   continueMBB->splice(continueMBB->begin(), BB,
16399                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16400   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16401
16402   // Add code to the main basic block to check if the stack limit has been hit,
16403   // and if so, jump to mallocMBB otherwise to bumpMBB.
16404   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16405   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16406     .addReg(tmpSPVReg).addReg(sizeVReg);
16407   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16408     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16409     .addReg(SPLimitVReg);
16410   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16411
16412   // bumpMBB simply decreases the stack pointer, since we know the current
16413   // stacklet has enough space.
16414   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16415     .addReg(SPLimitVReg);
16416   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16417     .addReg(SPLimitVReg);
16418   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16419
16420   // Calls into a routine in libgcc to allocate more space from the heap.
16421   const uint32_t *RegMask =
16422     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16423   if (Is64Bit) {
16424     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16425       .addReg(sizeVReg);
16426     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16427       .addExternalSymbol("__morestack_allocate_stack_space")
16428       .addRegMask(RegMask)
16429       .addReg(X86::RDI, RegState::Implicit)
16430       .addReg(X86::RAX, RegState::ImplicitDefine);
16431   } else {
16432     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16433       .addImm(12);
16434     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16435     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16436       .addExternalSymbol("__morestack_allocate_stack_space")
16437       .addRegMask(RegMask)
16438       .addReg(X86::EAX, RegState::ImplicitDefine);
16439   }
16440
16441   if (!Is64Bit)
16442     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16443       .addImm(16);
16444
16445   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16446     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16447   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16448
16449   // Set up the CFG correctly.
16450   BB->addSuccessor(bumpMBB);
16451   BB->addSuccessor(mallocMBB);
16452   mallocMBB->addSuccessor(continueMBB);
16453   bumpMBB->addSuccessor(continueMBB);
16454
16455   // Take care of the PHI nodes.
16456   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16457           MI->getOperand(0).getReg())
16458     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16459     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16460
16461   // Delete the original pseudo instruction.
16462   MI->eraseFromParent();
16463
16464   // And we're done.
16465   return continueMBB;
16466 }
16467
16468 MachineBasicBlock *
16469 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16470                                           MachineBasicBlock *BB) const {
16471   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16472   DebugLoc DL = MI->getDebugLoc();
16473
16474   assert(!Subtarget->isTargetMacho());
16475
16476   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16477   // non-trivial part is impdef of ESP.
16478
16479   if (Subtarget->isTargetWin64()) {
16480     if (Subtarget->isTargetCygMing()) {
16481       // ___chkstk(Mingw64):
16482       // Clobbers R10, R11, RAX and EFLAGS.
16483       // Updates RSP.
16484       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16485         .addExternalSymbol("___chkstk")
16486         .addReg(X86::RAX, RegState::Implicit)
16487         .addReg(X86::RSP, RegState::Implicit)
16488         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16489         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16490         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16491     } else {
16492       // __chkstk(MSVCRT): does not update stack pointer.
16493       // Clobbers R10, R11 and EFLAGS.
16494       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16495         .addExternalSymbol("__chkstk")
16496         .addReg(X86::RAX, RegState::Implicit)
16497         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16498       // RAX has the offset to be subtracted from RSP.
16499       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16500         .addReg(X86::RSP)
16501         .addReg(X86::RAX);
16502     }
16503   } else {
16504     const char *StackProbeSymbol =
16505       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16506
16507     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16508       .addExternalSymbol(StackProbeSymbol)
16509       .addReg(X86::EAX, RegState::Implicit)
16510       .addReg(X86::ESP, RegState::Implicit)
16511       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16512       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16513       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16514   }
16515
16516   MI->eraseFromParent();   // The pseudo instruction is gone now.
16517   return BB;
16518 }
16519
16520 MachineBasicBlock *
16521 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16522                                       MachineBasicBlock *BB) const {
16523   // This is pretty easy.  We're taking the value that we received from
16524   // our load from the relocation, sticking it in either RDI (x86-64)
16525   // or EAX and doing an indirect call.  The return value will then
16526   // be in the normal return register.
16527   const X86InstrInfo *TII
16528     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16529   DebugLoc DL = MI->getDebugLoc();
16530   MachineFunction *F = BB->getParent();
16531
16532   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16533   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16534
16535   // Get a register mask for the lowered call.
16536   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16537   // proper register mask.
16538   const uint32_t *RegMask =
16539     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16540   if (Subtarget->is64Bit()) {
16541     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16542                                       TII->get(X86::MOV64rm), X86::RDI)
16543     .addReg(X86::RIP)
16544     .addImm(0).addReg(0)
16545     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16546                       MI->getOperand(3).getTargetFlags())
16547     .addReg(0);
16548     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16549     addDirectMem(MIB, X86::RDI);
16550     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16551   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16552     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16553                                       TII->get(X86::MOV32rm), X86::EAX)
16554     .addReg(0)
16555     .addImm(0).addReg(0)
16556     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16557                       MI->getOperand(3).getTargetFlags())
16558     .addReg(0);
16559     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16560     addDirectMem(MIB, X86::EAX);
16561     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16562   } else {
16563     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16564                                       TII->get(X86::MOV32rm), X86::EAX)
16565     .addReg(TII->getGlobalBaseReg(F))
16566     .addImm(0).addReg(0)
16567     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16568                       MI->getOperand(3).getTargetFlags())
16569     .addReg(0);
16570     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16571     addDirectMem(MIB, X86::EAX);
16572     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16573   }
16574
16575   MI->eraseFromParent(); // The pseudo instruction is gone now.
16576   return BB;
16577 }
16578
16579 MachineBasicBlock *
16580 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16581                                     MachineBasicBlock *MBB) const {
16582   DebugLoc DL = MI->getDebugLoc();
16583   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16584
16585   MachineFunction *MF = MBB->getParent();
16586   MachineRegisterInfo &MRI = MF->getRegInfo();
16587
16588   const BasicBlock *BB = MBB->getBasicBlock();
16589   MachineFunction::iterator I = MBB;
16590   ++I;
16591
16592   // Memory Reference
16593   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16594   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16595
16596   unsigned DstReg;
16597   unsigned MemOpndSlot = 0;
16598
16599   unsigned CurOp = 0;
16600
16601   DstReg = MI->getOperand(CurOp++).getReg();
16602   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16603   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16604   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16605   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16606
16607   MemOpndSlot = CurOp;
16608
16609   MVT PVT = getPointerTy();
16610   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16611          "Invalid Pointer Size!");
16612
16613   // For v = setjmp(buf), we generate
16614   //
16615   // thisMBB:
16616   //  buf[LabelOffset] = restoreMBB
16617   //  SjLjSetup restoreMBB
16618   //
16619   // mainMBB:
16620   //  v_main = 0
16621   //
16622   // sinkMBB:
16623   //  v = phi(main, restore)
16624   //
16625   // restoreMBB:
16626   //  v_restore = 1
16627
16628   MachineBasicBlock *thisMBB = MBB;
16629   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16630   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16631   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16632   MF->insert(I, mainMBB);
16633   MF->insert(I, sinkMBB);
16634   MF->push_back(restoreMBB);
16635
16636   MachineInstrBuilder MIB;
16637
16638   // Transfer the remainder of BB and its successor edges to sinkMBB.
16639   sinkMBB->splice(sinkMBB->begin(), MBB,
16640                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16641   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16642
16643   // thisMBB:
16644   unsigned PtrStoreOpc = 0;
16645   unsigned LabelReg = 0;
16646   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16647   Reloc::Model RM = getTargetMachine().getRelocationModel();
16648   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16649                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16650
16651   // Prepare IP either in reg or imm.
16652   if (!UseImmLabel) {
16653     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16654     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16655     LabelReg = MRI.createVirtualRegister(PtrRC);
16656     if (Subtarget->is64Bit()) {
16657       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16658               .addReg(X86::RIP)
16659               .addImm(0)
16660               .addReg(0)
16661               .addMBB(restoreMBB)
16662               .addReg(0);
16663     } else {
16664       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16665       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16666               .addReg(XII->getGlobalBaseReg(MF))
16667               .addImm(0)
16668               .addReg(0)
16669               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16670               .addReg(0);
16671     }
16672   } else
16673     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16674   // Store IP
16675   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16676   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16677     if (i == X86::AddrDisp)
16678       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16679     else
16680       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16681   }
16682   if (!UseImmLabel)
16683     MIB.addReg(LabelReg);
16684   else
16685     MIB.addMBB(restoreMBB);
16686   MIB.setMemRefs(MMOBegin, MMOEnd);
16687   // Setup
16688   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16689           .addMBB(restoreMBB);
16690
16691   const X86RegisterInfo *RegInfo =
16692     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16693   MIB.addRegMask(RegInfo->getNoPreservedMask());
16694   thisMBB->addSuccessor(mainMBB);
16695   thisMBB->addSuccessor(restoreMBB);
16696
16697   // mainMBB:
16698   //  EAX = 0
16699   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16700   mainMBB->addSuccessor(sinkMBB);
16701
16702   // sinkMBB:
16703   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16704           TII->get(X86::PHI), DstReg)
16705     .addReg(mainDstReg).addMBB(mainMBB)
16706     .addReg(restoreDstReg).addMBB(restoreMBB);
16707
16708   // restoreMBB:
16709   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16710   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16711   restoreMBB->addSuccessor(sinkMBB);
16712
16713   MI->eraseFromParent();
16714   return sinkMBB;
16715 }
16716
16717 MachineBasicBlock *
16718 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16719                                      MachineBasicBlock *MBB) const {
16720   DebugLoc DL = MI->getDebugLoc();
16721   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16722
16723   MachineFunction *MF = MBB->getParent();
16724   MachineRegisterInfo &MRI = MF->getRegInfo();
16725
16726   // Memory Reference
16727   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16728   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16729
16730   MVT PVT = getPointerTy();
16731   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16732          "Invalid Pointer Size!");
16733
16734   const TargetRegisterClass *RC =
16735     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16736   unsigned Tmp = MRI.createVirtualRegister(RC);
16737   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16738   const X86RegisterInfo *RegInfo =
16739     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16740   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16741   unsigned SP = RegInfo->getStackRegister();
16742
16743   MachineInstrBuilder MIB;
16744
16745   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16746   const int64_t SPOffset = 2 * PVT.getStoreSize();
16747
16748   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16749   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16750
16751   // Reload FP
16752   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16753   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16754     MIB.addOperand(MI->getOperand(i));
16755   MIB.setMemRefs(MMOBegin, MMOEnd);
16756   // Reload IP
16757   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16758   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16759     if (i == X86::AddrDisp)
16760       MIB.addDisp(MI->getOperand(i), LabelOffset);
16761     else
16762       MIB.addOperand(MI->getOperand(i));
16763   }
16764   MIB.setMemRefs(MMOBegin, MMOEnd);
16765   // Reload SP
16766   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16767   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16768     if (i == X86::AddrDisp)
16769       MIB.addDisp(MI->getOperand(i), SPOffset);
16770     else
16771       MIB.addOperand(MI->getOperand(i));
16772   }
16773   MIB.setMemRefs(MMOBegin, MMOEnd);
16774   // Jump
16775   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16776
16777   MI->eraseFromParent();
16778   return MBB;
16779 }
16780
16781 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16782 // accumulator loops. Writing back to the accumulator allows the coalescer
16783 // to remove extra copies in the loop.   
16784 MachineBasicBlock *
16785 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16786                                  MachineBasicBlock *MBB) const {
16787   MachineOperand &AddendOp = MI->getOperand(3);
16788
16789   // Bail out early if the addend isn't a register - we can't switch these.
16790   if (!AddendOp.isReg())
16791     return MBB;
16792
16793   MachineFunction &MF = *MBB->getParent();
16794   MachineRegisterInfo &MRI = MF.getRegInfo();
16795
16796   // Check whether the addend is defined by a PHI:
16797   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16798   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16799   if (!AddendDef.isPHI())
16800     return MBB;
16801
16802   // Look for the following pattern:
16803   // loop:
16804   //   %addend = phi [%entry, 0], [%loop, %result]
16805   //   ...
16806   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16807
16808   // Replace with:
16809   //   loop:
16810   //   %addend = phi [%entry, 0], [%loop, %result]
16811   //   ...
16812   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16813
16814   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16815     assert(AddendDef.getOperand(i).isReg());
16816     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16817     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16818     if (&PHISrcInst == MI) {
16819       // Found a matching instruction.
16820       unsigned NewFMAOpc = 0;
16821       switch (MI->getOpcode()) {
16822         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16823         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16824         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16825         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16826         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16827         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16828         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16829         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16830         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16831         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16832         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16833         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16834         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16835         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16836         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16837         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16838         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16839         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16840         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16841         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16842         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16843         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16844         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16845         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16846         default: llvm_unreachable("Unrecognized FMA variant.");
16847       }
16848
16849       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16850       MachineInstrBuilder MIB =
16851         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16852         .addOperand(MI->getOperand(0))
16853         .addOperand(MI->getOperand(3))
16854         .addOperand(MI->getOperand(2))
16855         .addOperand(MI->getOperand(1));
16856       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16857       MI->eraseFromParent();
16858     }
16859   }
16860
16861   return MBB;
16862 }
16863
16864 MachineBasicBlock *
16865 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16866                                                MachineBasicBlock *BB) const {
16867   switch (MI->getOpcode()) {
16868   default: llvm_unreachable("Unexpected instr type to insert");
16869   case X86::TAILJMPd64:
16870   case X86::TAILJMPr64:
16871   case X86::TAILJMPm64:
16872     llvm_unreachable("TAILJMP64 would not be touched here.");
16873   case X86::TCRETURNdi64:
16874   case X86::TCRETURNri64:
16875   case X86::TCRETURNmi64:
16876     return BB;
16877   case X86::WIN_ALLOCA:
16878     return EmitLoweredWinAlloca(MI, BB);
16879   case X86::SEG_ALLOCA_32:
16880     return EmitLoweredSegAlloca(MI, BB, false);
16881   case X86::SEG_ALLOCA_64:
16882     return EmitLoweredSegAlloca(MI, BB, true);
16883   case X86::TLSCall_32:
16884   case X86::TLSCall_64:
16885     return EmitLoweredTLSCall(MI, BB);
16886   case X86::CMOV_GR8:
16887   case X86::CMOV_FR32:
16888   case X86::CMOV_FR64:
16889   case X86::CMOV_V4F32:
16890   case X86::CMOV_V2F64:
16891   case X86::CMOV_V2I64:
16892   case X86::CMOV_V8F32:
16893   case X86::CMOV_V4F64:
16894   case X86::CMOV_V4I64:
16895   case X86::CMOV_V16F32:
16896   case X86::CMOV_V8F64:
16897   case X86::CMOV_V8I64:
16898   case X86::CMOV_GR16:
16899   case X86::CMOV_GR32:
16900   case X86::CMOV_RFP32:
16901   case X86::CMOV_RFP64:
16902   case X86::CMOV_RFP80:
16903     return EmitLoweredSelect(MI, BB);
16904
16905   case X86::FP32_TO_INT16_IN_MEM:
16906   case X86::FP32_TO_INT32_IN_MEM:
16907   case X86::FP32_TO_INT64_IN_MEM:
16908   case X86::FP64_TO_INT16_IN_MEM:
16909   case X86::FP64_TO_INT32_IN_MEM:
16910   case X86::FP64_TO_INT64_IN_MEM:
16911   case X86::FP80_TO_INT16_IN_MEM:
16912   case X86::FP80_TO_INT32_IN_MEM:
16913   case X86::FP80_TO_INT64_IN_MEM: {
16914     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16915     DebugLoc DL = MI->getDebugLoc();
16916
16917     // Change the floating point control register to use "round towards zero"
16918     // mode when truncating to an integer value.
16919     MachineFunction *F = BB->getParent();
16920     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16921     addFrameReference(BuildMI(*BB, MI, DL,
16922                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16923
16924     // Load the old value of the high byte of the control word...
16925     unsigned OldCW =
16926       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16927     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16928                       CWFrameIdx);
16929
16930     // Set the high part to be round to zero...
16931     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16932       .addImm(0xC7F);
16933
16934     // Reload the modified control word now...
16935     addFrameReference(BuildMI(*BB, MI, DL,
16936                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16937
16938     // Restore the memory image of control word to original value
16939     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16940       .addReg(OldCW);
16941
16942     // Get the X86 opcode to use.
16943     unsigned Opc;
16944     switch (MI->getOpcode()) {
16945     default: llvm_unreachable("illegal opcode!");
16946     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16947     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16948     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16949     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16950     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16951     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16952     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16953     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16954     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16955     }
16956
16957     X86AddressMode AM;
16958     MachineOperand &Op = MI->getOperand(0);
16959     if (Op.isReg()) {
16960       AM.BaseType = X86AddressMode::RegBase;
16961       AM.Base.Reg = Op.getReg();
16962     } else {
16963       AM.BaseType = X86AddressMode::FrameIndexBase;
16964       AM.Base.FrameIndex = Op.getIndex();
16965     }
16966     Op = MI->getOperand(1);
16967     if (Op.isImm())
16968       AM.Scale = Op.getImm();
16969     Op = MI->getOperand(2);
16970     if (Op.isImm())
16971       AM.IndexReg = Op.getImm();
16972     Op = MI->getOperand(3);
16973     if (Op.isGlobal()) {
16974       AM.GV = Op.getGlobal();
16975     } else {
16976       AM.Disp = Op.getImm();
16977     }
16978     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16979                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16980
16981     // Reload the original control word now.
16982     addFrameReference(BuildMI(*BB, MI, DL,
16983                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16984
16985     MI->eraseFromParent();   // The pseudo instruction is gone now.
16986     return BB;
16987   }
16988     // String/text processing lowering.
16989   case X86::PCMPISTRM128REG:
16990   case X86::VPCMPISTRM128REG:
16991   case X86::PCMPISTRM128MEM:
16992   case X86::VPCMPISTRM128MEM:
16993   case X86::PCMPESTRM128REG:
16994   case X86::VPCMPESTRM128REG:
16995   case X86::PCMPESTRM128MEM:
16996   case X86::VPCMPESTRM128MEM:
16997     assert(Subtarget->hasSSE42() &&
16998            "Target must have SSE4.2 or AVX features enabled");
16999     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17000
17001   // String/text processing lowering.
17002   case X86::PCMPISTRIREG:
17003   case X86::VPCMPISTRIREG:
17004   case X86::PCMPISTRIMEM:
17005   case X86::VPCMPISTRIMEM:
17006   case X86::PCMPESTRIREG:
17007   case X86::VPCMPESTRIREG:
17008   case X86::PCMPESTRIMEM:
17009   case X86::VPCMPESTRIMEM:
17010     assert(Subtarget->hasSSE42() &&
17011            "Target must have SSE4.2 or AVX features enabled");
17012     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17013
17014   // Thread synchronization.
17015   case X86::MONITOR:
17016     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17017
17018   // xbegin
17019   case X86::XBEGIN:
17020     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17021
17022   // Atomic Lowering.
17023   case X86::ATOMAND8:
17024   case X86::ATOMAND16:
17025   case X86::ATOMAND32:
17026   case X86::ATOMAND64:
17027     // Fall through
17028   case X86::ATOMOR8:
17029   case X86::ATOMOR16:
17030   case X86::ATOMOR32:
17031   case X86::ATOMOR64:
17032     // Fall through
17033   case X86::ATOMXOR16:
17034   case X86::ATOMXOR8:
17035   case X86::ATOMXOR32:
17036   case X86::ATOMXOR64:
17037     // Fall through
17038   case X86::ATOMNAND8:
17039   case X86::ATOMNAND16:
17040   case X86::ATOMNAND32:
17041   case X86::ATOMNAND64:
17042     // Fall through
17043   case X86::ATOMMAX8:
17044   case X86::ATOMMAX16:
17045   case X86::ATOMMAX32:
17046   case X86::ATOMMAX64:
17047     // Fall through
17048   case X86::ATOMMIN8:
17049   case X86::ATOMMIN16:
17050   case X86::ATOMMIN32:
17051   case X86::ATOMMIN64:
17052     // Fall through
17053   case X86::ATOMUMAX8:
17054   case X86::ATOMUMAX16:
17055   case X86::ATOMUMAX32:
17056   case X86::ATOMUMAX64:
17057     // Fall through
17058   case X86::ATOMUMIN8:
17059   case X86::ATOMUMIN16:
17060   case X86::ATOMUMIN32:
17061   case X86::ATOMUMIN64:
17062     return EmitAtomicLoadArith(MI, BB);
17063
17064   // This group does 64-bit operations on a 32-bit host.
17065   case X86::ATOMAND6432:
17066   case X86::ATOMOR6432:
17067   case X86::ATOMXOR6432:
17068   case X86::ATOMNAND6432:
17069   case X86::ATOMADD6432:
17070   case X86::ATOMSUB6432:
17071   case X86::ATOMMAX6432:
17072   case X86::ATOMMIN6432:
17073   case X86::ATOMUMAX6432:
17074   case X86::ATOMUMIN6432:
17075   case X86::ATOMSWAP6432:
17076     return EmitAtomicLoadArith6432(MI, BB);
17077
17078   case X86::VASTART_SAVE_XMM_REGS:
17079     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17080
17081   case X86::VAARG_64:
17082     return EmitVAARG64WithCustomInserter(MI, BB);
17083
17084   case X86::EH_SjLj_SetJmp32:
17085   case X86::EH_SjLj_SetJmp64:
17086     return emitEHSjLjSetJmp(MI, BB);
17087
17088   case X86::EH_SjLj_LongJmp32:
17089   case X86::EH_SjLj_LongJmp64:
17090     return emitEHSjLjLongJmp(MI, BB);
17091
17092   case TargetOpcode::STACKMAP:
17093   case TargetOpcode::PATCHPOINT:
17094     return emitPatchPoint(MI, BB);
17095
17096   case X86::VFMADDPDr213r:
17097   case X86::VFMADDPSr213r:
17098   case X86::VFMADDSDr213r:
17099   case X86::VFMADDSSr213r:
17100   case X86::VFMSUBPDr213r:
17101   case X86::VFMSUBPSr213r:
17102   case X86::VFMSUBSDr213r:
17103   case X86::VFMSUBSSr213r:
17104   case X86::VFNMADDPDr213r:
17105   case X86::VFNMADDPSr213r:
17106   case X86::VFNMADDSDr213r:
17107   case X86::VFNMADDSSr213r:
17108   case X86::VFNMSUBPDr213r:
17109   case X86::VFNMSUBPSr213r:
17110   case X86::VFNMSUBSDr213r:
17111   case X86::VFNMSUBSSr213r:
17112   case X86::VFMADDPDr213rY:
17113   case X86::VFMADDPSr213rY:
17114   case X86::VFMSUBPDr213rY:
17115   case X86::VFMSUBPSr213rY:
17116   case X86::VFNMADDPDr213rY:
17117   case X86::VFNMADDPSr213rY:
17118   case X86::VFNMSUBPDr213rY:
17119   case X86::VFNMSUBPSr213rY:
17120     return emitFMA3Instr(MI, BB);
17121   }
17122 }
17123
17124 //===----------------------------------------------------------------------===//
17125 //                           X86 Optimization Hooks
17126 //===----------------------------------------------------------------------===//
17127
17128 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
17129                                                        APInt &KnownZero,
17130                                                        APInt &KnownOne,
17131                                                        const SelectionDAG &DAG,
17132                                                        unsigned Depth) const {
17133   unsigned BitWidth = KnownZero.getBitWidth();
17134   unsigned Opc = Op.getOpcode();
17135   assert((Opc >= ISD::BUILTIN_OP_END ||
17136           Opc == ISD::INTRINSIC_WO_CHAIN ||
17137           Opc == ISD::INTRINSIC_W_CHAIN ||
17138           Opc == ISD::INTRINSIC_VOID) &&
17139          "Should use MaskedValueIsZero if you don't know whether Op"
17140          " is a target node!");
17141
17142   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17143   switch (Opc) {
17144   default: break;
17145   case X86ISD::ADD:
17146   case X86ISD::SUB:
17147   case X86ISD::ADC:
17148   case X86ISD::SBB:
17149   case X86ISD::SMUL:
17150   case X86ISD::UMUL:
17151   case X86ISD::INC:
17152   case X86ISD::DEC:
17153   case X86ISD::OR:
17154   case X86ISD::XOR:
17155   case X86ISD::AND:
17156     // These nodes' second result is a boolean.
17157     if (Op.getResNo() == 0)
17158       break;
17159     // Fallthrough
17160   case X86ISD::SETCC:
17161     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17162     break;
17163   case ISD::INTRINSIC_WO_CHAIN: {
17164     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17165     unsigned NumLoBits = 0;
17166     switch (IntId) {
17167     default: break;
17168     case Intrinsic::x86_sse_movmsk_ps:
17169     case Intrinsic::x86_avx_movmsk_ps_256:
17170     case Intrinsic::x86_sse2_movmsk_pd:
17171     case Intrinsic::x86_avx_movmsk_pd_256:
17172     case Intrinsic::x86_mmx_pmovmskb:
17173     case Intrinsic::x86_sse2_pmovmskb_128:
17174     case Intrinsic::x86_avx2_pmovmskb: {
17175       // High bits of movmskp{s|d}, pmovmskb are known zero.
17176       switch (IntId) {
17177         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17178         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17179         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17180         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17181         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17182         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17183         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17184         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17185       }
17186       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17187       break;
17188     }
17189     }
17190     break;
17191   }
17192   }
17193 }
17194
17195 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17196   SDValue Op,
17197   const SelectionDAG &,
17198   unsigned Depth) const {
17199   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17200   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17201     return Op.getValueType().getScalarType().getSizeInBits();
17202
17203   // Fallback case.
17204   return 1;
17205 }
17206
17207 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17208 /// node is a GlobalAddress + offset.
17209 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17210                                        const GlobalValue* &GA,
17211                                        int64_t &Offset) const {
17212   if (N->getOpcode() == X86ISD::Wrapper) {
17213     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17214       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17215       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17216       return true;
17217     }
17218   }
17219   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17220 }
17221
17222 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17223 /// same as extracting the high 128-bit part of 256-bit vector and then
17224 /// inserting the result into the low part of a new 256-bit vector
17225 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17226   EVT VT = SVOp->getValueType(0);
17227   unsigned NumElems = VT.getVectorNumElements();
17228
17229   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17230   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17231     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17232         SVOp->getMaskElt(j) >= 0)
17233       return false;
17234
17235   return true;
17236 }
17237
17238 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17239 /// same as extracting the low 128-bit part of 256-bit vector and then
17240 /// inserting the result into the high part of a new 256-bit vector
17241 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17242   EVT VT = SVOp->getValueType(0);
17243   unsigned NumElems = VT.getVectorNumElements();
17244
17245   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17246   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17247     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17248         SVOp->getMaskElt(j) >= 0)
17249       return false;
17250
17251   return true;
17252 }
17253
17254 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17255 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17256                                         TargetLowering::DAGCombinerInfo &DCI,
17257                                         const X86Subtarget* Subtarget) {
17258   SDLoc dl(N);
17259   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17260   SDValue V1 = SVOp->getOperand(0);
17261   SDValue V2 = SVOp->getOperand(1);
17262   EVT VT = SVOp->getValueType(0);
17263   unsigned NumElems = VT.getVectorNumElements();
17264
17265   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17266       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17267     //
17268     //                   0,0,0,...
17269     //                      |
17270     //    V      UNDEF    BUILD_VECTOR    UNDEF
17271     //     \      /           \           /
17272     //  CONCAT_VECTOR         CONCAT_VECTOR
17273     //         \                  /
17274     //          \                /
17275     //          RESULT: V + zero extended
17276     //
17277     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17278         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17279         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17280       return SDValue();
17281
17282     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17283       return SDValue();
17284
17285     // To match the shuffle mask, the first half of the mask should
17286     // be exactly the first vector, and all the rest a splat with the
17287     // first element of the second one.
17288     for (unsigned i = 0; i != NumElems/2; ++i)
17289       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17290           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17291         return SDValue();
17292
17293     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17294     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17295       if (Ld->hasNUsesOfValue(1, 0)) {
17296         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17297         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17298         SDValue ResNode =
17299           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17300                                   Ld->getMemoryVT(),
17301                                   Ld->getPointerInfo(),
17302                                   Ld->getAlignment(),
17303                                   false/*isVolatile*/, true/*ReadMem*/,
17304                                   false/*WriteMem*/);
17305
17306         // Make sure the newly-created LOAD is in the same position as Ld in
17307         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17308         // and update uses of Ld's output chain to use the TokenFactor.
17309         if (Ld->hasAnyUseOfValue(1)) {
17310           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17311                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17312           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17313           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17314                                  SDValue(ResNode.getNode(), 1));
17315         }
17316
17317         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17318       }
17319     }
17320
17321     // Emit a zeroed vector and insert the desired subvector on its
17322     // first half.
17323     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17324     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17325     return DCI.CombineTo(N, InsV);
17326   }
17327
17328   //===--------------------------------------------------------------------===//
17329   // Combine some shuffles into subvector extracts and inserts:
17330   //
17331
17332   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17333   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17334     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17335     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17336     return DCI.CombineTo(N, InsV);
17337   }
17338
17339   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17340   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17341     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17342     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17343     return DCI.CombineTo(N, InsV);
17344   }
17345
17346   return SDValue();
17347 }
17348
17349 /// PerformShuffleCombine - Performs several different shuffle combines.
17350 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17351                                      TargetLowering::DAGCombinerInfo &DCI,
17352                                      const X86Subtarget *Subtarget) {
17353   SDLoc dl(N);
17354   EVT VT = N->getValueType(0);
17355
17356   // Don't create instructions with illegal types after legalize types has run.
17357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17358   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17359     return SDValue();
17360
17361   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17362   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17363       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17364     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17365
17366   // Only handle 128 wide vector from here on.
17367   if (!VT.is128BitVector())
17368     return SDValue();
17369
17370   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17371   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17372   // consecutive, non-overlapping, and in the right order.
17373   SmallVector<SDValue, 16> Elts;
17374   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17375     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17376
17377   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17378 }
17379
17380 /// PerformTruncateCombine - Converts truncate operation to
17381 /// a sequence of vector shuffle operations.
17382 /// It is possible when we truncate 256-bit vector to 128-bit vector
17383 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17384                                       TargetLowering::DAGCombinerInfo &DCI,
17385                                       const X86Subtarget *Subtarget)  {
17386   return SDValue();
17387 }
17388
17389 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17390 /// specific shuffle of a load can be folded into a single element load.
17391 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17392 /// shuffles have been customed lowered so we need to handle those here.
17393 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17394                                          TargetLowering::DAGCombinerInfo &DCI) {
17395   if (DCI.isBeforeLegalizeOps())
17396     return SDValue();
17397
17398   SDValue InVec = N->getOperand(0);
17399   SDValue EltNo = N->getOperand(1);
17400
17401   if (!isa<ConstantSDNode>(EltNo))
17402     return SDValue();
17403
17404   EVT VT = InVec.getValueType();
17405
17406   bool HasShuffleIntoBitcast = false;
17407   if (InVec.getOpcode() == ISD::BITCAST) {
17408     // Don't duplicate a load with other uses.
17409     if (!InVec.hasOneUse())
17410       return SDValue();
17411     EVT BCVT = InVec.getOperand(0).getValueType();
17412     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17413       return SDValue();
17414     InVec = InVec.getOperand(0);
17415     HasShuffleIntoBitcast = true;
17416   }
17417
17418   if (!isTargetShuffle(InVec.getOpcode()))
17419     return SDValue();
17420
17421   // Don't duplicate a load with other uses.
17422   if (!InVec.hasOneUse())
17423     return SDValue();
17424
17425   SmallVector<int, 16> ShuffleMask;
17426   bool UnaryShuffle;
17427   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17428                             UnaryShuffle))
17429     return SDValue();
17430
17431   // Select the input vector, guarding against out of range extract vector.
17432   unsigned NumElems = VT.getVectorNumElements();
17433   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17434   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17435   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17436                                          : InVec.getOperand(1);
17437
17438   // If inputs to shuffle are the same for both ops, then allow 2 uses
17439   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17440
17441   if (LdNode.getOpcode() == ISD::BITCAST) {
17442     // Don't duplicate a load with other uses.
17443     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17444       return SDValue();
17445
17446     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17447     LdNode = LdNode.getOperand(0);
17448   }
17449
17450   if (!ISD::isNormalLoad(LdNode.getNode()))
17451     return SDValue();
17452
17453   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17454
17455   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17456     return SDValue();
17457
17458   if (HasShuffleIntoBitcast) {
17459     // If there's a bitcast before the shuffle, check if the load type and
17460     // alignment is valid.
17461     unsigned Align = LN0->getAlignment();
17462     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17463     unsigned NewAlign = TLI.getDataLayout()->
17464       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17465
17466     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17467       return SDValue();
17468   }
17469
17470   // All checks match so transform back to vector_shuffle so that DAG combiner
17471   // can finish the job
17472   SDLoc dl(N);
17473
17474   // Create shuffle node taking into account the case that its a unary shuffle
17475   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17476   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17477                                  InVec.getOperand(0), Shuffle,
17478                                  &ShuffleMask[0]);
17479   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17480   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17481                      EltNo);
17482 }
17483
17484 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17485 /// generation and convert it from being a bunch of shuffles and extracts
17486 /// to a simple store and scalar loads to extract the elements.
17487 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17488                                          TargetLowering::DAGCombinerInfo &DCI) {
17489   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17490   if (NewOp.getNode())
17491     return NewOp;
17492
17493   SDValue InputVector = N->getOperand(0);
17494
17495   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17496   // from mmx to v2i32 has a single usage.
17497   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17498       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17499       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17500     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17501                        N->getValueType(0),
17502                        InputVector.getNode()->getOperand(0));
17503
17504   // Only operate on vectors of 4 elements, where the alternative shuffling
17505   // gets to be more expensive.
17506   if (InputVector.getValueType() != MVT::v4i32)
17507     return SDValue();
17508
17509   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17510   // single use which is a sign-extend or zero-extend, and all elements are
17511   // used.
17512   SmallVector<SDNode *, 4> Uses;
17513   unsigned ExtractedElements = 0;
17514   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17515        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17516     if (UI.getUse().getResNo() != InputVector.getResNo())
17517       return SDValue();
17518
17519     SDNode *Extract = *UI;
17520     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17521       return SDValue();
17522
17523     if (Extract->getValueType(0) != MVT::i32)
17524       return SDValue();
17525     if (!Extract->hasOneUse())
17526       return SDValue();
17527     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17528         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17529       return SDValue();
17530     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17531       return SDValue();
17532
17533     // Record which element was extracted.
17534     ExtractedElements |=
17535       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17536
17537     Uses.push_back(Extract);
17538   }
17539
17540   // If not all the elements were used, this may not be worthwhile.
17541   if (ExtractedElements != 15)
17542     return SDValue();
17543
17544   // Ok, we've now decided to do the transformation.
17545   SDLoc dl(InputVector);
17546
17547   // Store the value to a temporary stack slot.
17548   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17549   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17550                             MachinePointerInfo(), false, false, 0);
17551
17552   // Replace each use (extract) with a load of the appropriate element.
17553   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17554        UE = Uses.end(); UI != UE; ++UI) {
17555     SDNode *Extract = *UI;
17556
17557     // cOMpute the element's address.
17558     SDValue Idx = Extract->getOperand(1);
17559     unsigned EltSize =
17560         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17561     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17562     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17563     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17564
17565     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17566                                      StackPtr, OffsetVal);
17567
17568     // Load the scalar.
17569     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17570                                      ScalarAddr, MachinePointerInfo(),
17571                                      false, false, false, 0);
17572
17573     // Replace the exact with the load.
17574     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17575   }
17576
17577   // The replacement was made in place; don't return anything.
17578   return SDValue();
17579 }
17580
17581 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17582 static std::pair<unsigned, bool>
17583 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17584                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17585   if (!VT.isVector())
17586     return std::make_pair(0, false);
17587
17588   bool NeedSplit = false;
17589   switch (VT.getSimpleVT().SimpleTy) {
17590   default: return std::make_pair(0, false);
17591   case MVT::v32i8:
17592   case MVT::v16i16:
17593   case MVT::v8i32:
17594     if (!Subtarget->hasAVX2())
17595       NeedSplit = true;
17596     if (!Subtarget->hasAVX())
17597       return std::make_pair(0, false);
17598     break;
17599   case MVT::v16i8:
17600   case MVT::v8i16:
17601   case MVT::v4i32:
17602     if (!Subtarget->hasSSE2())
17603       return std::make_pair(0, false);
17604   }
17605
17606   // SSE2 has only a small subset of the operations.
17607   bool hasUnsigned = Subtarget->hasSSE41() ||
17608                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17609   bool hasSigned = Subtarget->hasSSE41() ||
17610                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17611
17612   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17613
17614   unsigned Opc = 0;
17615   // Check for x CC y ? x : y.
17616   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17617       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17618     switch (CC) {
17619     default: break;
17620     case ISD::SETULT:
17621     case ISD::SETULE:
17622       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17623     case ISD::SETUGT:
17624     case ISD::SETUGE:
17625       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17626     case ISD::SETLT:
17627     case ISD::SETLE:
17628       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17629     case ISD::SETGT:
17630     case ISD::SETGE:
17631       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17632     }
17633   // Check for x CC y ? y : x -- a min/max with reversed arms.
17634   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17635              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17636     switch (CC) {
17637     default: break;
17638     case ISD::SETULT:
17639     case ISD::SETULE:
17640       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17641     case ISD::SETUGT:
17642     case ISD::SETUGE:
17643       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17644     case ISD::SETLT:
17645     case ISD::SETLE:
17646       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17647     case ISD::SETGT:
17648     case ISD::SETGE:
17649       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17650     }
17651   }
17652
17653   return std::make_pair(Opc, NeedSplit);
17654 }
17655
17656 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17657 /// nodes.
17658 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17659                                     TargetLowering::DAGCombinerInfo &DCI,
17660                                     const X86Subtarget *Subtarget) {
17661   SDLoc DL(N);
17662   SDValue Cond = N->getOperand(0);
17663   // Get the LHS/RHS of the select.
17664   SDValue LHS = N->getOperand(1);
17665   SDValue RHS = N->getOperand(2);
17666   EVT VT = LHS.getValueType();
17667   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17668
17669   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17670   // instructions match the semantics of the common C idiom x<y?x:y but not
17671   // x<=y?x:y, because of how they handle negative zero (which can be
17672   // ignored in unsafe-math mode).
17673   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17674       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17675       (Subtarget->hasSSE2() ||
17676        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17677     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17678
17679     unsigned Opcode = 0;
17680     // Check for x CC y ? x : y.
17681     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17682         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17683       switch (CC) {
17684       default: break;
17685       case ISD::SETULT:
17686         // Converting this to a min would handle NaNs incorrectly, and swapping
17687         // the operands would cause it to handle comparisons between positive
17688         // and negative zero incorrectly.
17689         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17690           if (!DAG.getTarget().Options.UnsafeFPMath &&
17691               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17692             break;
17693           std::swap(LHS, RHS);
17694         }
17695         Opcode = X86ISD::FMIN;
17696         break;
17697       case ISD::SETOLE:
17698         // Converting this to a min would handle comparisons between positive
17699         // and negative zero incorrectly.
17700         if (!DAG.getTarget().Options.UnsafeFPMath &&
17701             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17702           break;
17703         Opcode = X86ISD::FMIN;
17704         break;
17705       case ISD::SETULE:
17706         // Converting this to a min would handle both negative zeros and NaNs
17707         // incorrectly, but we can swap the operands to fix both.
17708         std::swap(LHS, RHS);
17709       case ISD::SETOLT:
17710       case ISD::SETLT:
17711       case ISD::SETLE:
17712         Opcode = X86ISD::FMIN;
17713         break;
17714
17715       case ISD::SETOGE:
17716         // Converting this to a max would handle comparisons between positive
17717         // and negative zero incorrectly.
17718         if (!DAG.getTarget().Options.UnsafeFPMath &&
17719             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17720           break;
17721         Opcode = X86ISD::FMAX;
17722         break;
17723       case ISD::SETUGT:
17724         // Converting this to a max would handle NaNs incorrectly, and swapping
17725         // the operands would cause it to handle comparisons between positive
17726         // and negative zero incorrectly.
17727         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17728           if (!DAG.getTarget().Options.UnsafeFPMath &&
17729               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17730             break;
17731           std::swap(LHS, RHS);
17732         }
17733         Opcode = X86ISD::FMAX;
17734         break;
17735       case ISD::SETUGE:
17736         // Converting this to a max would handle both negative zeros and NaNs
17737         // incorrectly, but we can swap the operands to fix both.
17738         std::swap(LHS, RHS);
17739       case ISD::SETOGT:
17740       case ISD::SETGT:
17741       case ISD::SETGE:
17742         Opcode = X86ISD::FMAX;
17743         break;
17744       }
17745     // Check for x CC y ? y : x -- a min/max with reversed arms.
17746     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17747                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17748       switch (CC) {
17749       default: break;
17750       case ISD::SETOGE:
17751         // Converting this to a min would handle comparisons between positive
17752         // and negative zero incorrectly, and swapping the operands would
17753         // cause it to handle NaNs incorrectly.
17754         if (!DAG.getTarget().Options.UnsafeFPMath &&
17755             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17756           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17757             break;
17758           std::swap(LHS, RHS);
17759         }
17760         Opcode = X86ISD::FMIN;
17761         break;
17762       case ISD::SETUGT:
17763         // Converting this to a min would handle NaNs incorrectly.
17764         if (!DAG.getTarget().Options.UnsafeFPMath &&
17765             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17766           break;
17767         Opcode = X86ISD::FMIN;
17768         break;
17769       case ISD::SETUGE:
17770         // Converting this to a min would handle both negative zeros and NaNs
17771         // incorrectly, but we can swap the operands to fix both.
17772         std::swap(LHS, RHS);
17773       case ISD::SETOGT:
17774       case ISD::SETGT:
17775       case ISD::SETGE:
17776         Opcode = X86ISD::FMIN;
17777         break;
17778
17779       case ISD::SETULT:
17780         // Converting this to a max would handle NaNs incorrectly.
17781         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17782           break;
17783         Opcode = X86ISD::FMAX;
17784         break;
17785       case ISD::SETOLE:
17786         // Converting this to a max would handle comparisons between positive
17787         // and negative zero incorrectly, and swapping the operands would
17788         // cause it to handle NaNs incorrectly.
17789         if (!DAG.getTarget().Options.UnsafeFPMath &&
17790             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17791           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17792             break;
17793           std::swap(LHS, RHS);
17794         }
17795         Opcode = X86ISD::FMAX;
17796         break;
17797       case ISD::SETULE:
17798         // Converting this to a max would handle both negative zeros and NaNs
17799         // incorrectly, but we can swap the operands to fix both.
17800         std::swap(LHS, RHS);
17801       case ISD::SETOLT:
17802       case ISD::SETLT:
17803       case ISD::SETLE:
17804         Opcode = X86ISD::FMAX;
17805         break;
17806       }
17807     }
17808
17809     if (Opcode)
17810       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17811   }
17812
17813   EVT CondVT = Cond.getValueType();
17814   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17815       CondVT.getVectorElementType() == MVT::i1) {
17816     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17817     // lowering on AVX-512. In this case we convert it to
17818     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17819     // The same situation for all 128 and 256-bit vectors of i8 and i16
17820     EVT OpVT = LHS.getValueType();
17821     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17822         (OpVT.getVectorElementType() == MVT::i8 ||
17823          OpVT.getVectorElementType() == MVT::i16)) {
17824       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17825       DCI.AddToWorklist(Cond.getNode());
17826       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17827     }
17828   }
17829   // If this is a select between two integer constants, try to do some
17830   // optimizations.
17831   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17832     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17833       // Don't do this for crazy integer types.
17834       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17835         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17836         // so that TrueC (the true value) is larger than FalseC.
17837         bool NeedsCondInvert = false;
17838
17839         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17840             // Efficiently invertible.
17841             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17842              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17843               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17844           NeedsCondInvert = true;
17845           std::swap(TrueC, FalseC);
17846         }
17847
17848         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17849         if (FalseC->getAPIntValue() == 0 &&
17850             TrueC->getAPIntValue().isPowerOf2()) {
17851           if (NeedsCondInvert) // Invert the condition if needed.
17852             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17853                                DAG.getConstant(1, Cond.getValueType()));
17854
17855           // Zero extend the condition if needed.
17856           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17857
17858           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17859           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17860                              DAG.getConstant(ShAmt, MVT::i8));
17861         }
17862
17863         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17864         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17865           if (NeedsCondInvert) // Invert the condition if needed.
17866             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17867                                DAG.getConstant(1, Cond.getValueType()));
17868
17869           // Zero extend the condition if needed.
17870           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17871                              FalseC->getValueType(0), Cond);
17872           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17873                              SDValue(FalseC, 0));
17874         }
17875
17876         // Optimize cases that will turn into an LEA instruction.  This requires
17877         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17878         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17879           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17880           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17881
17882           bool isFastMultiplier = false;
17883           if (Diff < 10) {
17884             switch ((unsigned char)Diff) {
17885               default: break;
17886               case 1:  // result = add base, cond
17887               case 2:  // result = lea base(    , cond*2)
17888               case 3:  // result = lea base(cond, cond*2)
17889               case 4:  // result = lea base(    , cond*4)
17890               case 5:  // result = lea base(cond, cond*4)
17891               case 8:  // result = lea base(    , cond*8)
17892               case 9:  // result = lea base(cond, cond*8)
17893                 isFastMultiplier = true;
17894                 break;
17895             }
17896           }
17897
17898           if (isFastMultiplier) {
17899             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17900             if (NeedsCondInvert) // Invert the condition if needed.
17901               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17902                                  DAG.getConstant(1, Cond.getValueType()));
17903
17904             // Zero extend the condition if needed.
17905             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17906                                Cond);
17907             // Scale the condition by the difference.
17908             if (Diff != 1)
17909               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17910                                  DAG.getConstant(Diff, Cond.getValueType()));
17911
17912             // Add the base if non-zero.
17913             if (FalseC->getAPIntValue() != 0)
17914               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17915                                  SDValue(FalseC, 0));
17916             return Cond;
17917           }
17918         }
17919       }
17920   }
17921
17922   // Canonicalize max and min:
17923   // (x > y) ? x : y -> (x >= y) ? x : y
17924   // (x < y) ? x : y -> (x <= y) ? x : y
17925   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17926   // the need for an extra compare
17927   // against zero. e.g.
17928   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17929   // subl   %esi, %edi
17930   // testl  %edi, %edi
17931   // movl   $0, %eax
17932   // cmovgl %edi, %eax
17933   // =>
17934   // xorl   %eax, %eax
17935   // subl   %esi, $edi
17936   // cmovsl %eax, %edi
17937   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17938       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17939       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17940     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17941     switch (CC) {
17942     default: break;
17943     case ISD::SETLT:
17944     case ISD::SETGT: {
17945       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17946       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17947                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17948       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17949     }
17950     }
17951   }
17952
17953   // Early exit check
17954   if (!TLI.isTypeLegal(VT))
17955     return SDValue();
17956
17957   // Match VSELECTs into subs with unsigned saturation.
17958   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17959       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17960       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17961        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17962     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17963
17964     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17965     // left side invert the predicate to simplify logic below.
17966     SDValue Other;
17967     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17968       Other = RHS;
17969       CC = ISD::getSetCCInverse(CC, true);
17970     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17971       Other = LHS;
17972     }
17973
17974     if (Other.getNode() && Other->getNumOperands() == 2 &&
17975         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17976       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17977       SDValue CondRHS = Cond->getOperand(1);
17978
17979       // Look for a general sub with unsigned saturation first.
17980       // x >= y ? x-y : 0 --> subus x, y
17981       // x >  y ? x-y : 0 --> subus x, y
17982       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17983           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17984         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17985
17986       // If the RHS is a constant we have to reverse the const canonicalization.
17987       // x > C-1 ? x+-C : 0 --> subus x, C
17988       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17989           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17990         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17991         if (CondRHS.getConstantOperandVal(0) == -A-1)
17992           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17993                              DAG.getConstant(-A, VT));
17994       }
17995
17996       // Another special case: If C was a sign bit, the sub has been
17997       // canonicalized into a xor.
17998       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17999       //        it's safe to decanonicalize the xor?
18000       // x s< 0 ? x^C : 0 --> subus x, C
18001       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18002           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18003           isSplatVector(OpRHS.getNode())) {
18004         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18005         if (A.isSignBit())
18006           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18007       }
18008     }
18009   }
18010
18011   // Try to match a min/max vector operation.
18012   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18013     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18014     unsigned Opc = ret.first;
18015     bool NeedSplit = ret.second;
18016
18017     if (Opc && NeedSplit) {
18018       unsigned NumElems = VT.getVectorNumElements();
18019       // Extract the LHS vectors
18020       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18021       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18022
18023       // Extract the RHS vectors
18024       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18025       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18026
18027       // Create min/max for each subvector
18028       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18029       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18030
18031       // Merge the result
18032       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18033     } else if (Opc)
18034       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18035   }
18036
18037   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18038   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18039       // Check if SETCC has already been promoted
18040       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18041       // Check that condition value type matches vselect operand type
18042       CondVT == VT) { 
18043
18044     assert(Cond.getValueType().isVector() &&
18045            "vector select expects a vector selector!");
18046
18047     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18048     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18049
18050     if (!TValIsAllOnes && !FValIsAllZeros) {
18051       // Try invert the condition if true value is not all 1s and false value
18052       // is not all 0s.
18053       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18054       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18055
18056       if (TValIsAllZeros || FValIsAllOnes) {
18057         SDValue CC = Cond.getOperand(2);
18058         ISD::CondCode NewCC =
18059           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18060                                Cond.getOperand(0).getValueType().isInteger());
18061         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18062         std::swap(LHS, RHS);
18063         TValIsAllOnes = FValIsAllOnes;
18064         FValIsAllZeros = TValIsAllZeros;
18065       }
18066     }
18067
18068     if (TValIsAllOnes || FValIsAllZeros) {
18069       SDValue Ret;
18070
18071       if (TValIsAllOnes && FValIsAllZeros)
18072         Ret = Cond;
18073       else if (TValIsAllOnes)
18074         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18075                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18076       else if (FValIsAllZeros)
18077         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18078                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18079
18080       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18081     }
18082   }
18083
18084   // Try to fold this VSELECT into a MOVSS/MOVSD
18085   if (N->getOpcode() == ISD::VSELECT &&
18086       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18087     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18088         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18089       bool CanFold = false;
18090       unsigned NumElems = Cond.getNumOperands();
18091       SDValue A = LHS;
18092       SDValue B = RHS;
18093       
18094       if (isZero(Cond.getOperand(0))) {
18095         CanFold = true;
18096
18097         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18098         // fold (vselect <0,-1> -> (movsd A, B)
18099         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18100           CanFold = isAllOnes(Cond.getOperand(i));
18101       } else if (isAllOnes(Cond.getOperand(0))) {
18102         CanFold = true;
18103         std::swap(A, B);
18104
18105         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18106         // fold (vselect <-1,0> -> (movsd B, A)
18107         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18108           CanFold = isZero(Cond.getOperand(i));
18109       }
18110
18111       if (CanFold) {
18112         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18113           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18114         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18115       }
18116
18117       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18118         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18119         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18120         //                             (v2i64 (bitcast B)))))
18121         //
18122         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18123         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18124         //                             (v2f64 (bitcast B)))))
18125         //
18126         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18127         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18128         //                             (v2i64 (bitcast A)))))
18129         //
18130         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18131         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18132         //                             (v2f64 (bitcast A)))))
18133
18134         CanFold = (isZero(Cond.getOperand(0)) &&
18135                    isZero(Cond.getOperand(1)) &&
18136                    isAllOnes(Cond.getOperand(2)) &&
18137                    isAllOnes(Cond.getOperand(3)));
18138
18139         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18140             isAllOnes(Cond.getOperand(1)) &&
18141             isZero(Cond.getOperand(2)) &&
18142             isZero(Cond.getOperand(3))) {
18143           CanFold = true;
18144           std::swap(LHS, RHS);
18145         }
18146
18147         if (CanFold) {
18148           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18149           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18150           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18151           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18152                                                 NewB, DAG);
18153           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18154         }
18155       }
18156     }
18157   }
18158
18159   // If we know that this node is legal then we know that it is going to be
18160   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18161   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18162   // to simplify previous instructions.
18163   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18164       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
18165     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18166
18167     // Don't optimize vector selects that map to mask-registers.
18168     if (BitWidth == 1)
18169       return SDValue();
18170
18171     // Check all uses of that condition operand to check whether it will be
18172     // consumed by non-BLEND instructions, which may depend on all bits are set
18173     // properly.
18174     for (SDNode::use_iterator I = Cond->use_begin(),
18175                               E = Cond->use_end(); I != E; ++I)
18176       if (I->getOpcode() != ISD::VSELECT)
18177         // TODO: Add other opcodes eventually lowered into BLEND.
18178         return SDValue();
18179
18180     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18181     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18182
18183     APInt KnownZero, KnownOne;
18184     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18185                                           DCI.isBeforeLegalizeOps());
18186     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18187         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18188       DCI.CommitTargetLoweringOpt(TLO);
18189   }
18190
18191   return SDValue();
18192 }
18193
18194 // Check whether a boolean test is testing a boolean value generated by
18195 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18196 // code.
18197 //
18198 // Simplify the following patterns:
18199 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18200 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18201 // to (Op EFLAGS Cond)
18202 //
18203 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18204 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18205 // to (Op EFLAGS !Cond)
18206 //
18207 // where Op could be BRCOND or CMOV.
18208 //
18209 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18210   // Quit if not CMP and SUB with its value result used.
18211   if (Cmp.getOpcode() != X86ISD::CMP &&
18212       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18213       return SDValue();
18214
18215   // Quit if not used as a boolean value.
18216   if (CC != X86::COND_E && CC != X86::COND_NE)
18217     return SDValue();
18218
18219   // Check CMP operands. One of them should be 0 or 1 and the other should be
18220   // an SetCC or extended from it.
18221   SDValue Op1 = Cmp.getOperand(0);
18222   SDValue Op2 = Cmp.getOperand(1);
18223
18224   SDValue SetCC;
18225   const ConstantSDNode* C = nullptr;
18226   bool needOppositeCond = (CC == X86::COND_E);
18227   bool checkAgainstTrue = false; // Is it a comparison against 1?
18228
18229   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18230     SetCC = Op2;
18231   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18232     SetCC = Op1;
18233   else // Quit if all operands are not constants.
18234     return SDValue();
18235
18236   if (C->getZExtValue() == 1) {
18237     needOppositeCond = !needOppositeCond;
18238     checkAgainstTrue = true;
18239   } else if (C->getZExtValue() != 0)
18240     // Quit if the constant is neither 0 or 1.
18241     return SDValue();
18242
18243   bool truncatedToBoolWithAnd = false;
18244   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18245   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18246          SetCC.getOpcode() == ISD::TRUNCATE ||
18247          SetCC.getOpcode() == ISD::AND) {
18248     if (SetCC.getOpcode() == ISD::AND) {
18249       int OpIdx = -1;
18250       ConstantSDNode *CS;
18251       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18252           CS->getZExtValue() == 1)
18253         OpIdx = 1;
18254       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18255           CS->getZExtValue() == 1)
18256         OpIdx = 0;
18257       if (OpIdx == -1)
18258         break;
18259       SetCC = SetCC.getOperand(OpIdx);
18260       truncatedToBoolWithAnd = true;
18261     } else
18262       SetCC = SetCC.getOperand(0);
18263   }
18264
18265   switch (SetCC.getOpcode()) {
18266   case X86ISD::SETCC_CARRY:
18267     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18268     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18269     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18270     // truncated to i1 using 'and'.
18271     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18272       break;
18273     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18274            "Invalid use of SETCC_CARRY!");
18275     // FALL THROUGH
18276   case X86ISD::SETCC:
18277     // Set the condition code or opposite one if necessary.
18278     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18279     if (needOppositeCond)
18280       CC = X86::GetOppositeBranchCondition(CC);
18281     return SetCC.getOperand(1);
18282   case X86ISD::CMOV: {
18283     // Check whether false/true value has canonical one, i.e. 0 or 1.
18284     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18285     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18286     // Quit if true value is not a constant.
18287     if (!TVal)
18288       return SDValue();
18289     // Quit if false value is not a constant.
18290     if (!FVal) {
18291       SDValue Op = SetCC.getOperand(0);
18292       // Skip 'zext' or 'trunc' node.
18293       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18294           Op.getOpcode() == ISD::TRUNCATE)
18295         Op = Op.getOperand(0);
18296       // A special case for rdrand/rdseed, where 0 is set if false cond is
18297       // found.
18298       if ((Op.getOpcode() != X86ISD::RDRAND &&
18299            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18300         return SDValue();
18301     }
18302     // Quit if false value is not the constant 0 or 1.
18303     bool FValIsFalse = true;
18304     if (FVal && FVal->getZExtValue() != 0) {
18305       if (FVal->getZExtValue() != 1)
18306         return SDValue();
18307       // If FVal is 1, opposite cond is needed.
18308       needOppositeCond = !needOppositeCond;
18309       FValIsFalse = false;
18310     }
18311     // Quit if TVal is not the constant opposite of FVal.
18312     if (FValIsFalse && TVal->getZExtValue() != 1)
18313       return SDValue();
18314     if (!FValIsFalse && TVal->getZExtValue() != 0)
18315       return SDValue();
18316     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18317     if (needOppositeCond)
18318       CC = X86::GetOppositeBranchCondition(CC);
18319     return SetCC.getOperand(3);
18320   }
18321   }
18322
18323   return SDValue();
18324 }
18325
18326 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18327 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18328                                   TargetLowering::DAGCombinerInfo &DCI,
18329                                   const X86Subtarget *Subtarget) {
18330   SDLoc DL(N);
18331
18332   // If the flag operand isn't dead, don't touch this CMOV.
18333   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18334     return SDValue();
18335
18336   SDValue FalseOp = N->getOperand(0);
18337   SDValue TrueOp = N->getOperand(1);
18338   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18339   SDValue Cond = N->getOperand(3);
18340
18341   if (CC == X86::COND_E || CC == X86::COND_NE) {
18342     switch (Cond.getOpcode()) {
18343     default: break;
18344     case X86ISD::BSR:
18345     case X86ISD::BSF:
18346       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18347       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18348         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18349     }
18350   }
18351
18352   SDValue Flags;
18353
18354   Flags = checkBoolTestSetCCCombine(Cond, CC);
18355   if (Flags.getNode() &&
18356       // Extra check as FCMOV only supports a subset of X86 cond.
18357       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18358     SDValue Ops[] = { FalseOp, TrueOp,
18359                       DAG.getConstant(CC, MVT::i8), Flags };
18360     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18361   }
18362
18363   // If this is a select between two integer constants, try to do some
18364   // optimizations.  Note that the operands are ordered the opposite of SELECT
18365   // operands.
18366   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18367     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18368       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18369       // larger than FalseC (the false value).
18370       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18371         CC = X86::GetOppositeBranchCondition(CC);
18372         std::swap(TrueC, FalseC);
18373         std::swap(TrueOp, FalseOp);
18374       }
18375
18376       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18377       // This is efficient for any integer data type (including i8/i16) and
18378       // shift amount.
18379       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18380         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18381                            DAG.getConstant(CC, MVT::i8), Cond);
18382
18383         // Zero extend the condition if needed.
18384         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18385
18386         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18387         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18388                            DAG.getConstant(ShAmt, MVT::i8));
18389         if (N->getNumValues() == 2)  // Dead flag value?
18390           return DCI.CombineTo(N, Cond, SDValue());
18391         return Cond;
18392       }
18393
18394       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18395       // for any integer data type, including i8/i16.
18396       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18397         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18398                            DAG.getConstant(CC, MVT::i8), Cond);
18399
18400         // Zero extend the condition if needed.
18401         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18402                            FalseC->getValueType(0), Cond);
18403         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18404                            SDValue(FalseC, 0));
18405
18406         if (N->getNumValues() == 2)  // Dead flag value?
18407           return DCI.CombineTo(N, Cond, SDValue());
18408         return Cond;
18409       }
18410
18411       // Optimize cases that will turn into an LEA instruction.  This requires
18412       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18413       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18414         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18415         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18416
18417         bool isFastMultiplier = false;
18418         if (Diff < 10) {
18419           switch ((unsigned char)Diff) {
18420           default: break;
18421           case 1:  // result = add base, cond
18422           case 2:  // result = lea base(    , cond*2)
18423           case 3:  // result = lea base(cond, cond*2)
18424           case 4:  // result = lea base(    , cond*4)
18425           case 5:  // result = lea base(cond, cond*4)
18426           case 8:  // result = lea base(    , cond*8)
18427           case 9:  // result = lea base(cond, cond*8)
18428             isFastMultiplier = true;
18429             break;
18430           }
18431         }
18432
18433         if (isFastMultiplier) {
18434           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18435           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18436                              DAG.getConstant(CC, MVT::i8), Cond);
18437           // Zero extend the condition if needed.
18438           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18439                              Cond);
18440           // Scale the condition by the difference.
18441           if (Diff != 1)
18442             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18443                                DAG.getConstant(Diff, Cond.getValueType()));
18444
18445           // Add the base if non-zero.
18446           if (FalseC->getAPIntValue() != 0)
18447             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18448                                SDValue(FalseC, 0));
18449           if (N->getNumValues() == 2)  // Dead flag value?
18450             return DCI.CombineTo(N, Cond, SDValue());
18451           return Cond;
18452         }
18453       }
18454     }
18455   }
18456
18457   // Handle these cases:
18458   //   (select (x != c), e, c) -> select (x != c), e, x),
18459   //   (select (x == c), c, e) -> select (x == c), x, e)
18460   // where the c is an integer constant, and the "select" is the combination
18461   // of CMOV and CMP.
18462   //
18463   // The rationale for this change is that the conditional-move from a constant
18464   // needs two instructions, however, conditional-move from a register needs
18465   // only one instruction.
18466   //
18467   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18468   //  some instruction-combining opportunities. This opt needs to be
18469   //  postponed as late as possible.
18470   //
18471   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18472     // the DCI.xxxx conditions are provided to postpone the optimization as
18473     // late as possible.
18474
18475     ConstantSDNode *CmpAgainst = nullptr;
18476     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18477         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18478         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18479
18480       if (CC == X86::COND_NE &&
18481           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18482         CC = X86::GetOppositeBranchCondition(CC);
18483         std::swap(TrueOp, FalseOp);
18484       }
18485
18486       if (CC == X86::COND_E &&
18487           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18488         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18489                           DAG.getConstant(CC, MVT::i8), Cond };
18490         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18491       }
18492     }
18493   }
18494
18495   return SDValue();
18496 }
18497
18498 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG) {
18499   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18500   switch (IntNo) {
18501   default: return SDValue();
18502   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18503   case Intrinsic::x86_sse2_psrai_w:
18504   case Intrinsic::x86_sse2_psrai_d:
18505   case Intrinsic::x86_avx2_psrai_w:
18506   case Intrinsic::x86_avx2_psrai_d:
18507   case Intrinsic::x86_sse2_psra_w:
18508   case Intrinsic::x86_sse2_psra_d:
18509   case Intrinsic::x86_avx2_psra_w:
18510   case Intrinsic::x86_avx2_psra_d: {
18511     SDValue Op0 = N->getOperand(1);
18512     SDValue Op1 = N->getOperand(2);
18513     EVT VT = Op0.getValueType();
18514     assert(VT.isVector() && "Expected a vector type!");
18515
18516     if (isa<BuildVectorSDNode>(Op1))
18517       Op1 = Op1.getOperand(0);
18518
18519     if (!isa<ConstantSDNode>(Op1))
18520       return SDValue();
18521
18522     EVT SVT = VT.getVectorElementType();
18523     unsigned SVTBits = SVT.getSizeInBits();
18524
18525     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18526     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18527     uint64_t ShAmt = C.getZExtValue();
18528
18529     // Don't try to convert this shift into a ISD::SRA if the shift
18530     // count is bigger than or equal to the element size.
18531     if (ShAmt >= SVTBits)
18532       return SDValue();
18533
18534     // Trivial case: if the shift count is zero, then fold this
18535     // into the first operand.
18536     if (ShAmt == 0)
18537       return Op0;
18538
18539     // Replace this packed shift intrinsic with a target independent
18540     // shift dag node.
18541     SDValue Splat = DAG.getConstant(C, VT);
18542     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18543   }
18544   }
18545 }
18546
18547 /// PerformMulCombine - Optimize a single multiply with constant into two
18548 /// in order to implement it with two cheaper instructions, e.g.
18549 /// LEA + SHL, LEA + LEA.
18550 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18551                                  TargetLowering::DAGCombinerInfo &DCI) {
18552   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18553     return SDValue();
18554
18555   EVT VT = N->getValueType(0);
18556   if (VT != MVT::i64)
18557     return SDValue();
18558
18559   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18560   if (!C)
18561     return SDValue();
18562   uint64_t MulAmt = C->getZExtValue();
18563   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18564     return SDValue();
18565
18566   uint64_t MulAmt1 = 0;
18567   uint64_t MulAmt2 = 0;
18568   if ((MulAmt % 9) == 0) {
18569     MulAmt1 = 9;
18570     MulAmt2 = MulAmt / 9;
18571   } else if ((MulAmt % 5) == 0) {
18572     MulAmt1 = 5;
18573     MulAmt2 = MulAmt / 5;
18574   } else if ((MulAmt % 3) == 0) {
18575     MulAmt1 = 3;
18576     MulAmt2 = MulAmt / 3;
18577   }
18578   if (MulAmt2 &&
18579       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18580     SDLoc DL(N);
18581
18582     if (isPowerOf2_64(MulAmt2) &&
18583         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18584       // If second multiplifer is pow2, issue it first. We want the multiply by
18585       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18586       // is an add.
18587       std::swap(MulAmt1, MulAmt2);
18588
18589     SDValue NewMul;
18590     if (isPowerOf2_64(MulAmt1))
18591       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18592                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18593     else
18594       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18595                            DAG.getConstant(MulAmt1, VT));
18596
18597     if (isPowerOf2_64(MulAmt2))
18598       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18599                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18600     else
18601       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18602                            DAG.getConstant(MulAmt2, VT));
18603
18604     // Do not add new nodes to DAG combiner worklist.
18605     DCI.CombineTo(N, NewMul, false);
18606   }
18607   return SDValue();
18608 }
18609
18610 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18611   SDValue N0 = N->getOperand(0);
18612   SDValue N1 = N->getOperand(1);
18613   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18614   EVT VT = N0.getValueType();
18615
18616   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18617   // since the result of setcc_c is all zero's or all ones.
18618   if (VT.isInteger() && !VT.isVector() &&
18619       N1C && N0.getOpcode() == ISD::AND &&
18620       N0.getOperand(1).getOpcode() == ISD::Constant) {
18621     SDValue N00 = N0.getOperand(0);
18622     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18623         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18624           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18625          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18626       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18627       APInt ShAmt = N1C->getAPIntValue();
18628       Mask = Mask.shl(ShAmt);
18629       if (Mask != 0)
18630         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18631                            N00, DAG.getConstant(Mask, VT));
18632     }
18633   }
18634
18635   // Hardware support for vector shifts is sparse which makes us scalarize the
18636   // vector operations in many cases. Also, on sandybridge ADD is faster than
18637   // shl.
18638   // (shl V, 1) -> add V,V
18639   if (isSplatVector(N1.getNode())) {
18640     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18641     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18642     // We shift all of the values by one. In many cases we do not have
18643     // hardware support for this operation. This is better expressed as an ADD
18644     // of two values.
18645     if (N1C && (1 == N1C->getZExtValue())) {
18646       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18647     }
18648   }
18649
18650   return SDValue();
18651 }
18652
18653 /// \brief Returns a vector of 0s if the node in input is a vector logical
18654 /// shift by a constant amount which is known to be bigger than or equal
18655 /// to the vector element size in bits.
18656 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18657                                       const X86Subtarget *Subtarget) {
18658   EVT VT = N->getValueType(0);
18659
18660   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18661       (!Subtarget->hasInt256() ||
18662        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18663     return SDValue();
18664
18665   SDValue Amt = N->getOperand(1);
18666   SDLoc DL(N);
18667   if (isSplatVector(Amt.getNode())) {
18668     SDValue SclrAmt = Amt->getOperand(0);
18669     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18670       APInt ShiftAmt = C->getAPIntValue();
18671       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18672
18673       // SSE2/AVX2 logical shifts always return a vector of 0s
18674       // if the shift amount is bigger than or equal to
18675       // the element size. The constant shift amount will be
18676       // encoded as a 8-bit immediate.
18677       if (ShiftAmt.trunc(8).uge(MaxAmount))
18678         return getZeroVector(VT, Subtarget, DAG, DL);
18679     }
18680   }
18681
18682   return SDValue();
18683 }
18684
18685 /// PerformShiftCombine - Combine shifts.
18686 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18687                                    TargetLowering::DAGCombinerInfo &DCI,
18688                                    const X86Subtarget *Subtarget) {
18689   if (N->getOpcode() == ISD::SHL) {
18690     SDValue V = PerformSHLCombine(N, DAG);
18691     if (V.getNode()) return V;
18692   }
18693
18694   if (N->getOpcode() != ISD::SRA) {
18695     // Try to fold this logical shift into a zero vector.
18696     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18697     if (V.getNode()) return V;
18698   }
18699
18700   return SDValue();
18701 }
18702
18703 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18704 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18705 // and friends.  Likewise for OR -> CMPNEQSS.
18706 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18707                             TargetLowering::DAGCombinerInfo &DCI,
18708                             const X86Subtarget *Subtarget) {
18709   unsigned opcode;
18710
18711   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18712   // we're requiring SSE2 for both.
18713   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18714     SDValue N0 = N->getOperand(0);
18715     SDValue N1 = N->getOperand(1);
18716     SDValue CMP0 = N0->getOperand(1);
18717     SDValue CMP1 = N1->getOperand(1);
18718     SDLoc DL(N);
18719
18720     // The SETCCs should both refer to the same CMP.
18721     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18722       return SDValue();
18723
18724     SDValue CMP00 = CMP0->getOperand(0);
18725     SDValue CMP01 = CMP0->getOperand(1);
18726     EVT     VT    = CMP00.getValueType();
18727
18728     if (VT == MVT::f32 || VT == MVT::f64) {
18729       bool ExpectingFlags = false;
18730       // Check for any users that want flags:
18731       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18732            !ExpectingFlags && UI != UE; ++UI)
18733         switch (UI->getOpcode()) {
18734         default:
18735         case ISD::BR_CC:
18736         case ISD::BRCOND:
18737         case ISD::SELECT:
18738           ExpectingFlags = true;
18739           break;
18740         case ISD::CopyToReg:
18741         case ISD::SIGN_EXTEND:
18742         case ISD::ZERO_EXTEND:
18743         case ISD::ANY_EXTEND:
18744           break;
18745         }
18746
18747       if (!ExpectingFlags) {
18748         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18749         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18750
18751         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18752           X86::CondCode tmp = cc0;
18753           cc0 = cc1;
18754           cc1 = tmp;
18755         }
18756
18757         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18758             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18759           // FIXME: need symbolic constants for these magic numbers.
18760           // See X86ATTInstPrinter.cpp:printSSECC().
18761           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18762           if (Subtarget->hasAVX512()) {
18763             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18764                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18765             if (N->getValueType(0) != MVT::i1)
18766               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18767                                  FSetCC);
18768             return FSetCC;
18769           }
18770           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18771                                               CMP00.getValueType(), CMP00, CMP01,
18772                                               DAG.getConstant(x86cc, MVT::i8));
18773
18774           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18775           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18776
18777           if (is64BitFP && !Subtarget->is64Bit()) {
18778             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18779             // 64-bit integer, since that's not a legal type. Since
18780             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18781             // bits, but can do this little dance to extract the lowest 32 bits
18782             // and work with those going forward.
18783             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18784                                            OnesOrZeroesF);
18785             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18786                                            Vector64);
18787             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18788                                         Vector32, DAG.getIntPtrConstant(0));
18789             IntVT = MVT::i32;
18790           }
18791
18792           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18793           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18794                                       DAG.getConstant(1, IntVT));
18795           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18796           return OneBitOfTruth;
18797         }
18798       }
18799     }
18800   }
18801   return SDValue();
18802 }
18803
18804 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18805 /// so it can be folded inside ANDNP.
18806 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18807   EVT VT = N->getValueType(0);
18808
18809   // Match direct AllOnes for 128 and 256-bit vectors
18810   if (ISD::isBuildVectorAllOnes(N))
18811     return true;
18812
18813   // Look through a bit convert.
18814   if (N->getOpcode() == ISD::BITCAST)
18815     N = N->getOperand(0).getNode();
18816
18817   // Sometimes the operand may come from a insert_subvector building a 256-bit
18818   // allones vector
18819   if (VT.is256BitVector() &&
18820       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18821     SDValue V1 = N->getOperand(0);
18822     SDValue V2 = N->getOperand(1);
18823
18824     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18825         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18826         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18827         ISD::isBuildVectorAllOnes(V2.getNode()))
18828       return true;
18829   }
18830
18831   return false;
18832 }
18833
18834 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18835 // register. In most cases we actually compare or select YMM-sized registers
18836 // and mixing the two types creates horrible code. This method optimizes
18837 // some of the transition sequences.
18838 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18839                                  TargetLowering::DAGCombinerInfo &DCI,
18840                                  const X86Subtarget *Subtarget) {
18841   EVT VT = N->getValueType(0);
18842   if (!VT.is256BitVector())
18843     return SDValue();
18844
18845   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18846           N->getOpcode() == ISD::ZERO_EXTEND ||
18847           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18848
18849   SDValue Narrow = N->getOperand(0);
18850   EVT NarrowVT = Narrow->getValueType(0);
18851   if (!NarrowVT.is128BitVector())
18852     return SDValue();
18853
18854   if (Narrow->getOpcode() != ISD::XOR &&
18855       Narrow->getOpcode() != ISD::AND &&
18856       Narrow->getOpcode() != ISD::OR)
18857     return SDValue();
18858
18859   SDValue N0  = Narrow->getOperand(0);
18860   SDValue N1  = Narrow->getOperand(1);
18861   SDLoc DL(Narrow);
18862
18863   // The Left side has to be a trunc.
18864   if (N0.getOpcode() != ISD::TRUNCATE)
18865     return SDValue();
18866
18867   // The type of the truncated inputs.
18868   EVT WideVT = N0->getOperand(0)->getValueType(0);
18869   if (WideVT != VT)
18870     return SDValue();
18871
18872   // The right side has to be a 'trunc' or a constant vector.
18873   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18874   bool RHSConst = (isSplatVector(N1.getNode()) &&
18875                    isa<ConstantSDNode>(N1->getOperand(0)));
18876   if (!RHSTrunc && !RHSConst)
18877     return SDValue();
18878
18879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18880
18881   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18882     return SDValue();
18883
18884   // Set N0 and N1 to hold the inputs to the new wide operation.
18885   N0 = N0->getOperand(0);
18886   if (RHSConst) {
18887     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18888                      N1->getOperand(0));
18889     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18890     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18891   } else if (RHSTrunc) {
18892     N1 = N1->getOperand(0);
18893   }
18894
18895   // Generate the wide operation.
18896   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18897   unsigned Opcode = N->getOpcode();
18898   switch (Opcode) {
18899   case ISD::ANY_EXTEND:
18900     return Op;
18901   case ISD::ZERO_EXTEND: {
18902     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18903     APInt Mask = APInt::getAllOnesValue(InBits);
18904     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18905     return DAG.getNode(ISD::AND, DL, VT,
18906                        Op, DAG.getConstant(Mask, VT));
18907   }
18908   case ISD::SIGN_EXTEND:
18909     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18910                        Op, DAG.getValueType(NarrowVT));
18911   default:
18912     llvm_unreachable("Unexpected opcode");
18913   }
18914 }
18915
18916 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18917                                  TargetLowering::DAGCombinerInfo &DCI,
18918                                  const X86Subtarget *Subtarget) {
18919   EVT VT = N->getValueType(0);
18920   if (DCI.isBeforeLegalizeOps())
18921     return SDValue();
18922
18923   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18924   if (R.getNode())
18925     return R;
18926
18927   // Create BEXTR instructions
18928   // BEXTR is ((X >> imm) & (2**size-1))
18929   if (VT == MVT::i32 || VT == MVT::i64) {
18930     SDValue N0 = N->getOperand(0);
18931     SDValue N1 = N->getOperand(1);
18932     SDLoc DL(N);
18933
18934     // Check for BEXTR.
18935     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18936         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18937       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18938       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18939       if (MaskNode && ShiftNode) {
18940         uint64_t Mask = MaskNode->getZExtValue();
18941         uint64_t Shift = ShiftNode->getZExtValue();
18942         if (isMask_64(Mask)) {
18943           uint64_t MaskSize = CountPopulation_64(Mask);
18944           if (Shift + MaskSize <= VT.getSizeInBits())
18945             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18946                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18947         }
18948       }
18949     } // BEXTR
18950
18951     return SDValue();
18952   }
18953
18954   // Want to form ANDNP nodes:
18955   // 1) In the hopes of then easily combining them with OR and AND nodes
18956   //    to form PBLEND/PSIGN.
18957   // 2) To match ANDN packed intrinsics
18958   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18959     return SDValue();
18960
18961   SDValue N0 = N->getOperand(0);
18962   SDValue N1 = N->getOperand(1);
18963   SDLoc DL(N);
18964
18965   // Check LHS for vnot
18966   if (N0.getOpcode() == ISD::XOR &&
18967       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18968       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18969     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18970
18971   // Check RHS for vnot
18972   if (N1.getOpcode() == ISD::XOR &&
18973       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18974       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18975     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18976
18977   return SDValue();
18978 }
18979
18980 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18981                                 TargetLowering::DAGCombinerInfo &DCI,
18982                                 const X86Subtarget *Subtarget) {
18983   if (DCI.isBeforeLegalizeOps())
18984     return SDValue();
18985
18986   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18987   if (R.getNode())
18988     return R;
18989
18990   SDValue N0 = N->getOperand(0);
18991   SDValue N1 = N->getOperand(1);
18992   EVT VT = N->getValueType(0);
18993
18994   // look for psign/blend
18995   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18996     if (!Subtarget->hasSSSE3() ||
18997         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18998       return SDValue();
18999
19000     // Canonicalize pandn to RHS
19001     if (N0.getOpcode() == X86ISD::ANDNP)
19002       std::swap(N0, N1);
19003     // or (and (m, y), (pandn m, x))
19004     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19005       SDValue Mask = N1.getOperand(0);
19006       SDValue X    = N1.getOperand(1);
19007       SDValue Y;
19008       if (N0.getOperand(0) == Mask)
19009         Y = N0.getOperand(1);
19010       if (N0.getOperand(1) == Mask)
19011         Y = N0.getOperand(0);
19012
19013       // Check to see if the mask appeared in both the AND and ANDNP and
19014       if (!Y.getNode())
19015         return SDValue();
19016
19017       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19018       // Look through mask bitcast.
19019       if (Mask.getOpcode() == ISD::BITCAST)
19020         Mask = Mask.getOperand(0);
19021       if (X.getOpcode() == ISD::BITCAST)
19022         X = X.getOperand(0);
19023       if (Y.getOpcode() == ISD::BITCAST)
19024         Y = Y.getOperand(0);
19025
19026       EVT MaskVT = Mask.getValueType();
19027
19028       // Validate that the Mask operand is a vector sra node.
19029       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19030       // there is no psrai.b
19031       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19032       unsigned SraAmt = ~0;
19033       if (Mask.getOpcode() == ISD::SRA) {
19034         SDValue Amt = Mask.getOperand(1);
19035         if (isSplatVector(Amt.getNode())) {
19036           SDValue SclrAmt = Amt->getOperand(0);
19037           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19038             SraAmt = C->getZExtValue();
19039         }
19040       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19041         SDValue SraC = Mask.getOperand(1);
19042         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19043       }
19044       if ((SraAmt + 1) != EltBits)
19045         return SDValue();
19046
19047       SDLoc DL(N);
19048
19049       // Now we know we at least have a plendvb with the mask val.  See if
19050       // we can form a psignb/w/d.
19051       // psign = x.type == y.type == mask.type && y = sub(0, x);
19052       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19053           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19054           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19055         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19056                "Unsupported VT for PSIGN");
19057         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19058         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19059       }
19060       // PBLENDVB only available on SSE 4.1
19061       if (!Subtarget->hasSSE41())
19062         return SDValue();
19063
19064       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19065
19066       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19067       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19068       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19069       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19070       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19071     }
19072   }
19073
19074   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19075     return SDValue();
19076
19077   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19078   MachineFunction &MF = DAG.getMachineFunction();
19079   bool OptForSize = MF.getFunction()->getAttributes().
19080     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19081
19082   // SHLD/SHRD instructions have lower register pressure, but on some
19083   // platforms they have higher latency than the equivalent
19084   // series of shifts/or that would otherwise be generated.
19085   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19086   // have higher latencies and we are not optimizing for size.
19087   if (!OptForSize && Subtarget->isSHLDSlow())
19088     return SDValue();
19089
19090   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19091     std::swap(N0, N1);
19092   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19093     return SDValue();
19094   if (!N0.hasOneUse() || !N1.hasOneUse())
19095     return SDValue();
19096
19097   SDValue ShAmt0 = N0.getOperand(1);
19098   if (ShAmt0.getValueType() != MVT::i8)
19099     return SDValue();
19100   SDValue ShAmt1 = N1.getOperand(1);
19101   if (ShAmt1.getValueType() != MVT::i8)
19102     return SDValue();
19103   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19104     ShAmt0 = ShAmt0.getOperand(0);
19105   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19106     ShAmt1 = ShAmt1.getOperand(0);
19107
19108   SDLoc DL(N);
19109   unsigned Opc = X86ISD::SHLD;
19110   SDValue Op0 = N0.getOperand(0);
19111   SDValue Op1 = N1.getOperand(0);
19112   if (ShAmt0.getOpcode() == ISD::SUB) {
19113     Opc = X86ISD::SHRD;
19114     std::swap(Op0, Op1);
19115     std::swap(ShAmt0, ShAmt1);
19116   }
19117
19118   unsigned Bits = VT.getSizeInBits();
19119   if (ShAmt1.getOpcode() == ISD::SUB) {
19120     SDValue Sum = ShAmt1.getOperand(0);
19121     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19122       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19123       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19124         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19125       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19126         return DAG.getNode(Opc, DL, VT,
19127                            Op0, Op1,
19128                            DAG.getNode(ISD::TRUNCATE, DL,
19129                                        MVT::i8, ShAmt0));
19130     }
19131   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19132     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19133     if (ShAmt0C &&
19134         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19135       return DAG.getNode(Opc, DL, VT,
19136                          N0.getOperand(0), N1.getOperand(0),
19137                          DAG.getNode(ISD::TRUNCATE, DL,
19138                                        MVT::i8, ShAmt0));
19139   }
19140
19141   return SDValue();
19142 }
19143
19144 // Generate NEG and CMOV for integer abs.
19145 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19146   EVT VT = N->getValueType(0);
19147
19148   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19149   // 8-bit integer abs to NEG and CMOV.
19150   if (VT.isInteger() && VT.getSizeInBits() == 8)
19151     return SDValue();
19152
19153   SDValue N0 = N->getOperand(0);
19154   SDValue N1 = N->getOperand(1);
19155   SDLoc DL(N);
19156
19157   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19158   // and change it to SUB and CMOV.
19159   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19160       N0.getOpcode() == ISD::ADD &&
19161       N0.getOperand(1) == N1 &&
19162       N1.getOpcode() == ISD::SRA &&
19163       N1.getOperand(0) == N0.getOperand(0))
19164     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19165       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19166         // Generate SUB & CMOV.
19167         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19168                                   DAG.getConstant(0, VT), N0.getOperand(0));
19169
19170         SDValue Ops[] = { N0.getOperand(0), Neg,
19171                           DAG.getConstant(X86::COND_GE, MVT::i8),
19172                           SDValue(Neg.getNode(), 1) };
19173         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19174       }
19175   return SDValue();
19176 }
19177
19178 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19179 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19180                                  TargetLowering::DAGCombinerInfo &DCI,
19181                                  const X86Subtarget *Subtarget) {
19182   if (DCI.isBeforeLegalizeOps())
19183     return SDValue();
19184
19185   if (Subtarget->hasCMov()) {
19186     SDValue RV = performIntegerAbsCombine(N, DAG);
19187     if (RV.getNode())
19188       return RV;
19189   }
19190
19191   return SDValue();
19192 }
19193
19194 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19195 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19196                                   TargetLowering::DAGCombinerInfo &DCI,
19197                                   const X86Subtarget *Subtarget) {
19198   LoadSDNode *Ld = cast<LoadSDNode>(N);
19199   EVT RegVT = Ld->getValueType(0);
19200   EVT MemVT = Ld->getMemoryVT();
19201   SDLoc dl(Ld);
19202   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19203   unsigned RegSz = RegVT.getSizeInBits();
19204
19205   // On Sandybridge unaligned 256bit loads are inefficient.
19206   ISD::LoadExtType Ext = Ld->getExtensionType();
19207   unsigned Alignment = Ld->getAlignment();
19208   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19209   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19210       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19211     unsigned NumElems = RegVT.getVectorNumElements();
19212     if (NumElems < 2)
19213       return SDValue();
19214
19215     SDValue Ptr = Ld->getBasePtr();
19216     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19217
19218     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19219                                   NumElems/2);
19220     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19221                                 Ld->getPointerInfo(), Ld->isVolatile(),
19222                                 Ld->isNonTemporal(), Ld->isInvariant(),
19223                                 Alignment);
19224     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19225     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19226                                 Ld->getPointerInfo(), Ld->isVolatile(),
19227                                 Ld->isNonTemporal(), Ld->isInvariant(),
19228                                 std::min(16U, Alignment));
19229     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19230                              Load1.getValue(1),
19231                              Load2.getValue(1));
19232
19233     SDValue NewVec = DAG.getUNDEF(RegVT);
19234     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19235     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19236     return DCI.CombineTo(N, NewVec, TF, true);
19237   }
19238
19239   // If this is a vector EXT Load then attempt to optimize it using a
19240   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19241   // expansion is still better than scalar code.
19242   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19243   // emit a shuffle and a arithmetic shift.
19244   // TODO: It is possible to support ZExt by zeroing the undef values
19245   // during the shuffle phase or after the shuffle.
19246   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19247       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19248     assert(MemVT != RegVT && "Cannot extend to the same type");
19249     assert(MemVT.isVector() && "Must load a vector from memory");
19250
19251     unsigned NumElems = RegVT.getVectorNumElements();
19252     unsigned MemSz = MemVT.getSizeInBits();
19253     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19254
19255     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19256       return SDValue();
19257
19258     // All sizes must be a power of two.
19259     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19260       return SDValue();
19261
19262     // Attempt to load the original value using scalar loads.
19263     // Find the largest scalar type that divides the total loaded size.
19264     MVT SclrLoadTy = MVT::i8;
19265     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19266          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19267       MVT Tp = (MVT::SimpleValueType)tp;
19268       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19269         SclrLoadTy = Tp;
19270       }
19271     }
19272
19273     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19274     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19275         (64 <= MemSz))
19276       SclrLoadTy = MVT::f64;
19277
19278     // Calculate the number of scalar loads that we need to perform
19279     // in order to load our vector from memory.
19280     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19281     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19282       return SDValue();
19283
19284     unsigned loadRegZize = RegSz;
19285     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19286       loadRegZize /= 2;
19287
19288     // Represent our vector as a sequence of elements which are the
19289     // largest scalar that we can load.
19290     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19291       loadRegZize/SclrLoadTy.getSizeInBits());
19292
19293     // Represent the data using the same element type that is stored in
19294     // memory. In practice, we ''widen'' MemVT.
19295     EVT WideVecVT =
19296           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19297                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19298
19299     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19300       "Invalid vector type");
19301
19302     // We can't shuffle using an illegal type.
19303     if (!TLI.isTypeLegal(WideVecVT))
19304       return SDValue();
19305
19306     SmallVector<SDValue, 8> Chains;
19307     SDValue Ptr = Ld->getBasePtr();
19308     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19309                                         TLI.getPointerTy());
19310     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19311
19312     for (unsigned i = 0; i < NumLoads; ++i) {
19313       // Perform a single load.
19314       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19315                                        Ptr, Ld->getPointerInfo(),
19316                                        Ld->isVolatile(), Ld->isNonTemporal(),
19317                                        Ld->isInvariant(), Ld->getAlignment());
19318       Chains.push_back(ScalarLoad.getValue(1));
19319       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19320       // another round of DAGCombining.
19321       if (i == 0)
19322         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19323       else
19324         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19325                           ScalarLoad, DAG.getIntPtrConstant(i));
19326
19327       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19328     }
19329
19330     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19331
19332     // Bitcast the loaded value to a vector of the original element type, in
19333     // the size of the target vector type.
19334     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19335     unsigned SizeRatio = RegSz/MemSz;
19336
19337     if (Ext == ISD::SEXTLOAD) {
19338       // If we have SSE4.1 we can directly emit a VSEXT node.
19339       if (Subtarget->hasSSE41()) {
19340         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19341         return DCI.CombineTo(N, Sext, TF, true);
19342       }
19343
19344       // Otherwise we'll shuffle the small elements in the high bits of the
19345       // larger type and perform an arithmetic shift. If the shift is not legal
19346       // it's better to scalarize.
19347       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19348         return SDValue();
19349
19350       // Redistribute the loaded elements into the different locations.
19351       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19352       for (unsigned i = 0; i != NumElems; ++i)
19353         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19354
19355       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19356                                            DAG.getUNDEF(WideVecVT),
19357                                            &ShuffleVec[0]);
19358
19359       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19360
19361       // Build the arithmetic shift.
19362       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19363                      MemVT.getVectorElementType().getSizeInBits();
19364       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19365                           DAG.getConstant(Amt, RegVT));
19366
19367       return DCI.CombineTo(N, Shuff, TF, true);
19368     }
19369
19370     // Redistribute the loaded elements into the different locations.
19371     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19372     for (unsigned i = 0; i != NumElems; ++i)
19373       ShuffleVec[i*SizeRatio] = i;
19374
19375     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19376                                          DAG.getUNDEF(WideVecVT),
19377                                          &ShuffleVec[0]);
19378
19379     // Bitcast to the requested type.
19380     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19381     // Replace the original load with the new sequence
19382     // and return the new chain.
19383     return DCI.CombineTo(N, Shuff, TF, true);
19384   }
19385
19386   return SDValue();
19387 }
19388
19389 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19390 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19391                                    const X86Subtarget *Subtarget) {
19392   StoreSDNode *St = cast<StoreSDNode>(N);
19393   EVT VT = St->getValue().getValueType();
19394   EVT StVT = St->getMemoryVT();
19395   SDLoc dl(St);
19396   SDValue StoredVal = St->getOperand(1);
19397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19398
19399   // If we are saving a concatenation of two XMM registers, perform two stores.
19400   // On Sandy Bridge, 256-bit memory operations are executed by two
19401   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19402   // memory  operation.
19403   unsigned Alignment = St->getAlignment();
19404   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19405   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19406       StVT == VT && !IsAligned) {
19407     unsigned NumElems = VT.getVectorNumElements();
19408     if (NumElems < 2)
19409       return SDValue();
19410
19411     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19412     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19413
19414     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19415     SDValue Ptr0 = St->getBasePtr();
19416     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19417
19418     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19419                                 St->getPointerInfo(), St->isVolatile(),
19420                                 St->isNonTemporal(), Alignment);
19421     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19422                                 St->getPointerInfo(), St->isVolatile(),
19423                                 St->isNonTemporal(),
19424                                 std::min(16U, Alignment));
19425     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19426   }
19427
19428   // Optimize trunc store (of multiple scalars) to shuffle and store.
19429   // First, pack all of the elements in one place. Next, store to memory
19430   // in fewer chunks.
19431   if (St->isTruncatingStore() && VT.isVector()) {
19432     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19433     unsigned NumElems = VT.getVectorNumElements();
19434     assert(StVT != VT && "Cannot truncate to the same type");
19435     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19436     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19437
19438     // From, To sizes and ElemCount must be pow of two
19439     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19440     // We are going to use the original vector elt for storing.
19441     // Accumulated smaller vector elements must be a multiple of the store size.
19442     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19443
19444     unsigned SizeRatio  = FromSz / ToSz;
19445
19446     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19447
19448     // Create a type on which we perform the shuffle
19449     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19450             StVT.getScalarType(), NumElems*SizeRatio);
19451
19452     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19453
19454     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19455     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19456     for (unsigned i = 0; i != NumElems; ++i)
19457       ShuffleVec[i] = i * SizeRatio;
19458
19459     // Can't shuffle using an illegal type.
19460     if (!TLI.isTypeLegal(WideVecVT))
19461       return SDValue();
19462
19463     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19464                                          DAG.getUNDEF(WideVecVT),
19465                                          &ShuffleVec[0]);
19466     // At this point all of the data is stored at the bottom of the
19467     // register. We now need to save it to mem.
19468
19469     // Find the largest store unit
19470     MVT StoreType = MVT::i8;
19471     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19472          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19473       MVT Tp = (MVT::SimpleValueType)tp;
19474       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19475         StoreType = Tp;
19476     }
19477
19478     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19479     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19480         (64 <= NumElems * ToSz))
19481       StoreType = MVT::f64;
19482
19483     // Bitcast the original vector into a vector of store-size units
19484     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19485             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19486     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19487     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19488     SmallVector<SDValue, 8> Chains;
19489     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19490                                         TLI.getPointerTy());
19491     SDValue Ptr = St->getBasePtr();
19492
19493     // Perform one or more big stores into memory.
19494     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19495       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19496                                    StoreType, ShuffWide,
19497                                    DAG.getIntPtrConstant(i));
19498       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19499                                 St->getPointerInfo(), St->isVolatile(),
19500                                 St->isNonTemporal(), St->getAlignment());
19501       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19502       Chains.push_back(Ch);
19503     }
19504
19505     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19506   }
19507
19508   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19509   // the FP state in cases where an emms may be missing.
19510   // A preferable solution to the general problem is to figure out the right
19511   // places to insert EMMS.  This qualifies as a quick hack.
19512
19513   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19514   if (VT.getSizeInBits() != 64)
19515     return SDValue();
19516
19517   const Function *F = DAG.getMachineFunction().getFunction();
19518   bool NoImplicitFloatOps = F->getAttributes().
19519     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19520   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19521                      && Subtarget->hasSSE2();
19522   if ((VT.isVector() ||
19523        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19524       isa<LoadSDNode>(St->getValue()) &&
19525       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19526       St->getChain().hasOneUse() && !St->isVolatile()) {
19527     SDNode* LdVal = St->getValue().getNode();
19528     LoadSDNode *Ld = nullptr;
19529     int TokenFactorIndex = -1;
19530     SmallVector<SDValue, 8> Ops;
19531     SDNode* ChainVal = St->getChain().getNode();
19532     // Must be a store of a load.  We currently handle two cases:  the load
19533     // is a direct child, and it's under an intervening TokenFactor.  It is
19534     // possible to dig deeper under nested TokenFactors.
19535     if (ChainVal == LdVal)
19536       Ld = cast<LoadSDNode>(St->getChain());
19537     else if (St->getValue().hasOneUse() &&
19538              ChainVal->getOpcode() == ISD::TokenFactor) {
19539       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19540         if (ChainVal->getOperand(i).getNode() == LdVal) {
19541           TokenFactorIndex = i;
19542           Ld = cast<LoadSDNode>(St->getValue());
19543         } else
19544           Ops.push_back(ChainVal->getOperand(i));
19545       }
19546     }
19547
19548     if (!Ld || !ISD::isNormalLoad(Ld))
19549       return SDValue();
19550
19551     // If this is not the MMX case, i.e. we are just turning i64 load/store
19552     // into f64 load/store, avoid the transformation if there are multiple
19553     // uses of the loaded value.
19554     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19555       return SDValue();
19556
19557     SDLoc LdDL(Ld);
19558     SDLoc StDL(N);
19559     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19560     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19561     // pair instead.
19562     if (Subtarget->is64Bit() || F64IsLegal) {
19563       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19564       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19565                                   Ld->getPointerInfo(), Ld->isVolatile(),
19566                                   Ld->isNonTemporal(), Ld->isInvariant(),
19567                                   Ld->getAlignment());
19568       SDValue NewChain = NewLd.getValue(1);
19569       if (TokenFactorIndex != -1) {
19570         Ops.push_back(NewChain);
19571         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19572       }
19573       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19574                           St->getPointerInfo(),
19575                           St->isVolatile(), St->isNonTemporal(),
19576                           St->getAlignment());
19577     }
19578
19579     // Otherwise, lower to two pairs of 32-bit loads / stores.
19580     SDValue LoAddr = Ld->getBasePtr();
19581     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19582                                  DAG.getConstant(4, MVT::i32));
19583
19584     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19585                                Ld->getPointerInfo(),
19586                                Ld->isVolatile(), Ld->isNonTemporal(),
19587                                Ld->isInvariant(), Ld->getAlignment());
19588     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19589                                Ld->getPointerInfo().getWithOffset(4),
19590                                Ld->isVolatile(), Ld->isNonTemporal(),
19591                                Ld->isInvariant(),
19592                                MinAlign(Ld->getAlignment(), 4));
19593
19594     SDValue NewChain = LoLd.getValue(1);
19595     if (TokenFactorIndex != -1) {
19596       Ops.push_back(LoLd);
19597       Ops.push_back(HiLd);
19598       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19599     }
19600
19601     LoAddr = St->getBasePtr();
19602     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19603                          DAG.getConstant(4, MVT::i32));
19604
19605     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19606                                 St->getPointerInfo(),
19607                                 St->isVolatile(), St->isNonTemporal(),
19608                                 St->getAlignment());
19609     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19610                                 St->getPointerInfo().getWithOffset(4),
19611                                 St->isVolatile(),
19612                                 St->isNonTemporal(),
19613                                 MinAlign(St->getAlignment(), 4));
19614     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19615   }
19616   return SDValue();
19617 }
19618
19619 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19620 /// and return the operands for the horizontal operation in LHS and RHS.  A
19621 /// horizontal operation performs the binary operation on successive elements
19622 /// of its first operand, then on successive elements of its second operand,
19623 /// returning the resulting values in a vector.  For example, if
19624 ///   A = < float a0, float a1, float a2, float a3 >
19625 /// and
19626 ///   B = < float b0, float b1, float b2, float b3 >
19627 /// then the result of doing a horizontal operation on A and B is
19628 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19629 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19630 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19631 /// set to A, RHS to B, and the routine returns 'true'.
19632 /// Note that the binary operation should have the property that if one of the
19633 /// operands is UNDEF then the result is UNDEF.
19634 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19635   // Look for the following pattern: if
19636   //   A = < float a0, float a1, float a2, float a3 >
19637   //   B = < float b0, float b1, float b2, float b3 >
19638   // and
19639   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19640   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19641   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19642   // which is A horizontal-op B.
19643
19644   // At least one of the operands should be a vector shuffle.
19645   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19646       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19647     return false;
19648
19649   MVT VT = LHS.getSimpleValueType();
19650
19651   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19652          "Unsupported vector type for horizontal add/sub");
19653
19654   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19655   // operate independently on 128-bit lanes.
19656   unsigned NumElts = VT.getVectorNumElements();
19657   unsigned NumLanes = VT.getSizeInBits()/128;
19658   unsigned NumLaneElts = NumElts / NumLanes;
19659   assert((NumLaneElts % 2 == 0) &&
19660          "Vector type should have an even number of elements in each lane");
19661   unsigned HalfLaneElts = NumLaneElts/2;
19662
19663   // View LHS in the form
19664   //   LHS = VECTOR_SHUFFLE A, B, LMask
19665   // If LHS is not a shuffle then pretend it is the shuffle
19666   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19667   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19668   // type VT.
19669   SDValue A, B;
19670   SmallVector<int, 16> LMask(NumElts);
19671   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19672     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19673       A = LHS.getOperand(0);
19674     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19675       B = LHS.getOperand(1);
19676     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19677     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19678   } else {
19679     if (LHS.getOpcode() != ISD::UNDEF)
19680       A = LHS;
19681     for (unsigned i = 0; i != NumElts; ++i)
19682       LMask[i] = i;
19683   }
19684
19685   // Likewise, view RHS in the form
19686   //   RHS = VECTOR_SHUFFLE C, D, RMask
19687   SDValue C, D;
19688   SmallVector<int, 16> RMask(NumElts);
19689   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19690     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19691       C = RHS.getOperand(0);
19692     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19693       D = RHS.getOperand(1);
19694     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19695     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19696   } else {
19697     if (RHS.getOpcode() != ISD::UNDEF)
19698       C = RHS;
19699     for (unsigned i = 0; i != NumElts; ++i)
19700       RMask[i] = i;
19701   }
19702
19703   // Check that the shuffles are both shuffling the same vectors.
19704   if (!(A == C && B == D) && !(A == D && B == C))
19705     return false;
19706
19707   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19708   if (!A.getNode() && !B.getNode())
19709     return false;
19710
19711   // If A and B occur in reverse order in RHS, then "swap" them (which means
19712   // rewriting the mask).
19713   if (A != C)
19714     CommuteVectorShuffleMask(RMask, NumElts);
19715
19716   // At this point LHS and RHS are equivalent to
19717   //   LHS = VECTOR_SHUFFLE A, B, LMask
19718   //   RHS = VECTOR_SHUFFLE A, B, RMask
19719   // Check that the masks correspond to performing a horizontal operation.
19720   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19721     for (unsigned i = 0; i != NumLaneElts; ++i) {
19722       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19723
19724       // Ignore any UNDEF components.
19725       if (LIdx < 0 || RIdx < 0 ||
19726           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19727           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19728         continue;
19729
19730       // Check that successive elements are being operated on.  If not, this is
19731       // not a horizontal operation.
19732       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19733       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19734       if (!(LIdx == Index && RIdx == Index + 1) &&
19735           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19736         return false;
19737     }
19738   }
19739
19740   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19741   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19742   return true;
19743 }
19744
19745 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19746 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19747                                   const X86Subtarget *Subtarget) {
19748   EVT VT = N->getValueType(0);
19749   SDValue LHS = N->getOperand(0);
19750   SDValue RHS = N->getOperand(1);
19751
19752   // Try to synthesize horizontal adds from adds of shuffles.
19753   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19754        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19755       isHorizontalBinOp(LHS, RHS, true))
19756     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19757   return SDValue();
19758 }
19759
19760 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19761 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19762                                   const X86Subtarget *Subtarget) {
19763   EVT VT = N->getValueType(0);
19764   SDValue LHS = N->getOperand(0);
19765   SDValue RHS = N->getOperand(1);
19766
19767   // Try to synthesize horizontal subs from subs of shuffles.
19768   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19769        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19770       isHorizontalBinOp(LHS, RHS, false))
19771     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19772   return SDValue();
19773 }
19774
19775 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19776 /// X86ISD::FXOR nodes.
19777 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19778   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19779   // F[X]OR(0.0, x) -> x
19780   // F[X]OR(x, 0.0) -> x
19781   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19782     if (C->getValueAPF().isPosZero())
19783       return N->getOperand(1);
19784   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19785     if (C->getValueAPF().isPosZero())
19786       return N->getOperand(0);
19787   return SDValue();
19788 }
19789
19790 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19791 /// X86ISD::FMAX nodes.
19792 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19793   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19794
19795   // Only perform optimizations if UnsafeMath is used.
19796   if (!DAG.getTarget().Options.UnsafeFPMath)
19797     return SDValue();
19798
19799   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19800   // into FMINC and FMAXC, which are Commutative operations.
19801   unsigned NewOp = 0;
19802   switch (N->getOpcode()) {
19803     default: llvm_unreachable("unknown opcode");
19804     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19805     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19806   }
19807
19808   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19809                      N->getOperand(0), N->getOperand(1));
19810 }
19811
19812 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19813 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19814   // FAND(0.0, x) -> 0.0
19815   // FAND(x, 0.0) -> 0.0
19816   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19817     if (C->getValueAPF().isPosZero())
19818       return N->getOperand(0);
19819   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19820     if (C->getValueAPF().isPosZero())
19821       return N->getOperand(1);
19822   return SDValue();
19823 }
19824
19825 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19826 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19827   // FANDN(x, 0.0) -> 0.0
19828   // FANDN(0.0, x) -> x
19829   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19830     if (C->getValueAPF().isPosZero())
19831       return N->getOperand(1);
19832   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19833     if (C->getValueAPF().isPosZero())
19834       return N->getOperand(1);
19835   return SDValue();
19836 }
19837
19838 static SDValue PerformBTCombine(SDNode *N,
19839                                 SelectionDAG &DAG,
19840                                 TargetLowering::DAGCombinerInfo &DCI) {
19841   // BT ignores high bits in the bit index operand.
19842   SDValue Op1 = N->getOperand(1);
19843   if (Op1.hasOneUse()) {
19844     unsigned BitWidth = Op1.getValueSizeInBits();
19845     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19846     APInt KnownZero, KnownOne;
19847     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19848                                           !DCI.isBeforeLegalizeOps());
19849     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19850     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19851         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19852       DCI.CommitTargetLoweringOpt(TLO);
19853   }
19854   return SDValue();
19855 }
19856
19857 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19858   SDValue Op = N->getOperand(0);
19859   if (Op.getOpcode() == ISD::BITCAST)
19860     Op = Op.getOperand(0);
19861   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19862   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19863       VT.getVectorElementType().getSizeInBits() ==
19864       OpVT.getVectorElementType().getSizeInBits()) {
19865     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19866   }
19867   return SDValue();
19868 }
19869
19870 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19871                                                const X86Subtarget *Subtarget) {
19872   EVT VT = N->getValueType(0);
19873   if (!VT.isVector())
19874     return SDValue();
19875
19876   SDValue N0 = N->getOperand(0);
19877   SDValue N1 = N->getOperand(1);
19878   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19879   SDLoc dl(N);
19880
19881   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19882   // both SSE and AVX2 since there is no sign-extended shift right
19883   // operation on a vector with 64-bit elements.
19884   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19885   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19886   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19887       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19888     SDValue N00 = N0.getOperand(0);
19889
19890     // EXTLOAD has a better solution on AVX2,
19891     // it may be replaced with X86ISD::VSEXT node.
19892     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19893       if (!ISD::isNormalLoad(N00.getNode()))
19894         return SDValue();
19895
19896     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19897         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19898                                   N00, N1);
19899       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19900     }
19901   }
19902   return SDValue();
19903 }
19904
19905 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19906                                   TargetLowering::DAGCombinerInfo &DCI,
19907                                   const X86Subtarget *Subtarget) {
19908   if (!DCI.isBeforeLegalizeOps())
19909     return SDValue();
19910
19911   if (!Subtarget->hasFp256())
19912     return SDValue();
19913
19914   EVT VT = N->getValueType(0);
19915   if (VT.isVector() && VT.getSizeInBits() == 256) {
19916     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19917     if (R.getNode())
19918       return R;
19919   }
19920
19921   return SDValue();
19922 }
19923
19924 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19925                                  const X86Subtarget* Subtarget) {
19926   SDLoc dl(N);
19927   EVT VT = N->getValueType(0);
19928
19929   // Let legalize expand this if it isn't a legal type yet.
19930   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19931     return SDValue();
19932
19933   EVT ScalarVT = VT.getScalarType();
19934   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19935       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19936     return SDValue();
19937
19938   SDValue A = N->getOperand(0);
19939   SDValue B = N->getOperand(1);
19940   SDValue C = N->getOperand(2);
19941
19942   bool NegA = (A.getOpcode() == ISD::FNEG);
19943   bool NegB = (B.getOpcode() == ISD::FNEG);
19944   bool NegC = (C.getOpcode() == ISD::FNEG);
19945
19946   // Negative multiplication when NegA xor NegB
19947   bool NegMul = (NegA != NegB);
19948   if (NegA)
19949     A = A.getOperand(0);
19950   if (NegB)
19951     B = B.getOperand(0);
19952   if (NegC)
19953     C = C.getOperand(0);
19954
19955   unsigned Opcode;
19956   if (!NegMul)
19957     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19958   else
19959     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19960
19961   return DAG.getNode(Opcode, dl, VT, A, B, C);
19962 }
19963
19964 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19965                                   TargetLowering::DAGCombinerInfo &DCI,
19966                                   const X86Subtarget *Subtarget) {
19967   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19968   //           (and (i32 x86isd::setcc_carry), 1)
19969   // This eliminates the zext. This transformation is necessary because
19970   // ISD::SETCC is always legalized to i8.
19971   SDLoc dl(N);
19972   SDValue N0 = N->getOperand(0);
19973   EVT VT = N->getValueType(0);
19974
19975   if (N0.getOpcode() == ISD::AND &&
19976       N0.hasOneUse() &&
19977       N0.getOperand(0).hasOneUse()) {
19978     SDValue N00 = N0.getOperand(0);
19979     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19980       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19981       if (!C || C->getZExtValue() != 1)
19982         return SDValue();
19983       return DAG.getNode(ISD::AND, dl, VT,
19984                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19985                                      N00.getOperand(0), N00.getOperand(1)),
19986                          DAG.getConstant(1, VT));
19987     }
19988   }
19989
19990   if (N0.getOpcode() == ISD::TRUNCATE &&
19991       N0.hasOneUse() &&
19992       N0.getOperand(0).hasOneUse()) {
19993     SDValue N00 = N0.getOperand(0);
19994     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19995       return DAG.getNode(ISD::AND, dl, VT,
19996                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19997                                      N00.getOperand(0), N00.getOperand(1)),
19998                          DAG.getConstant(1, VT));
19999     }
20000   }
20001   if (VT.is256BitVector()) {
20002     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20003     if (R.getNode())
20004       return R;
20005   }
20006
20007   return SDValue();
20008 }
20009
20010 // Optimize x == -y --> x+y == 0
20011 //          x != -y --> x+y != 0
20012 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20013                                       const X86Subtarget* Subtarget) {
20014   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20015   SDValue LHS = N->getOperand(0);
20016   SDValue RHS = N->getOperand(1);
20017   EVT VT = N->getValueType(0);
20018   SDLoc DL(N);
20019
20020   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20021     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20022       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20023         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20024                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20025         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20026                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20027       }
20028   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20029     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20030       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20031         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20032                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20033         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20034                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20035       }
20036
20037   if (VT.getScalarType() == MVT::i1) {
20038     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20039       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20040     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20041     if (!IsSEXT0 && !IsVZero0)
20042       return SDValue();
20043     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20044       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20045     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20046
20047     if (!IsSEXT1 && !IsVZero1)
20048       return SDValue();
20049
20050     if (IsSEXT0 && IsVZero1) {
20051       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20052       if (CC == ISD::SETEQ)
20053         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20054       return LHS.getOperand(0);
20055     }
20056     if (IsSEXT1 && IsVZero0) {
20057       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20058       if (CC == ISD::SETEQ)
20059         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20060       return RHS.getOperand(0);
20061     }
20062   }
20063
20064   return SDValue();
20065 }
20066
20067 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20068 // as "sbb reg,reg", since it can be extended without zext and produces
20069 // an all-ones bit which is more useful than 0/1 in some cases.
20070 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20071                                MVT VT) {
20072   if (VT == MVT::i8)
20073     return DAG.getNode(ISD::AND, DL, VT,
20074                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20075                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20076                        DAG.getConstant(1, VT));
20077   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20078   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20079                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20080                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20081 }
20082
20083 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20084 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20085                                    TargetLowering::DAGCombinerInfo &DCI,
20086                                    const X86Subtarget *Subtarget) {
20087   SDLoc DL(N);
20088   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20089   SDValue EFLAGS = N->getOperand(1);
20090
20091   if (CC == X86::COND_A) {
20092     // Try to convert COND_A into COND_B in an attempt to facilitate
20093     // materializing "setb reg".
20094     //
20095     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20096     // cannot take an immediate as its first operand.
20097     //
20098     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20099         EFLAGS.getValueType().isInteger() &&
20100         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20101       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20102                                    EFLAGS.getNode()->getVTList(),
20103                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20104       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20105       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20106     }
20107   }
20108
20109   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20110   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20111   // cases.
20112   if (CC == X86::COND_B)
20113     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20114
20115   SDValue Flags;
20116
20117   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20118   if (Flags.getNode()) {
20119     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20120     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20121   }
20122
20123   return SDValue();
20124 }
20125
20126 // Optimize branch condition evaluation.
20127 //
20128 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20129                                     TargetLowering::DAGCombinerInfo &DCI,
20130                                     const X86Subtarget *Subtarget) {
20131   SDLoc DL(N);
20132   SDValue Chain = N->getOperand(0);
20133   SDValue Dest = N->getOperand(1);
20134   SDValue EFLAGS = N->getOperand(3);
20135   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20136
20137   SDValue Flags;
20138
20139   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20140   if (Flags.getNode()) {
20141     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20142     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20143                        Flags);
20144   }
20145
20146   return SDValue();
20147 }
20148
20149 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20150                                         const X86TargetLowering *XTLI) {
20151   SDValue Op0 = N->getOperand(0);
20152   EVT InVT = Op0->getValueType(0);
20153
20154   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20155   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20156     SDLoc dl(N);
20157     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20158     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20159     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20160   }
20161
20162   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20163   // a 32-bit target where SSE doesn't support i64->FP operations.
20164   if (Op0.getOpcode() == ISD::LOAD) {
20165     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20166     EVT VT = Ld->getValueType(0);
20167     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20168         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20169         !XTLI->getSubtarget()->is64Bit() &&
20170         VT == MVT::i64) {
20171       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20172                                           Ld->getChain(), Op0, DAG);
20173       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20174       return FILDChain;
20175     }
20176   }
20177   return SDValue();
20178 }
20179
20180 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20181 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20182                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20183   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20184   // the result is either zero or one (depending on the input carry bit).
20185   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20186   if (X86::isZeroNode(N->getOperand(0)) &&
20187       X86::isZeroNode(N->getOperand(1)) &&
20188       // We don't have a good way to replace an EFLAGS use, so only do this when
20189       // dead right now.
20190       SDValue(N, 1).use_empty()) {
20191     SDLoc DL(N);
20192     EVT VT = N->getValueType(0);
20193     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20194     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20195                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20196                                            DAG.getConstant(X86::COND_B,MVT::i8),
20197                                            N->getOperand(2)),
20198                                DAG.getConstant(1, VT));
20199     return DCI.CombineTo(N, Res1, CarryOut);
20200   }
20201
20202   return SDValue();
20203 }
20204
20205 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20206 //      (add Y, (setne X, 0)) -> sbb -1, Y
20207 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20208 //      (sub (setne X, 0), Y) -> adc -1, Y
20209 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20210   SDLoc DL(N);
20211
20212   // Look through ZExts.
20213   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20214   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20215     return SDValue();
20216
20217   SDValue SetCC = Ext.getOperand(0);
20218   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20219     return SDValue();
20220
20221   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20222   if (CC != X86::COND_E && CC != X86::COND_NE)
20223     return SDValue();
20224
20225   SDValue Cmp = SetCC.getOperand(1);
20226   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20227       !X86::isZeroNode(Cmp.getOperand(1)) ||
20228       !Cmp.getOperand(0).getValueType().isInteger())
20229     return SDValue();
20230
20231   SDValue CmpOp0 = Cmp.getOperand(0);
20232   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20233                                DAG.getConstant(1, CmpOp0.getValueType()));
20234
20235   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20236   if (CC == X86::COND_NE)
20237     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20238                        DL, OtherVal.getValueType(), OtherVal,
20239                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20240   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20241                      DL, OtherVal.getValueType(), OtherVal,
20242                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20243 }
20244
20245 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20246 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20247                                  const X86Subtarget *Subtarget) {
20248   EVT VT = N->getValueType(0);
20249   SDValue Op0 = N->getOperand(0);
20250   SDValue Op1 = N->getOperand(1);
20251
20252   // Try to synthesize horizontal adds from adds of shuffles.
20253   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20254        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20255       isHorizontalBinOp(Op0, Op1, true))
20256     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20257
20258   return OptimizeConditionalInDecrement(N, DAG);
20259 }
20260
20261 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20262                                  const X86Subtarget *Subtarget) {
20263   SDValue Op0 = N->getOperand(0);
20264   SDValue Op1 = N->getOperand(1);
20265
20266   // X86 can't encode an immediate LHS of a sub. See if we can push the
20267   // negation into a preceding instruction.
20268   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20269     // If the RHS of the sub is a XOR with one use and a constant, invert the
20270     // immediate. Then add one to the LHS of the sub so we can turn
20271     // X-Y -> X+~Y+1, saving one register.
20272     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20273         isa<ConstantSDNode>(Op1.getOperand(1))) {
20274       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20275       EVT VT = Op0.getValueType();
20276       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20277                                    Op1.getOperand(0),
20278                                    DAG.getConstant(~XorC, VT));
20279       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20280                          DAG.getConstant(C->getAPIntValue()+1, VT));
20281     }
20282   }
20283
20284   // Try to synthesize horizontal adds from adds of shuffles.
20285   EVT VT = N->getValueType(0);
20286   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20287        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20288       isHorizontalBinOp(Op0, Op1, true))
20289     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20290
20291   return OptimizeConditionalInDecrement(N, DAG);
20292 }
20293
20294 /// performVZEXTCombine - Performs build vector combines
20295 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20296                                         TargetLowering::DAGCombinerInfo &DCI,
20297                                         const X86Subtarget *Subtarget) {
20298   // (vzext (bitcast (vzext (x)) -> (vzext x)
20299   SDValue In = N->getOperand(0);
20300   while (In.getOpcode() == ISD::BITCAST)
20301     In = In.getOperand(0);
20302
20303   if (In.getOpcode() != X86ISD::VZEXT)
20304     return SDValue();
20305
20306   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20307                      In.getOperand(0));
20308 }
20309
20310 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20311                                              DAGCombinerInfo &DCI) const {
20312   SelectionDAG &DAG = DCI.DAG;
20313   switch (N->getOpcode()) {
20314   default: break;
20315   case ISD::EXTRACT_VECTOR_ELT:
20316     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20317   case ISD::VSELECT:
20318   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20319   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20320   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20321   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20322   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20323   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20324   case ISD::SHL:
20325   case ISD::SRA:
20326   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20327   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20328   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20329   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20330   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20331   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20332   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20333   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20334   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20335   case X86ISD::FXOR:
20336   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20337   case X86ISD::FMIN:
20338   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20339   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20340   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20341   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20342   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20343   case ISD::ANY_EXTEND:
20344   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20345   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20346   case ISD::SIGN_EXTEND_INREG:
20347     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20348   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20349   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20350   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20351   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20352   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20353   case X86ISD::SHUFP:       // Handle all target specific shuffles
20354   case X86ISD::PALIGNR:
20355   case X86ISD::UNPCKH:
20356   case X86ISD::UNPCKL:
20357   case X86ISD::MOVHLPS:
20358   case X86ISD::MOVLHPS:
20359   case X86ISD::PSHUFD:
20360   case X86ISD::PSHUFHW:
20361   case X86ISD::PSHUFLW:
20362   case X86ISD::MOVSS:
20363   case X86ISD::MOVSD:
20364   case X86ISD::VPERMILP:
20365   case X86ISD::VPERM2X128:
20366   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20367   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20368   case ISD::INTRINSIC_WO_CHAIN: return PerformINTRINSIC_WO_CHAINCombine(N, DAG);
20369   }
20370
20371   return SDValue();
20372 }
20373
20374 /// isTypeDesirableForOp - Return true if the target has native support for
20375 /// the specified value type and it is 'desirable' to use the type for the
20376 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20377 /// instruction encodings are longer and some i16 instructions are slow.
20378 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20379   if (!isTypeLegal(VT))
20380     return false;
20381   if (VT != MVT::i16)
20382     return true;
20383
20384   switch (Opc) {
20385   default:
20386     return true;
20387   case ISD::LOAD:
20388   case ISD::SIGN_EXTEND:
20389   case ISD::ZERO_EXTEND:
20390   case ISD::ANY_EXTEND:
20391   case ISD::SHL:
20392   case ISD::SRL:
20393   case ISD::SUB:
20394   case ISD::ADD:
20395   case ISD::MUL:
20396   case ISD::AND:
20397   case ISD::OR:
20398   case ISD::XOR:
20399     return false;
20400   }
20401 }
20402
20403 /// IsDesirableToPromoteOp - This method query the target whether it is
20404 /// beneficial for dag combiner to promote the specified node. If true, it
20405 /// should return the desired promotion type by reference.
20406 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20407   EVT VT = Op.getValueType();
20408   if (VT != MVT::i16)
20409     return false;
20410
20411   bool Promote = false;
20412   bool Commute = false;
20413   switch (Op.getOpcode()) {
20414   default: break;
20415   case ISD::LOAD: {
20416     LoadSDNode *LD = cast<LoadSDNode>(Op);
20417     // If the non-extending load has a single use and it's not live out, then it
20418     // might be folded.
20419     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20420                                                      Op.hasOneUse()*/) {
20421       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20422              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20423         // The only case where we'd want to promote LOAD (rather then it being
20424         // promoted as an operand is when it's only use is liveout.
20425         if (UI->getOpcode() != ISD::CopyToReg)
20426           return false;
20427       }
20428     }
20429     Promote = true;
20430     break;
20431   }
20432   case ISD::SIGN_EXTEND:
20433   case ISD::ZERO_EXTEND:
20434   case ISD::ANY_EXTEND:
20435     Promote = true;
20436     break;
20437   case ISD::SHL:
20438   case ISD::SRL: {
20439     SDValue N0 = Op.getOperand(0);
20440     // Look out for (store (shl (load), x)).
20441     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20442       return false;
20443     Promote = true;
20444     break;
20445   }
20446   case ISD::ADD:
20447   case ISD::MUL:
20448   case ISD::AND:
20449   case ISD::OR:
20450   case ISD::XOR:
20451     Commute = true;
20452     // fallthrough
20453   case ISD::SUB: {
20454     SDValue N0 = Op.getOperand(0);
20455     SDValue N1 = Op.getOperand(1);
20456     if (!Commute && MayFoldLoad(N1))
20457       return false;
20458     // Avoid disabling potential load folding opportunities.
20459     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20460       return false;
20461     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20462       return false;
20463     Promote = true;
20464   }
20465   }
20466
20467   PVT = MVT::i32;
20468   return Promote;
20469 }
20470
20471 //===----------------------------------------------------------------------===//
20472 //                           X86 Inline Assembly Support
20473 //===----------------------------------------------------------------------===//
20474
20475 namespace {
20476   // Helper to match a string separated by whitespace.
20477   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20478     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20479
20480     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20481       StringRef piece(*args[i]);
20482       if (!s.startswith(piece)) // Check if the piece matches.
20483         return false;
20484
20485       s = s.substr(piece.size());
20486       StringRef::size_type pos = s.find_first_not_of(" \t");
20487       if (pos == 0) // We matched a prefix.
20488         return false;
20489
20490       s = s.substr(pos);
20491     }
20492
20493     return s.empty();
20494   }
20495   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20496 }
20497
20498 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20499
20500   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20501     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20502         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20503         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20504
20505       if (AsmPieces.size() == 3)
20506         return true;
20507       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20508         return true;
20509     }
20510   }
20511   return false;
20512 }
20513
20514 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20515   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20516
20517   std::string AsmStr = IA->getAsmString();
20518
20519   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20520   if (!Ty || Ty->getBitWidth() % 16 != 0)
20521     return false;
20522
20523   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20524   SmallVector<StringRef, 4> AsmPieces;
20525   SplitString(AsmStr, AsmPieces, ";\n");
20526
20527   switch (AsmPieces.size()) {
20528   default: return false;
20529   case 1:
20530     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20531     // we will turn this bswap into something that will be lowered to logical
20532     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20533     // lower so don't worry about this.
20534     // bswap $0
20535     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20536         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20537         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20538         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20539         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20540         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20541       // No need to check constraints, nothing other than the equivalent of
20542       // "=r,0" would be valid here.
20543       return IntrinsicLowering::LowerToByteSwap(CI);
20544     }
20545
20546     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20547     if (CI->getType()->isIntegerTy(16) &&
20548         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20549         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20550          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20551       AsmPieces.clear();
20552       const std::string &ConstraintsStr = IA->getConstraintString();
20553       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20554       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20555       if (clobbersFlagRegisters(AsmPieces))
20556         return IntrinsicLowering::LowerToByteSwap(CI);
20557     }
20558     break;
20559   case 3:
20560     if (CI->getType()->isIntegerTy(32) &&
20561         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20562         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20563         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20564         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20565       AsmPieces.clear();
20566       const std::string &ConstraintsStr = IA->getConstraintString();
20567       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20568       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20569       if (clobbersFlagRegisters(AsmPieces))
20570         return IntrinsicLowering::LowerToByteSwap(CI);
20571     }
20572
20573     if (CI->getType()->isIntegerTy(64)) {
20574       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20575       if (Constraints.size() >= 2 &&
20576           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20577           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20578         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20579         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20580             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20581             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20582           return IntrinsicLowering::LowerToByteSwap(CI);
20583       }
20584     }
20585     break;
20586   }
20587   return false;
20588 }
20589
20590 /// getConstraintType - Given a constraint letter, return the type of
20591 /// constraint it is for this target.
20592 X86TargetLowering::ConstraintType
20593 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20594   if (Constraint.size() == 1) {
20595     switch (Constraint[0]) {
20596     case 'R':
20597     case 'q':
20598     case 'Q':
20599     case 'f':
20600     case 't':
20601     case 'u':
20602     case 'y':
20603     case 'x':
20604     case 'Y':
20605     case 'l':
20606       return C_RegisterClass;
20607     case 'a':
20608     case 'b':
20609     case 'c':
20610     case 'd':
20611     case 'S':
20612     case 'D':
20613     case 'A':
20614       return C_Register;
20615     case 'I':
20616     case 'J':
20617     case 'K':
20618     case 'L':
20619     case 'M':
20620     case 'N':
20621     case 'G':
20622     case 'C':
20623     case 'e':
20624     case 'Z':
20625       return C_Other;
20626     default:
20627       break;
20628     }
20629   }
20630   return TargetLowering::getConstraintType(Constraint);
20631 }
20632
20633 /// Examine constraint type and operand type and determine a weight value.
20634 /// This object must already have been set up with the operand type
20635 /// and the current alternative constraint selected.
20636 TargetLowering::ConstraintWeight
20637   X86TargetLowering::getSingleConstraintMatchWeight(
20638     AsmOperandInfo &info, const char *constraint) const {
20639   ConstraintWeight weight = CW_Invalid;
20640   Value *CallOperandVal = info.CallOperandVal;
20641     // If we don't have a value, we can't do a match,
20642     // but allow it at the lowest weight.
20643   if (!CallOperandVal)
20644     return CW_Default;
20645   Type *type = CallOperandVal->getType();
20646   // Look at the constraint type.
20647   switch (*constraint) {
20648   default:
20649     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20650   case 'R':
20651   case 'q':
20652   case 'Q':
20653   case 'a':
20654   case 'b':
20655   case 'c':
20656   case 'd':
20657   case 'S':
20658   case 'D':
20659   case 'A':
20660     if (CallOperandVal->getType()->isIntegerTy())
20661       weight = CW_SpecificReg;
20662     break;
20663   case 'f':
20664   case 't':
20665   case 'u':
20666     if (type->isFloatingPointTy())
20667       weight = CW_SpecificReg;
20668     break;
20669   case 'y':
20670     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20671       weight = CW_SpecificReg;
20672     break;
20673   case 'x':
20674   case 'Y':
20675     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20676         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20677       weight = CW_Register;
20678     break;
20679   case 'I':
20680     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20681       if (C->getZExtValue() <= 31)
20682         weight = CW_Constant;
20683     }
20684     break;
20685   case 'J':
20686     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20687       if (C->getZExtValue() <= 63)
20688         weight = CW_Constant;
20689     }
20690     break;
20691   case 'K':
20692     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20693       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20694         weight = CW_Constant;
20695     }
20696     break;
20697   case 'L':
20698     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20699       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20700         weight = CW_Constant;
20701     }
20702     break;
20703   case 'M':
20704     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20705       if (C->getZExtValue() <= 3)
20706         weight = CW_Constant;
20707     }
20708     break;
20709   case 'N':
20710     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20711       if (C->getZExtValue() <= 0xff)
20712         weight = CW_Constant;
20713     }
20714     break;
20715   case 'G':
20716   case 'C':
20717     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20718       weight = CW_Constant;
20719     }
20720     break;
20721   case 'e':
20722     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20723       if ((C->getSExtValue() >= -0x80000000LL) &&
20724           (C->getSExtValue() <= 0x7fffffffLL))
20725         weight = CW_Constant;
20726     }
20727     break;
20728   case 'Z':
20729     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20730       if (C->getZExtValue() <= 0xffffffff)
20731         weight = CW_Constant;
20732     }
20733     break;
20734   }
20735   return weight;
20736 }
20737
20738 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20739 /// with another that has more specific requirements based on the type of the
20740 /// corresponding operand.
20741 const char *X86TargetLowering::
20742 LowerXConstraint(EVT ConstraintVT) const {
20743   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20744   // 'f' like normal targets.
20745   if (ConstraintVT.isFloatingPoint()) {
20746     if (Subtarget->hasSSE2())
20747       return "Y";
20748     if (Subtarget->hasSSE1())
20749       return "x";
20750   }
20751
20752   return TargetLowering::LowerXConstraint(ConstraintVT);
20753 }
20754
20755 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20756 /// vector.  If it is invalid, don't add anything to Ops.
20757 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20758                                                      std::string &Constraint,
20759                                                      std::vector<SDValue>&Ops,
20760                                                      SelectionDAG &DAG) const {
20761   SDValue Result;
20762
20763   // Only support length 1 constraints for now.
20764   if (Constraint.length() > 1) return;
20765
20766   char ConstraintLetter = Constraint[0];
20767   switch (ConstraintLetter) {
20768   default: break;
20769   case 'I':
20770     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20771       if (C->getZExtValue() <= 31) {
20772         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20773         break;
20774       }
20775     }
20776     return;
20777   case 'J':
20778     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20779       if (C->getZExtValue() <= 63) {
20780         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20781         break;
20782       }
20783     }
20784     return;
20785   case 'K':
20786     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20787       if (isInt<8>(C->getSExtValue())) {
20788         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20789         break;
20790       }
20791     }
20792     return;
20793   case 'N':
20794     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20795       if (C->getZExtValue() <= 255) {
20796         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20797         break;
20798       }
20799     }
20800     return;
20801   case 'e': {
20802     // 32-bit signed value
20803     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20804       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20805                                            C->getSExtValue())) {
20806         // Widen to 64 bits here to get it sign extended.
20807         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20808         break;
20809       }
20810     // FIXME gcc accepts some relocatable values here too, but only in certain
20811     // memory models; it's complicated.
20812     }
20813     return;
20814   }
20815   case 'Z': {
20816     // 32-bit unsigned value
20817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20818       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20819                                            C->getZExtValue())) {
20820         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20821         break;
20822       }
20823     }
20824     // FIXME gcc accepts some relocatable values here too, but only in certain
20825     // memory models; it's complicated.
20826     return;
20827   }
20828   case 'i': {
20829     // Literal immediates are always ok.
20830     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20831       // Widen to 64 bits here to get it sign extended.
20832       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20833       break;
20834     }
20835
20836     // In any sort of PIC mode addresses need to be computed at runtime by
20837     // adding in a register or some sort of table lookup.  These can't
20838     // be used as immediates.
20839     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20840       return;
20841
20842     // If we are in non-pic codegen mode, we allow the address of a global (with
20843     // an optional displacement) to be used with 'i'.
20844     GlobalAddressSDNode *GA = nullptr;
20845     int64_t Offset = 0;
20846
20847     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20848     while (1) {
20849       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20850         Offset += GA->getOffset();
20851         break;
20852       } else if (Op.getOpcode() == ISD::ADD) {
20853         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20854           Offset += C->getZExtValue();
20855           Op = Op.getOperand(0);
20856           continue;
20857         }
20858       } else if (Op.getOpcode() == ISD::SUB) {
20859         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20860           Offset += -C->getZExtValue();
20861           Op = Op.getOperand(0);
20862           continue;
20863         }
20864       }
20865
20866       // Otherwise, this isn't something we can handle, reject it.
20867       return;
20868     }
20869
20870     const GlobalValue *GV = GA->getGlobal();
20871     // If we require an extra load to get this address, as in PIC mode, we
20872     // can't accept it.
20873     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20874                                                         getTargetMachine())))
20875       return;
20876
20877     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20878                                         GA->getValueType(0), Offset);
20879     break;
20880   }
20881   }
20882
20883   if (Result.getNode()) {
20884     Ops.push_back(Result);
20885     return;
20886   }
20887   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20888 }
20889
20890 std::pair<unsigned, const TargetRegisterClass*>
20891 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20892                                                 MVT VT) const {
20893   // First, see if this is a constraint that directly corresponds to an LLVM
20894   // register class.
20895   if (Constraint.size() == 1) {
20896     // GCC Constraint Letters
20897     switch (Constraint[0]) {
20898     default: break;
20899       // TODO: Slight differences here in allocation order and leaving
20900       // RIP in the class. Do they matter any more here than they do
20901       // in the normal allocation?
20902     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20903       if (Subtarget->is64Bit()) {
20904         if (VT == MVT::i32 || VT == MVT::f32)
20905           return std::make_pair(0U, &X86::GR32RegClass);
20906         if (VT == MVT::i16)
20907           return std::make_pair(0U, &X86::GR16RegClass);
20908         if (VT == MVT::i8 || VT == MVT::i1)
20909           return std::make_pair(0U, &X86::GR8RegClass);
20910         if (VT == MVT::i64 || VT == MVT::f64)
20911           return std::make_pair(0U, &X86::GR64RegClass);
20912         break;
20913       }
20914       // 32-bit fallthrough
20915     case 'Q':   // Q_REGS
20916       if (VT == MVT::i32 || VT == MVT::f32)
20917         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20918       if (VT == MVT::i16)
20919         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20920       if (VT == MVT::i8 || VT == MVT::i1)
20921         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20922       if (VT == MVT::i64)
20923         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20924       break;
20925     case 'r':   // GENERAL_REGS
20926     case 'l':   // INDEX_REGS
20927       if (VT == MVT::i8 || VT == MVT::i1)
20928         return std::make_pair(0U, &X86::GR8RegClass);
20929       if (VT == MVT::i16)
20930         return std::make_pair(0U, &X86::GR16RegClass);
20931       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20932         return std::make_pair(0U, &X86::GR32RegClass);
20933       return std::make_pair(0U, &X86::GR64RegClass);
20934     case 'R':   // LEGACY_REGS
20935       if (VT == MVT::i8 || VT == MVT::i1)
20936         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20937       if (VT == MVT::i16)
20938         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20939       if (VT == MVT::i32 || !Subtarget->is64Bit())
20940         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20941       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20942     case 'f':  // FP Stack registers.
20943       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20944       // value to the correct fpstack register class.
20945       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20946         return std::make_pair(0U, &X86::RFP32RegClass);
20947       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20948         return std::make_pair(0U, &X86::RFP64RegClass);
20949       return std::make_pair(0U, &X86::RFP80RegClass);
20950     case 'y':   // MMX_REGS if MMX allowed.
20951       if (!Subtarget->hasMMX()) break;
20952       return std::make_pair(0U, &X86::VR64RegClass);
20953     case 'Y':   // SSE_REGS if SSE2 allowed
20954       if (!Subtarget->hasSSE2()) break;
20955       // FALL THROUGH.
20956     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20957       if (!Subtarget->hasSSE1()) break;
20958
20959       switch (VT.SimpleTy) {
20960       default: break;
20961       // Scalar SSE types.
20962       case MVT::f32:
20963       case MVT::i32:
20964         return std::make_pair(0U, &X86::FR32RegClass);
20965       case MVT::f64:
20966       case MVT::i64:
20967         return std::make_pair(0U, &X86::FR64RegClass);
20968       // Vector types.
20969       case MVT::v16i8:
20970       case MVT::v8i16:
20971       case MVT::v4i32:
20972       case MVT::v2i64:
20973       case MVT::v4f32:
20974       case MVT::v2f64:
20975         return std::make_pair(0U, &X86::VR128RegClass);
20976       // AVX types.
20977       case MVT::v32i8:
20978       case MVT::v16i16:
20979       case MVT::v8i32:
20980       case MVT::v4i64:
20981       case MVT::v8f32:
20982       case MVT::v4f64:
20983         return std::make_pair(0U, &X86::VR256RegClass);
20984       case MVT::v8f64:
20985       case MVT::v16f32:
20986       case MVT::v16i32:
20987       case MVT::v8i64:
20988         return std::make_pair(0U, &X86::VR512RegClass);
20989       }
20990       break;
20991     }
20992   }
20993
20994   // Use the default implementation in TargetLowering to convert the register
20995   // constraint into a member of a register class.
20996   std::pair<unsigned, const TargetRegisterClass*> Res;
20997   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20998
20999   // Not found as a standard register?
21000   if (!Res.second) {
21001     // Map st(0) -> st(7) -> ST0
21002     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21003         tolower(Constraint[1]) == 's' &&
21004         tolower(Constraint[2]) == 't' &&
21005         Constraint[3] == '(' &&
21006         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21007         Constraint[5] == ')' &&
21008         Constraint[6] == '}') {
21009
21010       Res.first = X86::ST0+Constraint[4]-'0';
21011       Res.second = &X86::RFP80RegClass;
21012       return Res;
21013     }
21014
21015     // GCC allows "st(0)" to be called just plain "st".
21016     if (StringRef("{st}").equals_lower(Constraint)) {
21017       Res.first = X86::ST0;
21018       Res.second = &X86::RFP80RegClass;
21019       return Res;
21020     }
21021
21022     // flags -> EFLAGS
21023     if (StringRef("{flags}").equals_lower(Constraint)) {
21024       Res.first = X86::EFLAGS;
21025       Res.second = &X86::CCRRegClass;
21026       return Res;
21027     }
21028
21029     // 'A' means EAX + EDX.
21030     if (Constraint == "A") {
21031       Res.first = X86::EAX;
21032       Res.second = &X86::GR32_ADRegClass;
21033       return Res;
21034     }
21035     return Res;
21036   }
21037
21038   // Otherwise, check to see if this is a register class of the wrong value
21039   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21040   // turn into {ax},{dx}.
21041   if (Res.second->hasType(VT))
21042     return Res;   // Correct type already, nothing to do.
21043
21044   // All of the single-register GCC register classes map their values onto
21045   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21046   // really want an 8-bit or 32-bit register, map to the appropriate register
21047   // class and return the appropriate register.
21048   if (Res.second == &X86::GR16RegClass) {
21049     if (VT == MVT::i8 || VT == MVT::i1) {
21050       unsigned DestReg = 0;
21051       switch (Res.first) {
21052       default: break;
21053       case X86::AX: DestReg = X86::AL; break;
21054       case X86::DX: DestReg = X86::DL; break;
21055       case X86::CX: DestReg = X86::CL; break;
21056       case X86::BX: DestReg = X86::BL; break;
21057       }
21058       if (DestReg) {
21059         Res.first = DestReg;
21060         Res.second = &X86::GR8RegClass;
21061       }
21062     } else if (VT == MVT::i32 || VT == MVT::f32) {
21063       unsigned DestReg = 0;
21064       switch (Res.first) {
21065       default: break;
21066       case X86::AX: DestReg = X86::EAX; break;
21067       case X86::DX: DestReg = X86::EDX; break;
21068       case X86::CX: DestReg = X86::ECX; break;
21069       case X86::BX: DestReg = X86::EBX; break;
21070       case X86::SI: DestReg = X86::ESI; break;
21071       case X86::DI: DestReg = X86::EDI; break;
21072       case X86::BP: DestReg = X86::EBP; break;
21073       case X86::SP: DestReg = X86::ESP; break;
21074       }
21075       if (DestReg) {
21076         Res.first = DestReg;
21077         Res.second = &X86::GR32RegClass;
21078       }
21079     } else if (VT == MVT::i64 || VT == MVT::f64) {
21080       unsigned DestReg = 0;
21081       switch (Res.first) {
21082       default: break;
21083       case X86::AX: DestReg = X86::RAX; break;
21084       case X86::DX: DestReg = X86::RDX; break;
21085       case X86::CX: DestReg = X86::RCX; break;
21086       case X86::BX: DestReg = X86::RBX; break;
21087       case X86::SI: DestReg = X86::RSI; break;
21088       case X86::DI: DestReg = X86::RDI; break;
21089       case X86::BP: DestReg = X86::RBP; break;
21090       case X86::SP: DestReg = X86::RSP; break;
21091       }
21092       if (DestReg) {
21093         Res.first = DestReg;
21094         Res.second = &X86::GR64RegClass;
21095       }
21096     }
21097   } else if (Res.second == &X86::FR32RegClass ||
21098              Res.second == &X86::FR64RegClass ||
21099              Res.second == &X86::VR128RegClass ||
21100              Res.second == &X86::VR256RegClass ||
21101              Res.second == &X86::FR32XRegClass ||
21102              Res.second == &X86::FR64XRegClass ||
21103              Res.second == &X86::VR128XRegClass ||
21104              Res.second == &X86::VR256XRegClass ||
21105              Res.second == &X86::VR512RegClass) {
21106     // Handle references to XMM physical registers that got mapped into the
21107     // wrong class.  This can happen with constraints like {xmm0} where the
21108     // target independent register mapper will just pick the first match it can
21109     // find, ignoring the required type.
21110
21111     if (VT == MVT::f32 || VT == MVT::i32)
21112       Res.second = &X86::FR32RegClass;
21113     else if (VT == MVT::f64 || VT == MVT::i64)
21114       Res.second = &X86::FR64RegClass;
21115     else if (X86::VR128RegClass.hasType(VT))
21116       Res.second = &X86::VR128RegClass;
21117     else if (X86::VR256RegClass.hasType(VT))
21118       Res.second = &X86::VR256RegClass;
21119     else if (X86::VR512RegClass.hasType(VT))
21120       Res.second = &X86::VR512RegClass;
21121   }
21122
21123   return Res;
21124 }
21125
21126 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21127                                             Type *Ty) const {
21128   // Scaling factors are not free at all.
21129   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21130   // will take 2 allocations in the out of order engine instead of 1
21131   // for plain addressing mode, i.e. inst (reg1).
21132   // E.g.,
21133   // vaddps (%rsi,%drx), %ymm0, %ymm1
21134   // Requires two allocations (one for the load, one for the computation)
21135   // whereas:
21136   // vaddps (%rsi), %ymm0, %ymm1
21137   // Requires just 1 allocation, i.e., freeing allocations for other operations
21138   // and having less micro operations to execute.
21139   //
21140   // For some X86 architectures, this is even worse because for instance for
21141   // stores, the complex addressing mode forces the instruction to use the
21142   // "load" ports instead of the dedicated "store" port.
21143   // E.g., on Haswell:
21144   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21145   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21146   if (isLegalAddressingMode(AM, Ty))
21147     // Scale represents reg2 * scale, thus account for 1
21148     // as soon as we use a second register.
21149     return AM.Scale != 0;
21150   return -1;
21151 }