Convert SelectionDAG::getNode methods to use ArrayRef<SDValue>.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <bitset>
51 #include <cctype>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "x86-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63                                 SelectionDAG &DAG, SDLoc dl,
64                                 unsigned vectorWidth) {
65   assert((vectorWidth == 128 || vectorWidth == 256) &&
66          "Unsupported vector width");
67   EVT VT = Vec.getValueType();
68   EVT ElVT = VT.getVectorElementType();
69   unsigned Factor = VT.getSizeInBits()/vectorWidth;
70   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71                                   VT.getVectorNumElements()/Factor);
72
73   // Extract from UNDEF is UNDEF.
74   if (Vec.getOpcode() == ISD::UNDEF)
75     return DAG.getUNDEF(ResultVT);
76
77   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
78   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79
80   // This is the index of the first element of the vectorWidth-bit chunk
81   // we want.
82   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
83                                * ElemsPerChunk);
84
85   // If the input is a buildvector just emit a smaller one.
86   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89
90   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
92                                VecIdx);
93
94   return Result;
95
96 }
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104                                    SelectionDAG &DAG, SDLoc dl) {
105   assert((Vec.getValueType().is256BitVector() ||
106           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
108 }
109
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112                                    SelectionDAG &DAG, SDLoc dl) {
113   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
115 }
116
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118                                unsigned IdxVal, SelectionDAG &DAG,
119                                SDLoc dl, unsigned vectorWidth) {
120   assert((vectorWidth == 128 || vectorWidth == 256) &&
121          "Unsupported vector width");
122   // Inserting UNDEF is Result
123   if (Vec.getOpcode() == ISD::UNDEF)
124     return Result;
125   EVT VT = Vec.getValueType();
126   EVT ElVT = VT.getVectorElementType();
127   EVT ResultVT = Result.getValueType();
128
129   // Insert the relevant vectorWidth bits.
130   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131
132   // This is the index of the first element of the vectorWidth-bit chunk
133   // we want.
134   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
135                                * ElemsPerChunk);
136
137   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
139                      VecIdx);
140 }
141 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference.  Idx is an index in the 128 bits
145 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148                                   unsigned IdxVal, SelectionDAG &DAG,
149                                   SDLoc dl) {
150   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
152 }
153
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155                                   unsigned IdxVal, SelectionDAG &DAG,
156                                   SDLoc dl) {
157   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
159 }
160
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166                                    unsigned NumElems, SelectionDAG &DAG,
167                                    SDLoc dl) {
168   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
170 }
171
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173                                    unsigned NumElems, SelectionDAG &DAG,
174                                    SDLoc dl) {
175   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
177 }
178
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181   bool is64Bit = Subtarget->is64Bit();
182
183   if (Subtarget->isTargetMacho()) {
184     if (is64Bit)
185       return new X86_64MachoTargetObjectFile();
186     return new TargetLoweringObjectFileMachO();
187   }
188
189   if (Subtarget->isTargetLinux())
190     return new X86LinuxTargetObjectFile();
191   if (Subtarget->isTargetELF())
192     return new TargetLoweringObjectFileELF();
193   if (Subtarget->isTargetKnownWindowsMSVC())
194     return new X86WindowsTargetObjectFile();
195   if (Subtarget->isTargetCOFF())
196     return new TargetLoweringObjectFileCOFF();
197   llvm_unreachable("unknown subtarget type");
198 }
199
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201   : TargetLowering(TM, createTLOF(TM)) {
202   Subtarget = &TM.getSubtarget<X86Subtarget>();
203   X86ScalarSSEf64 = Subtarget->hasSSE2();
204   X86ScalarSSEf32 = Subtarget->hasSSE1();
205   TD = getDataLayout();
206
207   resetOperationActions();
208 }
209
210 void X86TargetLowering::resetOperationActions() {
211   const TargetMachine &TM = getTargetMachine();
212   static bool FirstTimeThrough = true;
213
214   // If none of the target options have changed, then we don't need to reset the
215   // operation actions.
216   if (!FirstTimeThrough && TO == TM.Options) return;
217
218   if (!FirstTimeThrough) {
219     // Reinitialize the actions.
220     initActions();
221     FirstTimeThrough = false;
222   }
223
224   TO = TM.Options;
225
226   // Set up the TargetLowering object.
227   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228
229   // X86 is weird, it always uses i8 for shift amounts and setcc results.
230   setBooleanContents(ZeroOrOneBooleanContent);
231   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233
234   // For 64-bit since we have so many registers use the ILP scheduler, for
235   // 32-bit code use the register pressure specific scheduling.
236   // For Atom, always use ILP scheduling.
237   if (Subtarget->isAtom())
238     setSchedulingPreference(Sched::ILP);
239   else if (Subtarget->is64Bit())
240     setSchedulingPreference(Sched::ILP);
241   else
242     setSchedulingPreference(Sched::RegPressure);
243   const X86RegisterInfo *RegInfo =
244     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246
247   // Bypass expensive divides on Atom when compiling with O2
248   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249     addBypassSlowDiv(32, 8);
250     if (Subtarget->is64Bit())
251       addBypassSlowDiv(64, 16);
252   }
253
254   if (Subtarget->isTargetKnownWindowsMSVC()) {
255     // Setup Windows compiler runtime calls.
256     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258     setLibcallName(RTLIB::SREM_I64, "_allrem");
259     setLibcallName(RTLIB::UREM_I64, "_aullrem");
260     setLibcallName(RTLIB::MUL_I64, "_allmul");
261     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266
267     // The _ftol2 runtime function has an unusual calling conv, which
268     // is modeled by a special pseudo-instruction.
269     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
273   }
274
275   if (Subtarget->isTargetDarwin()) {
276     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277     setUseUnderscoreSetJmp(false);
278     setUseUnderscoreLongJmp(false);
279   } else if (Subtarget->isTargetWindowsGNU()) {
280     // MS runtime is weird: it exports _setjmp, but longjmp!
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(false);
283   } else {
284     setUseUnderscoreSetJmp(true);
285     setUseUnderscoreLongJmp(true);
286   }
287
288   // Set up the register classes.
289   addRegisterClass(MVT::i8, &X86::GR8RegClass);
290   addRegisterClass(MVT::i16, &X86::GR16RegClass);
291   addRegisterClass(MVT::i32, &X86::GR32RegClass);
292   if (Subtarget->is64Bit())
293     addRegisterClass(MVT::i64, &X86::GR64RegClass);
294
295   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296
297   // We don't accept any truncstore of integer registers.
298   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
304
305   // SETOEQ and SETUNE require checking two conditions.
306   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312
313   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314   // operation.
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
318
319   if (Subtarget->is64Bit()) {
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
321     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
322   } else if (!TM.Options.UseSoftFloat) {
323     // We have an algorithm for SSE2->double, and we turn this into a
324     // 64-bit FILD followed by conditional FADD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
326     // We have an algorithm for SSE2, and we turn this into a 64-bit
327     // FILD for other targets.
328     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
329   }
330
331   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332   // this operation.
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
334   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
335
336   if (!TM.Options.UseSoftFloat) {
337     // SSE has no i16 to fp conversion, only i32
338     if (X86ScalarSSEf32) {
339       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
340       // f32 and f64 cases are Legal, f80 case is not
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     } else {
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
344       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
345     }
346   } else {
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
348     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
349   }
350
351   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
352   // are Legal, f80 is custom lowered.
353   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
354   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
355
356   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357   // this operation.
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
359   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
360
361   if (X86ScalarSSEf32) {
362     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
363     // f32 and f64 cases are Legal, f80 case is not
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   } else {
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
367     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
368   }
369
370   // Handle FP_TO_UINT by promoting the destination to a larger signed
371   // conversion.
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
375
376   if (Subtarget->is64Bit()) {
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
378     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
379   } else if (!TM.Options.UseSoftFloat) {
380     // Since AVX is a superset of SSE3, only check for SSE here.
381     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382       // Expand FP_TO_UINT into a select.
383       // FIXME: We would like to use a Custom expander here eventually to do
384       // the optimal thing for SSE vs. the default expansion in the legalizer.
385       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
386     else
387       // With SSE3 we can use fisttpll to convert to a signed i64; without
388       // SSE, we're stuck with a fistpll.
389       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
390   }
391
392   if (isTargetFTOL()) {
393     // Use the _ftol2 runtime function, which has a pseudo-instruction
394     // to handle its weird calling convention.
395     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
396   }
397
398   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399   if (!X86ScalarSSEf64) {
400     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
401     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
402     if (Subtarget->is64Bit()) {
403       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
404       // Without SSE, i64->f64 goes through memory.
405       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
406     }
407   }
408
409   // Scalar integer divide and remainder are lowered to use operations that
410   // produce two results, to match the available instructions. This exposes
411   // the two-result form to trivial CSE, which is able to combine x/y and x%y
412   // into a single instruction.
413   //
414   // Scalar integer multiply-high is also lowered to use two-result
415   // operations, to match the available instructions. However, plain multiply
416   // (low) operations are left as Legal, as there are single-result
417   // instructions for this in x86. Using the two-result multiply instructions
418   // when both high and low results are needed must be arranged by dagcombine.
419   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420     MVT VT = IntVTs[i];
421     setOperationAction(ISD::MULHS, VT, Expand);
422     setOperationAction(ISD::MULHU, VT, Expand);
423     setOperationAction(ISD::SDIV, VT, Expand);
424     setOperationAction(ISD::UDIV, VT, Expand);
425     setOperationAction(ISD::SREM, VT, Expand);
426     setOperationAction(ISD::UREM, VT, Expand);
427
428     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429     setOperationAction(ISD::ADDC, VT, Custom);
430     setOperationAction(ISD::ADDE, VT, Custom);
431     setOperationAction(ISD::SUBC, VT, Custom);
432     setOperationAction(ISD::SUBE, VT, Custom);
433   }
434
435   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
436   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
437   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
444   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
445   if (Subtarget->is64Bit())
446     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
450   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
454   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
455
456   // Promote the i8 variants and force them on up to i32 which has a shorter
457   // encoding.
458   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
459   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
460   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
461   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
462   if (Subtarget->hasBMI()) {
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
464     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467   } else {
468     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
469     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
470     if (Subtarget->is64Bit())
471       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
472   }
473
474   if (Subtarget->hasLZCNT()) {
475     // When promoting the i8 variants, force them to i32 for a shorter
476     // encoding.
477     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
478     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
480     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
482     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
483     if (Subtarget->is64Bit())
484       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485   } else {
486     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
492     if (Subtarget->is64Bit()) {
493       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
494       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
495     }
496   }
497
498   if (Subtarget->hasPOPCNT()) {
499     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
500   } else {
501     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
503     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
504     if (Subtarget->is64Bit())
505       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
506   }
507
508   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
509
510   if (!Subtarget->hasMOVBE())
511     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
512
513   // These should be promoted to a larger select which is supported.
514   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
515   // X86 wants to expand cmov itself.
516   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
528   if (Subtarget->is64Bit()) {
529     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
530     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
531   }
532   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
533   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535   // support continuation, user-level threading, and etc.. As a result, no
536   // other SjLj exception interfaces are implemented and please don't build
537   // your own exception handling based on them.
538   // LLVM/Clang supports zero-cost DWARF exception handling.
539   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
541
542   // Darwin ABI issue.
543   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
544   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
546   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
547   if (Subtarget->is64Bit())
548     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
550   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
551   if (Subtarget->is64Bit()) {
552     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
553     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
554     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
555     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
556     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
557   }
558   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
561   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
562   if (Subtarget->is64Bit()) {
563     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
565     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
566   }
567
568   if (Subtarget->hasSSE1())
569     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
570
571   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
572
573   // Expand certain atomics
574   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575     MVT VT = IntVTs[i];
576     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
579   }
580
581   if (!Subtarget->is64Bit()) {
582     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
594   }
595
596   if (Subtarget->hasCmpxchg16b()) {
597     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
598   }
599
600   // FIXME - use subtarget debug flags
601   if (!Subtarget->isTargetDarwin() &&
602       !Subtarget->isTargetELF() &&
603       !Subtarget->isTargetCygMing()) {
604     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
605   }
606
607   if (Subtarget->is64Bit()) {
608     setExceptionPointerRegister(X86::RAX);
609     setExceptionSelectorRegister(X86::RDX);
610   } else {
611     setExceptionPointerRegister(X86::EAX);
612     setExceptionSelectorRegister(X86::EDX);
613   }
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616
617   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619
620   setOperationAction(ISD::TRAP, MVT::Other, Legal);
621   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622
623   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
625   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
626   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627     // TargetInfo::X86_64ABIBuiltinVaList
628     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
629     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
630   } else {
631     // TargetInfo::CharPtrBuiltinVaList
632     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
633     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
634   }
635
636   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
637   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
638
639   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640                      MVT::i64 : MVT::i32, Custom);
641
642   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643     // f32 and f64 use SSE.
644     // Set up the FP register classes.
645     addRegisterClass(MVT::f32, &X86::FR32RegClass);
646     addRegisterClass(MVT::f64, &X86::FR64RegClass);
647
648     // Use ANDPD to simulate FABS.
649     setOperationAction(ISD::FABS , MVT::f64, Custom);
650     setOperationAction(ISD::FABS , MVT::f32, Custom);
651
652     // Use XORP to simulate FNEG.
653     setOperationAction(ISD::FNEG , MVT::f64, Custom);
654     setOperationAction(ISD::FNEG , MVT::f32, Custom);
655
656     // Use ANDPD and ORPD to simulate FCOPYSIGN.
657     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
659
660     // Lower this to FGETSIGNx86 plus an AND.
661     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
663
664     // We don't support sin/cos/fmod
665     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
666     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
667     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
669     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
670     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
671
672     // Expand FP immediates into loads from the stack, except for the special
673     // cases we handle.
674     addLegalFPImmediate(APFloat(+0.0)); // xorpd
675     addLegalFPImmediate(APFloat(+0.0f)); // xorps
676   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677     // Use SSE for f32, x87 for f64.
678     // Set up the FP register classes.
679     addRegisterClass(MVT::f32, &X86::FR32RegClass);
680     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
681
682     // Use ANDPS to simulate FABS.
683     setOperationAction(ISD::FABS , MVT::f32, Custom);
684
685     // Use XORP to simulate FNEG.
686     setOperationAction(ISD::FNEG , MVT::f32, Custom);
687
688     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
689
690     // Use ANDPS and ORPS to simulate FCOPYSIGN.
691     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
693
694     // We don't support sin/cos/fmod
695     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
696     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
697     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
698
699     // Special cases we handle for FP constants.
700     addLegalFPImmediate(APFloat(+0.0f)); // xorps
701     addLegalFPImmediate(APFloat(+0.0)); // FLD0
702     addLegalFPImmediate(APFloat(+1.0)); // FLD1
703     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
705
706     if (!TM.Options.UnsafeFPMath) {
707       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
708       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
709       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
710     }
711   } else if (!TM.Options.UseSoftFloat) {
712     // f32 and f64 in x87.
713     // Set up the FP register classes.
714     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
716
717     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
718     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
721
722     if (!TM.Options.UnsafeFPMath) {
723       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
724       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
726       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
729     }
730     addLegalFPImmediate(APFloat(+0.0)); // FLD0
731     addLegalFPImmediate(APFloat(+1.0)); // FLD1
732     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
738   }
739
740   // We don't support FMA.
741   setOperationAction(ISD::FMA, MVT::f64, Expand);
742   setOperationAction(ISD::FMA, MVT::f32, Expand);
743
744   // Long double always uses X87.
745   if (!TM.Options.UseSoftFloat) {
746     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
748     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
749     {
750       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751       addLegalFPImmediate(TmpFlt);  // FLD0
752       TmpFlt.changeSign();
753       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
754
755       bool ignored;
756       APFloat TmpFlt2(+1.0);
757       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
758                       &ignored);
759       addLegalFPImmediate(TmpFlt2);  // FLD1
760       TmpFlt2.changeSign();
761       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
762     }
763
764     if (!TM.Options.UnsafeFPMath) {
765       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
766       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
767       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
768     }
769
770     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
772     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
774     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775     setOperationAction(ISD::FMA, MVT::f80, Expand);
776   }
777
778   // Always use a library call for pow.
779   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
781   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
782
783   setOperationAction(ISD::FLOG, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP, MVT::f80, Expand);
787   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
788
789   // First set operation action for all vector types to either promote
790   // (for widening) or expand (for scalarization). Then we will selectively
791   // turn on ones that can be effectively codegen'd.
792   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794     MVT VT = (MVT::SimpleValueType)i;
795     setOperationAction(ISD::ADD , VT, Expand);
796     setOperationAction(ISD::SUB , VT, Expand);
797     setOperationAction(ISD::FADD, VT, Expand);
798     setOperationAction(ISD::FNEG, VT, Expand);
799     setOperationAction(ISD::FSUB, VT, Expand);
800     setOperationAction(ISD::MUL , VT, Expand);
801     setOperationAction(ISD::FMUL, VT, Expand);
802     setOperationAction(ISD::SDIV, VT, Expand);
803     setOperationAction(ISD::UDIV, VT, Expand);
804     setOperationAction(ISD::FDIV, VT, Expand);
805     setOperationAction(ISD::SREM, VT, Expand);
806     setOperationAction(ISD::UREM, VT, Expand);
807     setOperationAction(ISD::LOAD, VT, Expand);
808     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813     setOperationAction(ISD::FABS, VT, Expand);
814     setOperationAction(ISD::FSIN, VT, Expand);
815     setOperationAction(ISD::FSINCOS, VT, Expand);
816     setOperationAction(ISD::FCOS, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FREM, VT, Expand);
819     setOperationAction(ISD::FMA,  VT, Expand);
820     setOperationAction(ISD::FPOWI, VT, Expand);
821     setOperationAction(ISD::FSQRT, VT, Expand);
822     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823     setOperationAction(ISD::FFLOOR, VT, Expand);
824     setOperationAction(ISD::FCEIL, VT, Expand);
825     setOperationAction(ISD::FTRUNC, VT, Expand);
826     setOperationAction(ISD::FRINT, VT, Expand);
827     setOperationAction(ISD::FNEARBYINT, VT, Expand);
828     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829     setOperationAction(ISD::MULHS, VT, Expand);
830     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::MULHU, VT, Expand);
832     setOperationAction(ISD::SDIVREM, VT, Expand);
833     setOperationAction(ISD::UDIVREM, VT, Expand);
834     setOperationAction(ISD::FPOW, VT, Expand);
835     setOperationAction(ISD::CTPOP, VT, Expand);
836     setOperationAction(ISD::CTTZ, VT, Expand);
837     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::CTLZ, VT, Expand);
839     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::SHL, VT, Expand);
841     setOperationAction(ISD::SRA, VT, Expand);
842     setOperationAction(ISD::SRL, VT, Expand);
843     setOperationAction(ISD::ROTL, VT, Expand);
844     setOperationAction(ISD::ROTR, VT, Expand);
845     setOperationAction(ISD::BSWAP, VT, Expand);
846     setOperationAction(ISD::SETCC, VT, Expand);
847     setOperationAction(ISD::FLOG, VT, Expand);
848     setOperationAction(ISD::FLOG2, VT, Expand);
849     setOperationAction(ISD::FLOG10, VT, Expand);
850     setOperationAction(ISD::FEXP, VT, Expand);
851     setOperationAction(ISD::FEXP2, VT, Expand);
852     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857     setOperationAction(ISD::TRUNCATE, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861     setOperationAction(ISD::VSELECT, VT, Expand);
862     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864       setTruncStoreAction(VT,
865                           (MVT::SimpleValueType)InnerVT, Expand);
866     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869   }
870
871   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872   // with -msoft-float, disable use of MMX as well.
873   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875     // No operations on x86mmx supported, everything uses intrinsics.
876   }
877
878   // MMX-sized vectors (other than x86mmx) are expected to be expanded
879   // into smaller operations.
880   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
881   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
884   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
885   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
886   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
887   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
888   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
889   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
890   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
891   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
892   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
893   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
894   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
895   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
900   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
902   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
909
910   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912
913     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
919     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
920     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
921     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
922     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
923     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
925   }
926
927   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929
930     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931     // registers cannot be used even for integer operations.
932     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936
937     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
938     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
939     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
940     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
941     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
942     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
943     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
944     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
945     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
946     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
947     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
948     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
949     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
950     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
951     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
956     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
957     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
958
959     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
962     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
963
964     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
965     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
969
970     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972       MVT VT = (MVT::SimpleValueType)i;
973       // Do not attempt to custom lower non-power-of-2 vectors
974       if (!isPowerOf2_32(VT.getVectorNumElements()))
975         continue;
976       // Do not attempt to custom lower non-128-bit vectors
977       if (!VT.is128BitVector())
978         continue;
979       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
980       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
981       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
982     }
983
984     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
985     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
986     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
987     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
990
991     if (Subtarget->is64Bit()) {
992       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
993       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
994     }
995
996     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998       MVT VT = (MVT::SimpleValueType)i;
999
1000       // Do not attempt to promote non-128-bit vectors
1001       if (!VT.is128BitVector())
1002         continue;
1003
1004       setOperationAction(ISD::AND,    VT, Promote);
1005       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1006       setOperationAction(ISD::OR,     VT, Promote);
1007       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1008       setOperationAction(ISD::XOR,    VT, Promote);
1009       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1010       setOperationAction(ISD::LOAD,   VT, Promote);
1011       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1012       setOperationAction(ISD::SELECT, VT, Promote);
1013       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1014     }
1015
1016     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1017
1018     // Custom lower v2i64 and v2f64 selects.
1019     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1020     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1021     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1022     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1023
1024     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1025     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1026
1027     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1028     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1029     // As there is no 64-bit GPR available, we need build a special custom
1030     // sequence to convert from v2i32 to v2f32.
1031     if (!Subtarget->is64Bit())
1032       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1033
1034     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1035     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1036
1037     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1038   }
1039
1040   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1041     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1042     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1043     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1044     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1045     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1046     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1047     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1048     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1049     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1050     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1051
1052     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1062
1063     // FIXME: Do we need to handle scalar-to-vector here?
1064     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1065     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
1066
1067     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1069     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1070     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1071     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1072
1073     // i8 and i16 vectors are custom , because the source register and source
1074     // source memory operand types are not the same width.  f32 vectors are
1075     // custom since the immediate controlling the insert encodes additional
1076     // information.
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1078     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1079     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1080     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1081
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1083     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1084     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1085     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1086
1087     // FIXME: these should be Legal but thats only for the case where
1088     // the index is constant.  For now custom expand to deal with that.
1089     if (Subtarget->is64Bit()) {
1090       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1091       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1092     }
1093   }
1094
1095   if (Subtarget->hasSSE2()) {
1096     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1098
1099     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1100     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1101
1102     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1103     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1104
1105     // In the customized shift lowering, the legal cases in AVX2 will be
1106     // recognized.
1107     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1108     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1109
1110     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1111     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1112
1113     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1114   }
1115
1116   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1117     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1118     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1119     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1122     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1123
1124     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1125     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1126     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1127
1128     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1133     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1134     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1135     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1136     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1137     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1138     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1139     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1140
1141     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1145     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1146     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1147     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1148     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1149     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1150     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1151     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1152     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1153
1154     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1155     // even though v8i16 is a legal type.
1156     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1157     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1158     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1159
1160     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1161     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1162     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1163
1164     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1165     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1166
1167     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1168
1169     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1182
1183     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1184     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1185     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1186
1187     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1191
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1200     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1203     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1204
1205     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1206       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1209       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1210       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1211       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1212     }
1213
1214     if (Subtarget->hasInt256()) {
1215       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1218       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1219
1220       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1223       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1224
1225       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1226       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1227       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1228       // Don't lower v32i8 because there is no 128-bit byte mul
1229
1230       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1231       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1232       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1233       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1234
1235       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1236     } else {
1237       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1238       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1239       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1240       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1241
1242       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1243       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1244       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1245       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1246
1247       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1248       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1249       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1250       // Don't lower v32i8 because there is no 128-bit byte mul
1251     }
1252
1253     // In the customized shift lowering, the legal cases in AVX2 will be
1254     // recognized.
1255     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1256     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1257
1258     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1259     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1260
1261     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1262
1263     // Custom lower several nodes for 256-bit types.
1264     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1265              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1266       MVT VT = (MVT::SimpleValueType)i;
1267
1268       // Extract subvector is special because the value type
1269       // (result) is 128-bit but the source is 256-bit wide.
1270       if (VT.is128BitVector())
1271         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1272
1273       // Do not attempt to custom lower other non-256-bit vectors
1274       if (!VT.is256BitVector())
1275         continue;
1276
1277       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1278       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1279       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1280       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1281       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1282       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1283       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1284     }
1285
1286     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1287     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1288       MVT VT = (MVT::SimpleValueType)i;
1289
1290       // Do not attempt to promote non-256-bit vectors
1291       if (!VT.is256BitVector())
1292         continue;
1293
1294       setOperationAction(ISD::AND,    VT, Promote);
1295       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1296       setOperationAction(ISD::OR,     VT, Promote);
1297       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1298       setOperationAction(ISD::XOR,    VT, Promote);
1299       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1300       setOperationAction(ISD::LOAD,   VT, Promote);
1301       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1302       setOperationAction(ISD::SELECT, VT, Promote);
1303       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1304     }
1305   }
1306
1307   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1308     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1309     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1310     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1311     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1312
1313     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1314     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1315     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1316
1317     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1318     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1319     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1320     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1321     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1322     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1324     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1326     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1327     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1328
1329     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1330     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1331     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1332     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1333     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1334     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1335
1336     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1337     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1338     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1340     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1341     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1342     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1343     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1344
1345     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1346     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1347     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1348     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1349     if (Subtarget->is64Bit()) {
1350       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1351       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1352       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1353       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1354     }
1355     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1356     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1358     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1359     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1360     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1361     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1363     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1364     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1365
1366     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1368     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1369     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1370     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1371     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1372     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1373     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1374     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1375     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1376     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1377     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1378     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1379
1380     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1382     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1383     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1384     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1386
1387     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1388     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1389
1390     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1391
1392     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1393     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1394     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1395     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1396     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1397     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1398     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1399     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1400     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1401
1402     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1403     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1404
1405     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1406     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1407
1408     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1409
1410     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1411     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1412
1413     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1414     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1415
1416     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1417     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1418
1419     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1420     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1421     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1422     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1423     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1424     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1425
1426     // Custom lower several nodes.
1427     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1428              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1429       MVT VT = (MVT::SimpleValueType)i;
1430
1431       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1432       // Extract subvector is special because the value type
1433       // (result) is 256/128-bit but the source is 512-bit wide.
1434       if (VT.is128BitVector() || VT.is256BitVector())
1435         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1436
1437       if (VT.getVectorElementType() == MVT::i1)
1438         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1439
1440       // Do not attempt to custom lower other non-512-bit vectors
1441       if (!VT.is512BitVector())
1442         continue;
1443
1444       if ( EltSize >= 32) {
1445         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1446         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1447         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1448         setOperationAction(ISD::VSELECT,             VT, Legal);
1449         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1450         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1451         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1452       }
1453     }
1454     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1455       MVT VT = (MVT::SimpleValueType)i;
1456
1457       // Do not attempt to promote non-256-bit vectors
1458       if (!VT.is512BitVector())
1459         continue;
1460
1461       setOperationAction(ISD::SELECT, VT, Promote);
1462       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1463     }
1464   }// has  AVX-512
1465
1466   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1467   // of this type with custom code.
1468   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1469            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1470     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1471                        Custom);
1472   }
1473
1474   // We want to custom lower some of our intrinsics.
1475   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1476   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1477   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1478   if (!Subtarget->is64Bit())
1479     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1480
1481   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1482   // handle type legalization for these operations here.
1483   //
1484   // FIXME: We really should do custom legalization for addition and
1485   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1486   // than generic legalization for 64-bit multiplication-with-overflow, though.
1487   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1488     // Add/Sub/Mul with overflow operations are custom lowered.
1489     MVT VT = IntVTs[i];
1490     setOperationAction(ISD::SADDO, VT, Custom);
1491     setOperationAction(ISD::UADDO, VT, Custom);
1492     setOperationAction(ISD::SSUBO, VT, Custom);
1493     setOperationAction(ISD::USUBO, VT, Custom);
1494     setOperationAction(ISD::SMULO, VT, Custom);
1495     setOperationAction(ISD::UMULO, VT, Custom);
1496   }
1497
1498   // There are no 8-bit 3-address imul/mul instructions
1499   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1500   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1501
1502   if (!Subtarget->is64Bit()) {
1503     // These libcalls are not available in 32-bit.
1504     setLibcallName(RTLIB::SHL_I128, nullptr);
1505     setLibcallName(RTLIB::SRL_I128, nullptr);
1506     setLibcallName(RTLIB::SRA_I128, nullptr);
1507   }
1508
1509   // Combine sin / cos into one node or libcall if possible.
1510   if (Subtarget->hasSinCos()) {
1511     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1512     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1513     if (Subtarget->isTargetDarwin()) {
1514       // For MacOSX, we don't want to the normal expansion of a libcall to
1515       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1516       // traffic.
1517       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1518       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1519     }
1520   }
1521
1522   // We have target-specific dag combine patterns for the following nodes:
1523   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1524   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1525   setTargetDAGCombine(ISD::VSELECT);
1526   setTargetDAGCombine(ISD::SELECT);
1527   setTargetDAGCombine(ISD::SHL);
1528   setTargetDAGCombine(ISD::SRA);
1529   setTargetDAGCombine(ISD::SRL);
1530   setTargetDAGCombine(ISD::OR);
1531   setTargetDAGCombine(ISD::AND);
1532   setTargetDAGCombine(ISD::ADD);
1533   setTargetDAGCombine(ISD::FADD);
1534   setTargetDAGCombine(ISD::FSUB);
1535   setTargetDAGCombine(ISD::FMA);
1536   setTargetDAGCombine(ISD::SUB);
1537   setTargetDAGCombine(ISD::LOAD);
1538   setTargetDAGCombine(ISD::STORE);
1539   setTargetDAGCombine(ISD::ZERO_EXTEND);
1540   setTargetDAGCombine(ISD::ANY_EXTEND);
1541   setTargetDAGCombine(ISD::SIGN_EXTEND);
1542   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1543   setTargetDAGCombine(ISD::TRUNCATE);
1544   setTargetDAGCombine(ISD::SINT_TO_FP);
1545   setTargetDAGCombine(ISD::SETCC);
1546   if (Subtarget->is64Bit())
1547     setTargetDAGCombine(ISD::MUL);
1548   setTargetDAGCombine(ISD::XOR);
1549
1550   computeRegisterProperties();
1551
1552   // On Darwin, -Os means optimize for size without hurting performance,
1553   // do not reduce the limit.
1554   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1555   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1556   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1557   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1558   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1559   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1560   setPrefLoopAlignment(4); // 2^4 bytes.
1561
1562   // Predictable cmov don't hurt on atom because it's in-order.
1563   PredictableSelectIsExpensive = !Subtarget->isAtom();
1564
1565   setPrefFunctionAlignment(4); // 2^4 bytes.
1566 }
1567
1568 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1569   if (!VT.isVector())
1570     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1571
1572   if (Subtarget->hasAVX512())
1573     switch(VT.getVectorNumElements()) {
1574     case  8: return MVT::v8i1;
1575     case 16: return MVT::v16i1;
1576   }
1577
1578   return VT.changeVectorElementTypeToInteger();
1579 }
1580
1581 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1582 /// the desired ByVal argument alignment.
1583 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1584   if (MaxAlign == 16)
1585     return;
1586   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1587     if (VTy->getBitWidth() == 128)
1588       MaxAlign = 16;
1589   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1590     unsigned EltAlign = 0;
1591     getMaxByValAlign(ATy->getElementType(), EltAlign);
1592     if (EltAlign > MaxAlign)
1593       MaxAlign = EltAlign;
1594   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1595     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1596       unsigned EltAlign = 0;
1597       getMaxByValAlign(STy->getElementType(i), EltAlign);
1598       if (EltAlign > MaxAlign)
1599         MaxAlign = EltAlign;
1600       if (MaxAlign == 16)
1601         break;
1602     }
1603   }
1604 }
1605
1606 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1607 /// function arguments in the caller parameter area. For X86, aggregates
1608 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1609 /// are at 4-byte boundaries.
1610 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1611   if (Subtarget->is64Bit()) {
1612     // Max of 8 and alignment of type.
1613     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1614     if (TyAlign > 8)
1615       return TyAlign;
1616     return 8;
1617   }
1618
1619   unsigned Align = 4;
1620   if (Subtarget->hasSSE1())
1621     getMaxByValAlign(Ty, Align);
1622   return Align;
1623 }
1624
1625 /// getOptimalMemOpType - Returns the target specific optimal type for load
1626 /// and store operations as a result of memset, memcpy, and memmove
1627 /// lowering. If DstAlign is zero that means it's safe to destination
1628 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1629 /// means there isn't a need to check it against alignment requirement,
1630 /// probably because the source does not need to be loaded. If 'IsMemset' is
1631 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1632 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1633 /// source is constant so it does not need to be loaded.
1634 /// It returns EVT::Other if the type should be determined using generic
1635 /// target-independent logic.
1636 EVT
1637 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1638                                        unsigned DstAlign, unsigned SrcAlign,
1639                                        bool IsMemset, bool ZeroMemset,
1640                                        bool MemcpyStrSrc,
1641                                        MachineFunction &MF) const {
1642   const Function *F = MF.getFunction();
1643   if ((!IsMemset || ZeroMemset) &&
1644       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1645                                        Attribute::NoImplicitFloat)) {
1646     if (Size >= 16 &&
1647         (Subtarget->isUnalignedMemAccessFast() ||
1648          ((DstAlign == 0 || DstAlign >= 16) &&
1649           (SrcAlign == 0 || SrcAlign >= 16)))) {
1650       if (Size >= 32) {
1651         if (Subtarget->hasInt256())
1652           return MVT::v8i32;
1653         if (Subtarget->hasFp256())
1654           return MVT::v8f32;
1655       }
1656       if (Subtarget->hasSSE2())
1657         return MVT::v4i32;
1658       if (Subtarget->hasSSE1())
1659         return MVT::v4f32;
1660     } else if (!MemcpyStrSrc && Size >= 8 &&
1661                !Subtarget->is64Bit() &&
1662                Subtarget->hasSSE2()) {
1663       // Do not use f64 to lower memcpy if source is string constant. It's
1664       // better to use i32 to avoid the loads.
1665       return MVT::f64;
1666     }
1667   }
1668   if (Subtarget->is64Bit() && Size >= 8)
1669     return MVT::i64;
1670   return MVT::i32;
1671 }
1672
1673 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1674   if (VT == MVT::f32)
1675     return X86ScalarSSEf32;
1676   else if (VT == MVT::f64)
1677     return X86ScalarSSEf64;
1678   return true;
1679 }
1680
1681 bool
1682 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1683                                                  unsigned,
1684                                                  bool *Fast) const {
1685   if (Fast)
1686     *Fast = Subtarget->isUnalignedMemAccessFast();
1687   return true;
1688 }
1689
1690 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1691 /// current function.  The returned value is a member of the
1692 /// MachineJumpTableInfo::JTEntryKind enum.
1693 unsigned X86TargetLowering::getJumpTableEncoding() const {
1694   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1695   // symbol.
1696   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1697       Subtarget->isPICStyleGOT())
1698     return MachineJumpTableInfo::EK_Custom32;
1699
1700   // Otherwise, use the normal jump table encoding heuristics.
1701   return TargetLowering::getJumpTableEncoding();
1702 }
1703
1704 const MCExpr *
1705 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1706                                              const MachineBasicBlock *MBB,
1707                                              unsigned uid,MCContext &Ctx) const{
1708   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1709          Subtarget->isPICStyleGOT());
1710   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1711   // entries.
1712   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1713                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1714 }
1715
1716 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1717 /// jumptable.
1718 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1719                                                     SelectionDAG &DAG) const {
1720   if (!Subtarget->is64Bit())
1721     // This doesn't have SDLoc associated with it, but is not really the
1722     // same as a Register.
1723     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1724   return Table;
1725 }
1726
1727 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1728 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1729 /// MCExpr.
1730 const MCExpr *X86TargetLowering::
1731 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1732                              MCContext &Ctx) const {
1733   // X86-64 uses RIP relative addressing based on the jump table label.
1734   if (Subtarget->isPICStyleRIPRel())
1735     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1736
1737   // Otherwise, the reference is relative to the PIC base.
1738   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1739 }
1740
1741 // FIXME: Why this routine is here? Move to RegInfo!
1742 std::pair<const TargetRegisterClass*, uint8_t>
1743 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1744   const TargetRegisterClass *RRC = nullptr;
1745   uint8_t Cost = 1;
1746   switch (VT.SimpleTy) {
1747   default:
1748     return TargetLowering::findRepresentativeClass(VT);
1749   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1750     RRC = Subtarget->is64Bit() ?
1751       (const TargetRegisterClass*)&X86::GR64RegClass :
1752       (const TargetRegisterClass*)&X86::GR32RegClass;
1753     break;
1754   case MVT::x86mmx:
1755     RRC = &X86::VR64RegClass;
1756     break;
1757   case MVT::f32: case MVT::f64:
1758   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1759   case MVT::v4f32: case MVT::v2f64:
1760   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1761   case MVT::v4f64:
1762     RRC = &X86::VR128RegClass;
1763     break;
1764   }
1765   return std::make_pair(RRC, Cost);
1766 }
1767
1768 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1769                                                unsigned &Offset) const {
1770   if (!Subtarget->isTargetLinux())
1771     return false;
1772
1773   if (Subtarget->is64Bit()) {
1774     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1775     Offset = 0x28;
1776     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1777       AddressSpace = 256;
1778     else
1779       AddressSpace = 257;
1780   } else {
1781     // %gs:0x14 on i386
1782     Offset = 0x14;
1783     AddressSpace = 256;
1784   }
1785   return true;
1786 }
1787
1788 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1789                                             unsigned DestAS) const {
1790   assert(SrcAS != DestAS && "Expected different address spaces!");
1791
1792   return SrcAS < 256 && DestAS < 256;
1793 }
1794
1795 //===----------------------------------------------------------------------===//
1796 //               Return Value Calling Convention Implementation
1797 //===----------------------------------------------------------------------===//
1798
1799 #include "X86GenCallingConv.inc"
1800
1801 bool
1802 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1803                                   MachineFunction &MF, bool isVarArg,
1804                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1805                         LLVMContext &Context) const {
1806   SmallVector<CCValAssign, 16> RVLocs;
1807   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1808                  RVLocs, Context);
1809   return CCInfo.CheckReturn(Outs, RetCC_X86);
1810 }
1811
1812 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1813   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1814   return ScratchRegs;
1815 }
1816
1817 SDValue
1818 X86TargetLowering::LowerReturn(SDValue Chain,
1819                                CallingConv::ID CallConv, bool isVarArg,
1820                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1821                                const SmallVectorImpl<SDValue> &OutVals,
1822                                SDLoc dl, SelectionDAG &DAG) const {
1823   MachineFunction &MF = DAG.getMachineFunction();
1824   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1825
1826   SmallVector<CCValAssign, 16> RVLocs;
1827   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1828                  RVLocs, *DAG.getContext());
1829   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1830
1831   SDValue Flag;
1832   SmallVector<SDValue, 6> RetOps;
1833   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1834   // Operand #1 = Bytes To Pop
1835   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1836                    MVT::i16));
1837
1838   // Copy the result values into the output registers.
1839   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1840     CCValAssign &VA = RVLocs[i];
1841     assert(VA.isRegLoc() && "Can only return in registers!");
1842     SDValue ValToCopy = OutVals[i];
1843     EVT ValVT = ValToCopy.getValueType();
1844
1845     // Promote values to the appropriate types
1846     if (VA.getLocInfo() == CCValAssign::SExt)
1847       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1848     else if (VA.getLocInfo() == CCValAssign::ZExt)
1849       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1850     else if (VA.getLocInfo() == CCValAssign::AExt)
1851       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1852     else if (VA.getLocInfo() == CCValAssign::BCvt)
1853       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1854
1855     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1856            "Unexpected FP-extend for return value.");  
1857
1858     // If this is x86-64, and we disabled SSE, we can't return FP values,
1859     // or SSE or MMX vectors.
1860     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1861          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1862           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1863       report_fatal_error("SSE register return with SSE disabled");
1864     }
1865     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1866     // llvm-gcc has never done it right and no one has noticed, so this
1867     // should be OK for now.
1868     if (ValVT == MVT::f64 &&
1869         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1870       report_fatal_error("SSE2 register return with SSE2 disabled");
1871
1872     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1873     // the RET instruction and handled by the FP Stackifier.
1874     if (VA.getLocReg() == X86::ST0 ||
1875         VA.getLocReg() == X86::ST1) {
1876       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1877       // change the value to the FP stack register class.
1878       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1879         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1880       RetOps.push_back(ValToCopy);
1881       // Don't emit a copytoreg.
1882       continue;
1883     }
1884
1885     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1886     // which is returned in RAX / RDX.
1887     if (Subtarget->is64Bit()) {
1888       if (ValVT == MVT::x86mmx) {
1889         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1890           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1891           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1892                                   ValToCopy);
1893           // If we don't have SSE2 available, convert to v4f32 so the generated
1894           // register is legal.
1895           if (!Subtarget->hasSSE2())
1896             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1897         }
1898       }
1899     }
1900
1901     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1902     Flag = Chain.getValue(1);
1903     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1904   }
1905
1906   // The x86-64 ABIs require that for returning structs by value we copy
1907   // the sret argument into %rax/%eax (depending on ABI) for the return.
1908   // Win32 requires us to put the sret argument to %eax as well.
1909   // We saved the argument into a virtual register in the entry block,
1910   // so now we copy the value out and into %rax/%eax.
1911   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1912       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1913     MachineFunction &MF = DAG.getMachineFunction();
1914     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1915     unsigned Reg = FuncInfo->getSRetReturnReg();
1916     assert(Reg &&
1917            "SRetReturnReg should have been set in LowerFormalArguments().");
1918     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1919
1920     unsigned RetValReg
1921         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1922           X86::RAX : X86::EAX;
1923     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1924     Flag = Chain.getValue(1);
1925
1926     // RAX/EAX now acts like a return value.
1927     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1928   }
1929
1930   RetOps[0] = Chain;  // Update chain.
1931
1932   // Add the flag if we have it.
1933   if (Flag.getNode())
1934     RetOps.push_back(Flag);
1935
1936   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1937 }
1938
1939 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1940   if (N->getNumValues() != 1)
1941     return false;
1942   if (!N->hasNUsesOfValue(1, 0))
1943     return false;
1944
1945   SDValue TCChain = Chain;
1946   SDNode *Copy = *N->use_begin();
1947   if (Copy->getOpcode() == ISD::CopyToReg) {
1948     // If the copy has a glue operand, we conservatively assume it isn't safe to
1949     // perform a tail call.
1950     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1951       return false;
1952     TCChain = Copy->getOperand(0);
1953   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1954     return false;
1955
1956   bool HasRet = false;
1957   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1958        UI != UE; ++UI) {
1959     if (UI->getOpcode() != X86ISD::RET_FLAG)
1960       return false;
1961     HasRet = true;
1962   }
1963
1964   if (!HasRet)
1965     return false;
1966
1967   Chain = TCChain;
1968   return true;
1969 }
1970
1971 MVT
1972 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1973                                             ISD::NodeType ExtendKind) const {
1974   MVT ReturnMVT;
1975   // TODO: Is this also valid on 32-bit?
1976   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1977     ReturnMVT = MVT::i8;
1978   else
1979     ReturnMVT = MVT::i32;
1980
1981   MVT MinVT = getRegisterType(ReturnMVT);
1982   return VT.bitsLT(MinVT) ? MinVT : VT;
1983 }
1984
1985 /// LowerCallResult - Lower the result values of a call into the
1986 /// appropriate copies out of appropriate physical registers.
1987 ///
1988 SDValue
1989 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1990                                    CallingConv::ID CallConv, bool isVarArg,
1991                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1992                                    SDLoc dl, SelectionDAG &DAG,
1993                                    SmallVectorImpl<SDValue> &InVals) const {
1994
1995   // Assign locations to each value returned by this call.
1996   SmallVector<CCValAssign, 16> RVLocs;
1997   bool Is64Bit = Subtarget->is64Bit();
1998   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1999                  getTargetMachine(), RVLocs, *DAG.getContext());
2000   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2001
2002   // Copy all of the result registers out of their specified physreg.
2003   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2004     CCValAssign &VA = RVLocs[i];
2005     EVT CopyVT = VA.getValVT();
2006
2007     // If this is x86-64, and we disabled SSE, we can't return FP values
2008     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2009         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2010       report_fatal_error("SSE register return with SSE disabled");
2011     }
2012
2013     SDValue Val;
2014
2015     // If this is a call to a function that returns an fp value on the floating
2016     // point stack, we must guarantee the value is popped from the stack, so
2017     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2018     // if the return value is not used. We use the FpPOP_RETVAL instruction
2019     // instead.
2020     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2021       // If we prefer to use the value in xmm registers, copy it out as f80 and
2022       // use a truncate to move it from fp stack reg to xmm reg.
2023       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2024       SDValue Ops[] = { Chain, InFlag };
2025       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2026                                          MVT::Other, MVT::Glue, Ops), 1);
2027       Val = Chain.getValue(0);
2028
2029       // Round the f80 to the right size, which also moves it to the appropriate
2030       // xmm register.
2031       if (CopyVT != VA.getValVT())
2032         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2033                           // This truncation won't change the value.
2034                           DAG.getIntPtrConstant(1));
2035     } else {
2036       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2037                                  CopyVT, InFlag).getValue(1);
2038       Val = Chain.getValue(0);
2039     }
2040     InFlag = Chain.getValue(2);
2041     InVals.push_back(Val);
2042   }
2043
2044   return Chain;
2045 }
2046
2047 //===----------------------------------------------------------------------===//
2048 //                C & StdCall & Fast Calling Convention implementation
2049 //===----------------------------------------------------------------------===//
2050 //  StdCall calling convention seems to be standard for many Windows' API
2051 //  routines and around. It differs from C calling convention just a little:
2052 //  callee should clean up the stack, not caller. Symbols should be also
2053 //  decorated in some fancy way :) It doesn't support any vector arguments.
2054 //  For info on fast calling convention see Fast Calling Convention (tail call)
2055 //  implementation LowerX86_32FastCCCallTo.
2056
2057 /// CallIsStructReturn - Determines whether a call uses struct return
2058 /// semantics.
2059 enum StructReturnType {
2060   NotStructReturn,
2061   RegStructReturn,
2062   StackStructReturn
2063 };
2064 static StructReturnType
2065 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2066   if (Outs.empty())
2067     return NotStructReturn;
2068
2069   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2070   if (!Flags.isSRet())
2071     return NotStructReturn;
2072   if (Flags.isInReg())
2073     return RegStructReturn;
2074   return StackStructReturn;
2075 }
2076
2077 /// ArgsAreStructReturn - Determines whether a function uses struct
2078 /// return semantics.
2079 static StructReturnType
2080 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2081   if (Ins.empty())
2082     return NotStructReturn;
2083
2084   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2085   if (!Flags.isSRet())
2086     return NotStructReturn;
2087   if (Flags.isInReg())
2088     return RegStructReturn;
2089   return StackStructReturn;
2090 }
2091
2092 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2093 /// by "Src" to address "Dst" with size and alignment information specified by
2094 /// the specific parameter attribute. The copy will be passed as a byval
2095 /// function parameter.
2096 static SDValue
2097 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2098                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2099                           SDLoc dl) {
2100   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2101
2102   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2103                        /*isVolatile*/false, /*AlwaysInline=*/true,
2104                        MachinePointerInfo(), MachinePointerInfo());
2105 }
2106
2107 /// IsTailCallConvention - Return true if the calling convention is one that
2108 /// supports tail call optimization.
2109 static bool IsTailCallConvention(CallingConv::ID CC) {
2110   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2111           CC == CallingConv::HiPE);
2112 }
2113
2114 /// \brief Return true if the calling convention is a C calling convention.
2115 static bool IsCCallConvention(CallingConv::ID CC) {
2116   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2117           CC == CallingConv::X86_64_SysV);
2118 }
2119
2120 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2121   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2122     return false;
2123
2124   CallSite CS(CI);
2125   CallingConv::ID CalleeCC = CS.getCallingConv();
2126   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2127     return false;
2128
2129   return true;
2130 }
2131
2132 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2133 /// a tailcall target by changing its ABI.
2134 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2135                                    bool GuaranteedTailCallOpt) {
2136   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2137 }
2138
2139 SDValue
2140 X86TargetLowering::LowerMemArgument(SDValue Chain,
2141                                     CallingConv::ID CallConv,
2142                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2143                                     SDLoc dl, SelectionDAG &DAG,
2144                                     const CCValAssign &VA,
2145                                     MachineFrameInfo *MFI,
2146                                     unsigned i) const {
2147   // Create the nodes corresponding to a load from this parameter slot.
2148   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2149   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2150                               getTargetMachine().Options.GuaranteedTailCallOpt);
2151   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2152   EVT ValVT;
2153
2154   // If value is passed by pointer we have address passed instead of the value
2155   // itself.
2156   if (VA.getLocInfo() == CCValAssign::Indirect)
2157     ValVT = VA.getLocVT();
2158   else
2159     ValVT = VA.getValVT();
2160
2161   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2162   // changed with more analysis.
2163   // In case of tail call optimization mark all arguments mutable. Since they
2164   // could be overwritten by lowering of arguments in case of a tail call.
2165   if (Flags.isByVal()) {
2166     unsigned Bytes = Flags.getByValSize();
2167     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2168     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2169     return DAG.getFrameIndex(FI, getPointerTy());
2170   } else {
2171     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2172                                     VA.getLocMemOffset(), isImmutable);
2173     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2174     return DAG.getLoad(ValVT, dl, Chain, FIN,
2175                        MachinePointerInfo::getFixedStack(FI),
2176                        false, false, false, 0);
2177   }
2178 }
2179
2180 SDValue
2181 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2182                                         CallingConv::ID CallConv,
2183                                         bool isVarArg,
2184                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2185                                         SDLoc dl,
2186                                         SelectionDAG &DAG,
2187                                         SmallVectorImpl<SDValue> &InVals)
2188                                           const {
2189   MachineFunction &MF = DAG.getMachineFunction();
2190   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2191
2192   const Function* Fn = MF.getFunction();
2193   if (Fn->hasExternalLinkage() &&
2194       Subtarget->isTargetCygMing() &&
2195       Fn->getName() == "main")
2196     FuncInfo->setForceFramePointer(true);
2197
2198   MachineFrameInfo *MFI = MF.getFrameInfo();
2199   bool Is64Bit = Subtarget->is64Bit();
2200   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2201
2202   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2203          "Var args not supported with calling convention fastcc, ghc or hipe");
2204
2205   // Assign locations to all of the incoming arguments.
2206   SmallVector<CCValAssign, 16> ArgLocs;
2207   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2208                  ArgLocs, *DAG.getContext());
2209
2210   // Allocate shadow area for Win64
2211   if (IsWin64)
2212     CCInfo.AllocateStack(32, 8);
2213
2214   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2215
2216   unsigned LastVal = ~0U;
2217   SDValue ArgValue;
2218   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2219     CCValAssign &VA = ArgLocs[i];
2220     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2221     // places.
2222     assert(VA.getValNo() != LastVal &&
2223            "Don't support value assigned to multiple locs yet");
2224     (void)LastVal;
2225     LastVal = VA.getValNo();
2226
2227     if (VA.isRegLoc()) {
2228       EVT RegVT = VA.getLocVT();
2229       const TargetRegisterClass *RC;
2230       if (RegVT == MVT::i32)
2231         RC = &X86::GR32RegClass;
2232       else if (Is64Bit && RegVT == MVT::i64)
2233         RC = &X86::GR64RegClass;
2234       else if (RegVT == MVT::f32)
2235         RC = &X86::FR32RegClass;
2236       else if (RegVT == MVT::f64)
2237         RC = &X86::FR64RegClass;
2238       else if (RegVT.is512BitVector())
2239         RC = &X86::VR512RegClass;
2240       else if (RegVT.is256BitVector())
2241         RC = &X86::VR256RegClass;
2242       else if (RegVT.is128BitVector())
2243         RC = &X86::VR128RegClass;
2244       else if (RegVT == MVT::x86mmx)
2245         RC = &X86::VR64RegClass;
2246       else if (RegVT == MVT::i1)
2247         RC = &X86::VK1RegClass;
2248       else if (RegVT == MVT::v8i1)
2249         RC = &X86::VK8RegClass;
2250       else if (RegVT == MVT::v16i1)
2251         RC = &X86::VK16RegClass;
2252       else
2253         llvm_unreachable("Unknown argument type!");
2254
2255       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2256       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2257
2258       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2259       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2260       // right size.
2261       if (VA.getLocInfo() == CCValAssign::SExt)
2262         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2263                                DAG.getValueType(VA.getValVT()));
2264       else if (VA.getLocInfo() == CCValAssign::ZExt)
2265         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2266                                DAG.getValueType(VA.getValVT()));
2267       else if (VA.getLocInfo() == CCValAssign::BCvt)
2268         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2269
2270       if (VA.isExtInLoc()) {
2271         // Handle MMX values passed in XMM regs.
2272         if (RegVT.isVector())
2273           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2274         else
2275           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2276       }
2277     } else {
2278       assert(VA.isMemLoc());
2279       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2280     }
2281
2282     // If value is passed via pointer - do a load.
2283     if (VA.getLocInfo() == CCValAssign::Indirect)
2284       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2285                              MachinePointerInfo(), false, false, false, 0);
2286
2287     InVals.push_back(ArgValue);
2288   }
2289
2290   // The x86-64 ABIs require that for returning structs by value we copy
2291   // the sret argument into %rax/%eax (depending on ABI) for the return.
2292   // Win32 requires us to put the sret argument to %eax as well.
2293   // Save the argument into a virtual register so that we can access it
2294   // from the return points.
2295   if (MF.getFunction()->hasStructRetAttr() &&
2296       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2297     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2298     unsigned Reg = FuncInfo->getSRetReturnReg();
2299     if (!Reg) {
2300       MVT PtrTy = getPointerTy();
2301       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2302       FuncInfo->setSRetReturnReg(Reg);
2303     }
2304     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2305     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2306   }
2307
2308   unsigned StackSize = CCInfo.getNextStackOffset();
2309   // Align stack specially for tail calls.
2310   if (FuncIsMadeTailCallSafe(CallConv,
2311                              MF.getTarget().Options.GuaranteedTailCallOpt))
2312     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2313
2314   // If the function takes variable number of arguments, make a frame index for
2315   // the start of the first vararg value... for expansion of llvm.va_start.
2316   if (isVarArg) {
2317     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2318                     CallConv != CallingConv::X86_ThisCall)) {
2319       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2320     }
2321     if (Is64Bit) {
2322       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2323
2324       // FIXME: We should really autogenerate these arrays
2325       static const MCPhysReg GPR64ArgRegsWin64[] = {
2326         X86::RCX, X86::RDX, X86::R8,  X86::R9
2327       };
2328       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2329         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2330       };
2331       static const MCPhysReg XMMArgRegs64Bit[] = {
2332         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2333         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2334       };
2335       const MCPhysReg *GPR64ArgRegs;
2336       unsigned NumXMMRegs = 0;
2337
2338       if (IsWin64) {
2339         // The XMM registers which might contain var arg parameters are shadowed
2340         // in their paired GPR.  So we only need to save the GPR to their home
2341         // slots.
2342         TotalNumIntRegs = 4;
2343         GPR64ArgRegs = GPR64ArgRegsWin64;
2344       } else {
2345         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2346         GPR64ArgRegs = GPR64ArgRegs64Bit;
2347
2348         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2349                                                 TotalNumXMMRegs);
2350       }
2351       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2352                                                        TotalNumIntRegs);
2353
2354       bool NoImplicitFloatOps = Fn->getAttributes().
2355         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2356       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2357              "SSE register cannot be used when SSE is disabled!");
2358       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2359                NoImplicitFloatOps) &&
2360              "SSE register cannot be used when SSE is disabled!");
2361       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2362           !Subtarget->hasSSE1())
2363         // Kernel mode asks for SSE to be disabled, so don't push them
2364         // on the stack.
2365         TotalNumXMMRegs = 0;
2366
2367       if (IsWin64) {
2368         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2369         // Get to the caller-allocated home save location.  Add 8 to account
2370         // for the return address.
2371         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2372         FuncInfo->setRegSaveFrameIndex(
2373           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2374         // Fixup to set vararg frame on shadow area (4 x i64).
2375         if (NumIntRegs < 4)
2376           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2377       } else {
2378         // For X86-64, if there are vararg parameters that are passed via
2379         // registers, then we must store them to their spots on the stack so
2380         // they may be loaded by deferencing the result of va_next.
2381         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2382         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2383         FuncInfo->setRegSaveFrameIndex(
2384           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2385                                false));
2386       }
2387
2388       // Store the integer parameter registers.
2389       SmallVector<SDValue, 8> MemOps;
2390       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2391                                         getPointerTy());
2392       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2393       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2394         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2395                                   DAG.getIntPtrConstant(Offset));
2396         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2397                                      &X86::GR64RegClass);
2398         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2399         SDValue Store =
2400           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2401                        MachinePointerInfo::getFixedStack(
2402                          FuncInfo->getRegSaveFrameIndex(), Offset),
2403                        false, false, 0);
2404         MemOps.push_back(Store);
2405         Offset += 8;
2406       }
2407
2408       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2409         // Now store the XMM (fp + vector) parameter registers.
2410         SmallVector<SDValue, 11> SaveXMMOps;
2411         SaveXMMOps.push_back(Chain);
2412
2413         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2414         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2415         SaveXMMOps.push_back(ALVal);
2416
2417         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418                                FuncInfo->getRegSaveFrameIndex()));
2419         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2420                                FuncInfo->getVarArgsFPOffset()));
2421
2422         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2423           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2424                                        &X86::VR128RegClass);
2425           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2426           SaveXMMOps.push_back(Val);
2427         }
2428         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2429                                      MVT::Other, SaveXMMOps));
2430       }
2431
2432       if (!MemOps.empty())
2433         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2434     }
2435   }
2436
2437   // Some CCs need callee pop.
2438   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2441   } else {
2442     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443     // If this is an sret function, the return should pop the hidden pointer.
2444     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446         argsAreStructReturn(Ins) == StackStructReturn)
2447       FuncInfo->setBytesToPopOnReturn(4);
2448   }
2449
2450   if (!Is64Bit) {
2451     // RegSaveFrameIndex is X86-64 only.
2452     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453     if (CallConv == CallingConv::X86_FastCall ||
2454         CallConv == CallingConv::X86_ThisCall)
2455       // fastcc functions can't have varargs.
2456       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2457   }
2458
2459   FuncInfo->setArgumentStackSize(StackSize);
2460
2461   return Chain;
2462 }
2463
2464 SDValue
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466                                     SDValue StackPtr, SDValue Arg,
2467                                     SDLoc dl, SelectionDAG &DAG,
2468                                     const CCValAssign &VA,
2469                                     ISD::ArgFlagsTy Flags) const {
2470   unsigned LocMemOffset = VA.getLocMemOffset();
2471   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473   if (Flags.isByVal())
2474     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2475
2476   return DAG.getStore(Chain, dl, Arg, PtrOff,
2477                       MachinePointerInfo::getStack(LocMemOffset),
2478                       false, false, 0);
2479 }
2480
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2483 SDValue
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485                                            SDValue &OutRetAddr, SDValue Chain,
2486                                            bool IsTailCall, bool Is64Bit,
2487                                            int FPDiff, SDLoc dl) const {
2488   // Adjust the Return address stack slot.
2489   EVT VT = getPointerTy();
2490   OutRetAddr = getReturnAddressFrameIndex(DAG);
2491
2492   // Load the "old" Return address.
2493   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494                            false, false, false, 0);
2495   return SDValue(OutRetAddr.getNode(), 1);
2496 }
2497
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2500 static SDValue
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2504   // Store the return address to the appropriate stack slot.
2505   if (!FPDiff) return Chain;
2506   // Calculate the new stack slot for the return address.
2507   int NewReturnAddrFI =
2508     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2509                                          false);
2510   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2513                        false, false, 0);
2514   return Chain;
2515 }
2516
2517 SDValue
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519                              SmallVectorImpl<SDValue> &InVals) const {
2520   SelectionDAG &DAG                     = CLI.DAG;
2521   SDLoc &dl                             = CLI.DL;
2522   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2524   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2525   SDValue Chain                         = CLI.Chain;
2526   SDValue Callee                        = CLI.Callee;
2527   CallingConv::ID CallConv              = CLI.CallConv;
2528   bool &isTailCall                      = CLI.IsTailCall;
2529   bool isVarArg                         = CLI.IsVarArg;
2530
2531   MachineFunction &MF = DAG.getMachineFunction();
2532   bool Is64Bit        = Subtarget->is64Bit();
2533   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2534   StructReturnType SR = callIsStructReturn(Outs);
2535   bool IsSibcall      = false;
2536
2537   if (MF.getTarget().Options.DisableTailCalls)
2538     isTailCall = false;
2539
2540   if (isTailCall) {
2541     // Check if it's really possible to do a tail call.
2542     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543                     isVarArg, SR != NotStructReturn,
2544                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545                     Outs, OutVals, Ins, DAG);
2546
2547     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2548       report_fatal_error("failed to perform tail call elimination on a call "
2549                          "site marked musttail");
2550
2551     // Sibcalls are automatically detected tailcalls which do not require
2552     // ABI changes.
2553     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2554       IsSibcall = true;
2555
2556     if (isTailCall)
2557       ++NumTailCalls;
2558   }
2559
2560   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2561          "Var args not supported with calling convention fastcc, ghc or hipe");
2562
2563   // Analyze operands of the call, assigning locations to each operand.
2564   SmallVector<CCValAssign, 16> ArgLocs;
2565   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2566                  ArgLocs, *DAG.getContext());
2567
2568   // Allocate shadow area for Win64
2569   if (IsWin64)
2570     CCInfo.AllocateStack(32, 8);
2571
2572   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2573
2574   // Get a count of how many bytes are to be pushed on the stack.
2575   unsigned NumBytes = CCInfo.getNextStackOffset();
2576   if (IsSibcall)
2577     // This is a sibcall. The memory operands are available in caller's
2578     // own caller's stack.
2579     NumBytes = 0;
2580   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2581            IsTailCallConvention(CallConv))
2582     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2583
2584   int FPDiff = 0;
2585   if (isTailCall && !IsSibcall) {
2586     // Lower arguments at fp - stackoffset + fpdiff.
2587     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2588     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2589
2590     FPDiff = NumBytesCallerPushed - NumBytes;
2591
2592     // Set the delta of movement of the returnaddr stackslot.
2593     // But only set if delta is greater than previous delta.
2594     if (FPDiff < X86Info->getTCReturnAddrDelta())
2595       X86Info->setTCReturnAddrDelta(FPDiff);
2596   }
2597
2598   unsigned NumBytesToPush = NumBytes;
2599   unsigned NumBytesToPop = NumBytes;
2600
2601   // If we have an inalloca argument, all stack space has already been allocated
2602   // for us and be right at the top of the stack.  We don't support multiple
2603   // arguments passed in memory when using inalloca.
2604   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2605     NumBytesToPush = 0;
2606     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2607            "an inalloca argument must be the only memory argument");
2608   }
2609
2610   if (!IsSibcall)
2611     Chain = DAG.getCALLSEQ_START(
2612         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2613
2614   SDValue RetAddrFrIdx;
2615   // Load return address for tail calls.
2616   if (isTailCall && FPDiff)
2617     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2618                                     Is64Bit, FPDiff, dl);
2619
2620   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2621   SmallVector<SDValue, 8> MemOpChains;
2622   SDValue StackPtr;
2623
2624   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2625   // of tail call optimization arguments are handle later.
2626   const X86RegisterInfo *RegInfo =
2627     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2628   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629     // Skip inalloca arguments, they have already been written.
2630     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2631     if (Flags.isInAlloca())
2632       continue;
2633
2634     CCValAssign &VA = ArgLocs[i];
2635     EVT RegVT = VA.getLocVT();
2636     SDValue Arg = OutVals[i];
2637     bool isByVal = Flags.isByVal();
2638
2639     // Promote the value if needed.
2640     switch (VA.getLocInfo()) {
2641     default: llvm_unreachable("Unknown loc info!");
2642     case CCValAssign::Full: break;
2643     case CCValAssign::SExt:
2644       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2645       break;
2646     case CCValAssign::ZExt:
2647       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2648       break;
2649     case CCValAssign::AExt:
2650       if (RegVT.is128BitVector()) {
2651         // Special case: passing MMX values in XMM registers.
2652         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2653         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2654         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2655       } else
2656         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2657       break;
2658     case CCValAssign::BCvt:
2659       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2660       break;
2661     case CCValAssign::Indirect: {
2662       // Store the argument.
2663       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2664       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2665       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2666                            MachinePointerInfo::getFixedStack(FI),
2667                            false, false, 0);
2668       Arg = SpillSlot;
2669       break;
2670     }
2671     }
2672
2673     if (VA.isRegLoc()) {
2674       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2675       if (isVarArg && IsWin64) {
2676         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2677         // shadow reg if callee is a varargs function.
2678         unsigned ShadowReg = 0;
2679         switch (VA.getLocReg()) {
2680         case X86::XMM0: ShadowReg = X86::RCX; break;
2681         case X86::XMM1: ShadowReg = X86::RDX; break;
2682         case X86::XMM2: ShadowReg = X86::R8; break;
2683         case X86::XMM3: ShadowReg = X86::R9; break;
2684         }
2685         if (ShadowReg)
2686           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2687       }
2688     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2689       assert(VA.isMemLoc());
2690       if (!StackPtr.getNode())
2691         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2692                                       getPointerTy());
2693       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2694                                              dl, DAG, VA, Flags));
2695     }
2696   }
2697
2698   if (!MemOpChains.empty())
2699     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2700
2701   if (Subtarget->isPICStyleGOT()) {
2702     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2703     // GOT pointer.
2704     if (!isTailCall) {
2705       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2706                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2707     } else {
2708       // If we are tail calling and generating PIC/GOT style code load the
2709       // address of the callee into ECX. The value in ecx is used as target of
2710       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2711       // for tail calls on PIC/GOT architectures. Normally we would just put the
2712       // address of GOT into ebx and then call target@PLT. But for tail calls
2713       // ebx would be restored (since ebx is callee saved) before jumping to the
2714       // target@PLT.
2715
2716       // Note: The actual moving to ECX is done further down.
2717       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2718       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2719           !G->getGlobal()->hasProtectedVisibility())
2720         Callee = LowerGlobalAddress(Callee, DAG);
2721       else if (isa<ExternalSymbolSDNode>(Callee))
2722         Callee = LowerExternalSymbol(Callee, DAG);
2723     }
2724   }
2725
2726   if (Is64Bit && isVarArg && !IsWin64) {
2727     // From AMD64 ABI document:
2728     // For calls that may call functions that use varargs or stdargs
2729     // (prototype-less calls or calls to functions containing ellipsis (...) in
2730     // the declaration) %al is used as hidden argument to specify the number
2731     // of SSE registers used. The contents of %al do not need to match exactly
2732     // the number of registers, but must be an ubound on the number of SSE
2733     // registers used and is in the range 0 - 8 inclusive.
2734
2735     // Count the number of XMM registers allocated.
2736     static const MCPhysReg XMMArgRegs[] = {
2737       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2738       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2739     };
2740     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2741     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2742            && "SSE registers cannot be used when SSE is disabled");
2743
2744     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2745                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2746   }
2747
2748   // For tail calls lower the arguments to the 'real' stack slot.
2749   if (isTailCall) {
2750     // Force all the incoming stack arguments to be loaded from the stack
2751     // before any new outgoing arguments are stored to the stack, because the
2752     // outgoing stack slots may alias the incoming argument stack slots, and
2753     // the alias isn't otherwise explicit. This is slightly more conservative
2754     // than necessary, because it means that each store effectively depends
2755     // on every argument instead of just those arguments it would clobber.
2756     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2757
2758     SmallVector<SDValue, 8> MemOpChains2;
2759     SDValue FIN;
2760     int FI = 0;
2761     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2762       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2763         CCValAssign &VA = ArgLocs[i];
2764         if (VA.isRegLoc())
2765           continue;
2766         assert(VA.isMemLoc());
2767         SDValue Arg = OutVals[i];
2768         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2769         // Create frame index.
2770         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2771         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2772         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2773         FIN = DAG.getFrameIndex(FI, getPointerTy());
2774
2775         if (Flags.isByVal()) {
2776           // Copy relative to framepointer.
2777           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2778           if (!StackPtr.getNode())
2779             StackPtr = DAG.getCopyFromReg(Chain, dl,
2780                                           RegInfo->getStackRegister(),
2781                                           getPointerTy());
2782           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2783
2784           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2785                                                            ArgChain,
2786                                                            Flags, DAG, dl));
2787         } else {
2788           // Store relative to framepointer.
2789           MemOpChains2.push_back(
2790             DAG.getStore(ArgChain, dl, Arg, FIN,
2791                          MachinePointerInfo::getFixedStack(FI),
2792                          false, false, 0));
2793         }
2794       }
2795     }
2796
2797     if (!MemOpChains2.empty())
2798       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2799
2800     // Store the return address to the appropriate stack slot.
2801     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2802                                      getPointerTy(), RegInfo->getSlotSize(),
2803                                      FPDiff, dl);
2804   }
2805
2806   // Build a sequence of copy-to-reg nodes chained together with token chain
2807   // and flag operands which copy the outgoing args into registers.
2808   SDValue InFlag;
2809   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2810     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2811                              RegsToPass[i].second, InFlag);
2812     InFlag = Chain.getValue(1);
2813   }
2814
2815   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2816     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2817     // In the 64-bit large code model, we have to make all calls
2818     // through a register, since the call instruction's 32-bit
2819     // pc-relative offset may not be large enough to hold the whole
2820     // address.
2821   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2822     // If the callee is a GlobalAddress node (quite common, every direct call
2823     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2824     // it.
2825
2826     // We should use extra load for direct calls to dllimported functions in
2827     // non-JIT mode.
2828     const GlobalValue *GV = G->getGlobal();
2829     if (!GV->hasDLLImportStorageClass()) {
2830       unsigned char OpFlags = 0;
2831       bool ExtraLoad = false;
2832       unsigned WrapperKind = ISD::DELETED_NODE;
2833
2834       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2835       // external symbols most go through the PLT in PIC mode.  If the symbol
2836       // has hidden or protected visibility, or if it is static or local, then
2837       // we don't need to use the PLT - we can directly call it.
2838       if (Subtarget->isTargetELF() &&
2839           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2840           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2841         OpFlags = X86II::MO_PLT;
2842       } else if (Subtarget->isPICStyleStubAny() &&
2843                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2844                  (!Subtarget->getTargetTriple().isMacOSX() ||
2845                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2846         // PC-relative references to external symbols should go through $stub,
2847         // unless we're building with the leopard linker or later, which
2848         // automatically synthesizes these stubs.
2849         OpFlags = X86II::MO_DARWIN_STUB;
2850       } else if (Subtarget->isPICStyleRIPRel() &&
2851                  isa<Function>(GV) &&
2852                  cast<Function>(GV)->getAttributes().
2853                    hasAttribute(AttributeSet::FunctionIndex,
2854                                 Attribute::NonLazyBind)) {
2855         // If the function is marked as non-lazy, generate an indirect call
2856         // which loads from the GOT directly. This avoids runtime overhead
2857         // at the cost of eager binding (and one extra byte of encoding).
2858         OpFlags = X86II::MO_GOTPCREL;
2859         WrapperKind = X86ISD::WrapperRIP;
2860         ExtraLoad = true;
2861       }
2862
2863       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2864                                           G->getOffset(), OpFlags);
2865
2866       // Add a wrapper if needed.
2867       if (WrapperKind != ISD::DELETED_NODE)
2868         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2869       // Add extra indirection if needed.
2870       if (ExtraLoad)
2871         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2872                              MachinePointerInfo::getGOT(),
2873                              false, false, false, 0);
2874     }
2875   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2876     unsigned char OpFlags = 0;
2877
2878     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2879     // external symbols should go through the PLT.
2880     if (Subtarget->isTargetELF() &&
2881         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2882       OpFlags = X86II::MO_PLT;
2883     } else if (Subtarget->isPICStyleStubAny() &&
2884                (!Subtarget->getTargetTriple().isMacOSX() ||
2885                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2886       // PC-relative references to external symbols should go through $stub,
2887       // unless we're building with the leopard linker or later, which
2888       // automatically synthesizes these stubs.
2889       OpFlags = X86II::MO_DARWIN_STUB;
2890     }
2891
2892     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2893                                          OpFlags);
2894   }
2895
2896   // Returns a chain & a flag for retval copy to use.
2897   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2898   SmallVector<SDValue, 8> Ops;
2899
2900   if (!IsSibcall && isTailCall) {
2901     Chain = DAG.getCALLSEQ_END(Chain,
2902                                DAG.getIntPtrConstant(NumBytesToPop, true),
2903                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2904     InFlag = Chain.getValue(1);
2905   }
2906
2907   Ops.push_back(Chain);
2908   Ops.push_back(Callee);
2909
2910   if (isTailCall)
2911     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2912
2913   // Add argument registers to the end of the list so that they are known live
2914   // into the call.
2915   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2916     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2917                                   RegsToPass[i].second.getValueType()));
2918
2919   // Add a register mask operand representing the call-preserved registers.
2920   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2921   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2922   assert(Mask && "Missing call preserved mask for calling convention");
2923   Ops.push_back(DAG.getRegisterMask(Mask));
2924
2925   if (InFlag.getNode())
2926     Ops.push_back(InFlag);
2927
2928   if (isTailCall) {
2929     // We used to do:
2930     //// If this is the first return lowered for this function, add the regs
2931     //// to the liveout set for the function.
2932     // This isn't right, although it's probably harmless on x86; liveouts
2933     // should be computed from returns not tail calls.  Consider a void
2934     // function making a tail call to a function returning int.
2935     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2936   }
2937
2938   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2939   InFlag = Chain.getValue(1);
2940
2941   // Create the CALLSEQ_END node.
2942   unsigned NumBytesForCalleeToPop;
2943   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2944                        getTargetMachine().Options.GuaranteedTailCallOpt))
2945     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2946   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2947            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2948            SR == StackStructReturn)
2949     // If this is a call to a struct-return function, the callee
2950     // pops the hidden struct pointer, so we have to push it back.
2951     // This is common for Darwin/X86, Linux & Mingw32 targets.
2952     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2953     NumBytesForCalleeToPop = 4;
2954   else
2955     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2956
2957   // Returns a flag for retval copy to use.
2958   if (!IsSibcall) {
2959     Chain = DAG.getCALLSEQ_END(Chain,
2960                                DAG.getIntPtrConstant(NumBytesToPop, true),
2961                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2962                                                      true),
2963                                InFlag, dl);
2964     InFlag = Chain.getValue(1);
2965   }
2966
2967   // Handle result values, copying them out of physregs into vregs that we
2968   // return.
2969   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2970                          Ins, dl, DAG, InVals);
2971 }
2972
2973 //===----------------------------------------------------------------------===//
2974 //                Fast Calling Convention (tail call) implementation
2975 //===----------------------------------------------------------------------===//
2976
2977 //  Like std call, callee cleans arguments, convention except that ECX is
2978 //  reserved for storing the tail called function address. Only 2 registers are
2979 //  free for argument passing (inreg). Tail call optimization is performed
2980 //  provided:
2981 //                * tailcallopt is enabled
2982 //                * caller/callee are fastcc
2983 //  On X86_64 architecture with GOT-style position independent code only local
2984 //  (within module) calls are supported at the moment.
2985 //  To keep the stack aligned according to platform abi the function
2986 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2987 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2988 //  If a tail called function callee has more arguments than the caller the
2989 //  caller needs to make sure that there is room to move the RETADDR to. This is
2990 //  achieved by reserving an area the size of the argument delta right after the
2991 //  original REtADDR, but before the saved framepointer or the spilled registers
2992 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2993 //  stack layout:
2994 //    arg1
2995 //    arg2
2996 //    RETADDR
2997 //    [ new RETADDR
2998 //      move area ]
2999 //    (possible EBP)
3000 //    ESI
3001 //    EDI
3002 //    local1 ..
3003
3004 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3005 /// for a 16 byte align requirement.
3006 unsigned
3007 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3008                                                SelectionDAG& DAG) const {
3009   MachineFunction &MF = DAG.getMachineFunction();
3010   const TargetMachine &TM = MF.getTarget();
3011   const X86RegisterInfo *RegInfo =
3012     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3013   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3014   unsigned StackAlignment = TFI.getStackAlignment();
3015   uint64_t AlignMask = StackAlignment - 1;
3016   int64_t Offset = StackSize;
3017   unsigned SlotSize = RegInfo->getSlotSize();
3018   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3019     // Number smaller than 12 so just add the difference.
3020     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3021   } else {
3022     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3023     Offset = ((~AlignMask) & Offset) + StackAlignment +
3024       (StackAlignment-SlotSize);
3025   }
3026   return Offset;
3027 }
3028
3029 /// MatchingStackOffset - Return true if the given stack call argument is
3030 /// already available in the same position (relatively) of the caller's
3031 /// incoming argument stack.
3032 static
3033 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3034                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3035                          const X86InstrInfo *TII) {
3036   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3037   int FI = INT_MAX;
3038   if (Arg.getOpcode() == ISD::CopyFromReg) {
3039     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3040     if (!TargetRegisterInfo::isVirtualRegister(VR))
3041       return false;
3042     MachineInstr *Def = MRI->getVRegDef(VR);
3043     if (!Def)
3044       return false;
3045     if (!Flags.isByVal()) {
3046       if (!TII->isLoadFromStackSlot(Def, FI))
3047         return false;
3048     } else {
3049       unsigned Opcode = Def->getOpcode();
3050       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3051           Def->getOperand(1).isFI()) {
3052         FI = Def->getOperand(1).getIndex();
3053         Bytes = Flags.getByValSize();
3054       } else
3055         return false;
3056     }
3057   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3058     if (Flags.isByVal())
3059       // ByVal argument is passed in as a pointer but it's now being
3060       // dereferenced. e.g.
3061       // define @foo(%struct.X* %A) {
3062       //   tail call @bar(%struct.X* byval %A)
3063       // }
3064       return false;
3065     SDValue Ptr = Ld->getBasePtr();
3066     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3067     if (!FINode)
3068       return false;
3069     FI = FINode->getIndex();
3070   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3071     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3072     FI = FINode->getIndex();
3073     Bytes = Flags.getByValSize();
3074   } else
3075     return false;
3076
3077   assert(FI != INT_MAX);
3078   if (!MFI->isFixedObjectIndex(FI))
3079     return false;
3080   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3081 }
3082
3083 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3084 /// for tail call optimization. Targets which want to do tail call
3085 /// optimization should implement this function.
3086 bool
3087 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3088                                                      CallingConv::ID CalleeCC,
3089                                                      bool isVarArg,
3090                                                      bool isCalleeStructRet,
3091                                                      bool isCallerStructRet,
3092                                                      Type *RetTy,
3093                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3094                                     const SmallVectorImpl<SDValue> &OutVals,
3095                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3096                                                      SelectionDAG &DAG) const {
3097   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3098     return false;
3099
3100   // If -tailcallopt is specified, make fastcc functions tail-callable.
3101   const MachineFunction &MF = DAG.getMachineFunction();
3102   const Function *CallerF = MF.getFunction();
3103
3104   // If the function return type is x86_fp80 and the callee return type is not,
3105   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3106   // perform a tailcall optimization here.
3107   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3108     return false;
3109
3110   CallingConv::ID CallerCC = CallerF->getCallingConv();
3111   bool CCMatch = CallerCC == CalleeCC;
3112   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3113   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3114
3115   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3116     if (IsTailCallConvention(CalleeCC) && CCMatch)
3117       return true;
3118     return false;
3119   }
3120
3121   // Look for obvious safe cases to perform tail call optimization that do not
3122   // require ABI changes. This is what gcc calls sibcall.
3123
3124   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3125   // emit a special epilogue.
3126   const X86RegisterInfo *RegInfo =
3127     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3128   if (RegInfo->needsStackRealignment(MF))
3129     return false;
3130
3131   // Also avoid sibcall optimization if either caller or callee uses struct
3132   // return semantics.
3133   if (isCalleeStructRet || isCallerStructRet)
3134     return false;
3135
3136   // An stdcall/thiscall caller is expected to clean up its arguments; the
3137   // callee isn't going to do that.
3138   // FIXME: this is more restrictive than needed. We could produce a tailcall
3139   // when the stack adjustment matches. For example, with a thiscall that takes
3140   // only one argument.
3141   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3142                    CallerCC == CallingConv::X86_ThisCall))
3143     return false;
3144
3145   // Do not sibcall optimize vararg calls unless all arguments are passed via
3146   // registers.
3147   if (isVarArg && !Outs.empty()) {
3148
3149     // Optimizing for varargs on Win64 is unlikely to be safe without
3150     // additional testing.
3151     if (IsCalleeWin64 || IsCallerWin64)
3152       return false;
3153
3154     SmallVector<CCValAssign, 16> ArgLocs;
3155     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3156                    getTargetMachine(), ArgLocs, *DAG.getContext());
3157
3158     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3159     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3160       if (!ArgLocs[i].isRegLoc())
3161         return false;
3162   }
3163
3164   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3165   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3166   // this into a sibcall.
3167   bool Unused = false;
3168   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3169     if (!Ins[i].Used) {
3170       Unused = true;
3171       break;
3172     }
3173   }
3174   if (Unused) {
3175     SmallVector<CCValAssign, 16> RVLocs;
3176     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3177                    getTargetMachine(), RVLocs, *DAG.getContext());
3178     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3179     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3180       CCValAssign &VA = RVLocs[i];
3181       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3182         return false;
3183     }
3184   }
3185
3186   // If the calling conventions do not match, then we'd better make sure the
3187   // results are returned in the same way as what the caller expects.
3188   if (!CCMatch) {
3189     SmallVector<CCValAssign, 16> RVLocs1;
3190     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3191                     getTargetMachine(), RVLocs1, *DAG.getContext());
3192     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3193
3194     SmallVector<CCValAssign, 16> RVLocs2;
3195     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3196                     getTargetMachine(), RVLocs2, *DAG.getContext());
3197     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3198
3199     if (RVLocs1.size() != RVLocs2.size())
3200       return false;
3201     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3202       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3203         return false;
3204       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3205         return false;
3206       if (RVLocs1[i].isRegLoc()) {
3207         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3208           return false;
3209       } else {
3210         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3211           return false;
3212       }
3213     }
3214   }
3215
3216   // If the callee takes no arguments then go on to check the results of the
3217   // call.
3218   if (!Outs.empty()) {
3219     // Check if stack adjustment is needed. For now, do not do this if any
3220     // argument is passed on the stack.
3221     SmallVector<CCValAssign, 16> ArgLocs;
3222     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3223                    getTargetMachine(), ArgLocs, *DAG.getContext());
3224
3225     // Allocate shadow area for Win64
3226     if (IsCalleeWin64)
3227       CCInfo.AllocateStack(32, 8);
3228
3229     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3230     if (CCInfo.getNextStackOffset()) {
3231       MachineFunction &MF = DAG.getMachineFunction();
3232       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3233         return false;
3234
3235       // Check if the arguments are already laid out in the right way as
3236       // the caller's fixed stack objects.
3237       MachineFrameInfo *MFI = MF.getFrameInfo();
3238       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3239       const X86InstrInfo *TII =
3240         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3241       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3242         CCValAssign &VA = ArgLocs[i];
3243         SDValue Arg = OutVals[i];
3244         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3245         if (VA.getLocInfo() == CCValAssign::Indirect)
3246           return false;
3247         if (!VA.isRegLoc()) {
3248           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3249                                    MFI, MRI, TII))
3250             return false;
3251         }
3252       }
3253     }
3254
3255     // If the tailcall address may be in a register, then make sure it's
3256     // possible to register allocate for it. In 32-bit, the call address can
3257     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3258     // callee-saved registers are restored. These happen to be the same
3259     // registers used to pass 'inreg' arguments so watch out for those.
3260     if (!Subtarget->is64Bit() &&
3261         ((!isa<GlobalAddressSDNode>(Callee) &&
3262           !isa<ExternalSymbolSDNode>(Callee)) ||
3263          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3264       unsigned NumInRegs = 0;
3265       // In PIC we need an extra register to formulate the address computation
3266       // for the callee.
3267       unsigned MaxInRegs =
3268           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3269
3270       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3271         CCValAssign &VA = ArgLocs[i];
3272         if (!VA.isRegLoc())
3273           continue;
3274         unsigned Reg = VA.getLocReg();
3275         switch (Reg) {
3276         default: break;
3277         case X86::EAX: case X86::EDX: case X86::ECX:
3278           if (++NumInRegs == MaxInRegs)
3279             return false;
3280           break;
3281         }
3282       }
3283     }
3284   }
3285
3286   return true;
3287 }
3288
3289 FastISel *
3290 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3291                                   const TargetLibraryInfo *libInfo) const {
3292   return X86::createFastISel(funcInfo, libInfo);
3293 }
3294
3295 //===----------------------------------------------------------------------===//
3296 //                           Other Lowering Hooks
3297 //===----------------------------------------------------------------------===//
3298
3299 static bool MayFoldLoad(SDValue Op) {
3300   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3301 }
3302
3303 static bool MayFoldIntoStore(SDValue Op) {
3304   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3305 }
3306
3307 static bool isTargetShuffle(unsigned Opcode) {
3308   switch(Opcode) {
3309   default: return false;
3310   case X86ISD::PSHUFD:
3311   case X86ISD::PSHUFHW:
3312   case X86ISD::PSHUFLW:
3313   case X86ISD::SHUFP:
3314   case X86ISD::PALIGNR:
3315   case X86ISD::MOVLHPS:
3316   case X86ISD::MOVLHPD:
3317   case X86ISD::MOVHLPS:
3318   case X86ISD::MOVLPS:
3319   case X86ISD::MOVLPD:
3320   case X86ISD::MOVSHDUP:
3321   case X86ISD::MOVSLDUP:
3322   case X86ISD::MOVDDUP:
3323   case X86ISD::MOVSS:
3324   case X86ISD::MOVSD:
3325   case X86ISD::UNPCKL:
3326   case X86ISD::UNPCKH:
3327   case X86ISD::VPERMILP:
3328   case X86ISD::VPERM2X128:
3329   case X86ISD::VPERMI:
3330     return true;
3331   }
3332 }
3333
3334 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3335                                     SDValue V1, SelectionDAG &DAG) {
3336   switch(Opc) {
3337   default: llvm_unreachable("Unknown x86 shuffle node");
3338   case X86ISD::MOVSHDUP:
3339   case X86ISD::MOVSLDUP:
3340   case X86ISD::MOVDDUP:
3341     return DAG.getNode(Opc, dl, VT, V1);
3342   }
3343 }
3344
3345 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3346                                     SDValue V1, unsigned TargetMask,
3347                                     SelectionDAG &DAG) {
3348   switch(Opc) {
3349   default: llvm_unreachable("Unknown x86 shuffle node");
3350   case X86ISD::PSHUFD:
3351   case X86ISD::PSHUFHW:
3352   case X86ISD::PSHUFLW:
3353   case X86ISD::VPERMILP:
3354   case X86ISD::VPERMI:
3355     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3356   }
3357 }
3358
3359 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3360                                     SDValue V1, SDValue V2, unsigned TargetMask,
3361                                     SelectionDAG &DAG) {
3362   switch(Opc) {
3363   default: llvm_unreachable("Unknown x86 shuffle node");
3364   case X86ISD::PALIGNR:
3365   case X86ISD::SHUFP:
3366   case X86ISD::VPERM2X128:
3367     return DAG.getNode(Opc, dl, VT, V1, V2,
3368                        DAG.getConstant(TargetMask, MVT::i8));
3369   }
3370 }
3371
3372 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3373                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3374   switch(Opc) {
3375   default: llvm_unreachable("Unknown x86 shuffle node");
3376   case X86ISD::MOVLHPS:
3377   case X86ISD::MOVLHPD:
3378   case X86ISD::MOVHLPS:
3379   case X86ISD::MOVLPS:
3380   case X86ISD::MOVLPD:
3381   case X86ISD::MOVSS:
3382   case X86ISD::MOVSD:
3383   case X86ISD::UNPCKL:
3384   case X86ISD::UNPCKH:
3385     return DAG.getNode(Opc, dl, VT, V1, V2);
3386   }
3387 }
3388
3389 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3390   MachineFunction &MF = DAG.getMachineFunction();
3391   const X86RegisterInfo *RegInfo =
3392     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3393   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3394   int ReturnAddrIndex = FuncInfo->getRAIndex();
3395
3396   if (ReturnAddrIndex == 0) {
3397     // Set up a frame object for the return address.
3398     unsigned SlotSize = RegInfo->getSlotSize();
3399     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3400                                                            -(int64_t)SlotSize,
3401                                                            false);
3402     FuncInfo->setRAIndex(ReturnAddrIndex);
3403   }
3404
3405   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3406 }
3407
3408 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3409                                        bool hasSymbolicDisplacement) {
3410   // Offset should fit into 32 bit immediate field.
3411   if (!isInt<32>(Offset))
3412     return false;
3413
3414   // If we don't have a symbolic displacement - we don't have any extra
3415   // restrictions.
3416   if (!hasSymbolicDisplacement)
3417     return true;
3418
3419   // FIXME: Some tweaks might be needed for medium code model.
3420   if (M != CodeModel::Small && M != CodeModel::Kernel)
3421     return false;
3422
3423   // For small code model we assume that latest object is 16MB before end of 31
3424   // bits boundary. We may also accept pretty large negative constants knowing
3425   // that all objects are in the positive half of address space.
3426   if (M == CodeModel::Small && Offset < 16*1024*1024)
3427     return true;
3428
3429   // For kernel code model we know that all object resist in the negative half
3430   // of 32bits address space. We may not accept negative offsets, since they may
3431   // be just off and we may accept pretty large positive ones.
3432   if (M == CodeModel::Kernel && Offset > 0)
3433     return true;
3434
3435   return false;
3436 }
3437
3438 /// isCalleePop - Determines whether the callee is required to pop its
3439 /// own arguments. Callee pop is necessary to support tail calls.
3440 bool X86::isCalleePop(CallingConv::ID CallingConv,
3441                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3442   if (IsVarArg)
3443     return false;
3444
3445   switch (CallingConv) {
3446   default:
3447     return false;
3448   case CallingConv::X86_StdCall:
3449     return !is64Bit;
3450   case CallingConv::X86_FastCall:
3451     return !is64Bit;
3452   case CallingConv::X86_ThisCall:
3453     return !is64Bit;
3454   case CallingConv::Fast:
3455     return TailCallOpt;
3456   case CallingConv::GHC:
3457     return TailCallOpt;
3458   case CallingConv::HiPE:
3459     return TailCallOpt;
3460   }
3461 }
3462
3463 /// \brief Return true if the condition is an unsigned comparison operation.
3464 static bool isX86CCUnsigned(unsigned X86CC) {
3465   switch (X86CC) {
3466   default: llvm_unreachable("Invalid integer condition!");
3467   case X86::COND_E:     return true;
3468   case X86::COND_G:     return false;
3469   case X86::COND_GE:    return false;
3470   case X86::COND_L:     return false;
3471   case X86::COND_LE:    return false;
3472   case X86::COND_NE:    return true;
3473   case X86::COND_B:     return true;
3474   case X86::COND_A:     return true;
3475   case X86::COND_BE:    return true;
3476   case X86::COND_AE:    return true;
3477   }
3478   llvm_unreachable("covered switch fell through?!");
3479 }
3480
3481 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3482 /// specific condition code, returning the condition code and the LHS/RHS of the
3483 /// comparison to make.
3484 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3485                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3486   if (!isFP) {
3487     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3488       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3489         // X > -1   -> X == 0, jump !sign.
3490         RHS = DAG.getConstant(0, RHS.getValueType());
3491         return X86::COND_NS;
3492       }
3493       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3494         // X < 0   -> X == 0, jump on sign.
3495         return X86::COND_S;
3496       }
3497       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3498         // X < 1   -> X <= 0
3499         RHS = DAG.getConstant(0, RHS.getValueType());
3500         return X86::COND_LE;
3501       }
3502     }
3503
3504     switch (SetCCOpcode) {
3505     default: llvm_unreachable("Invalid integer condition!");
3506     case ISD::SETEQ:  return X86::COND_E;
3507     case ISD::SETGT:  return X86::COND_G;
3508     case ISD::SETGE:  return X86::COND_GE;
3509     case ISD::SETLT:  return X86::COND_L;
3510     case ISD::SETLE:  return X86::COND_LE;
3511     case ISD::SETNE:  return X86::COND_NE;
3512     case ISD::SETULT: return X86::COND_B;
3513     case ISD::SETUGT: return X86::COND_A;
3514     case ISD::SETULE: return X86::COND_BE;
3515     case ISD::SETUGE: return X86::COND_AE;
3516     }
3517   }
3518
3519   // First determine if it is required or is profitable to flip the operands.
3520
3521   // If LHS is a foldable load, but RHS is not, flip the condition.
3522   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3523       !ISD::isNON_EXTLoad(RHS.getNode())) {
3524     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3525     std::swap(LHS, RHS);
3526   }
3527
3528   switch (SetCCOpcode) {
3529   default: break;
3530   case ISD::SETOLT:
3531   case ISD::SETOLE:
3532   case ISD::SETUGT:
3533   case ISD::SETUGE:
3534     std::swap(LHS, RHS);
3535     break;
3536   }
3537
3538   // On a floating point condition, the flags are set as follows:
3539   // ZF  PF  CF   op
3540   //  0 | 0 | 0 | X > Y
3541   //  0 | 0 | 1 | X < Y
3542   //  1 | 0 | 0 | X == Y
3543   //  1 | 1 | 1 | unordered
3544   switch (SetCCOpcode) {
3545   default: llvm_unreachable("Condcode should be pre-legalized away");
3546   case ISD::SETUEQ:
3547   case ISD::SETEQ:   return X86::COND_E;
3548   case ISD::SETOLT:              // flipped
3549   case ISD::SETOGT:
3550   case ISD::SETGT:   return X86::COND_A;
3551   case ISD::SETOLE:              // flipped
3552   case ISD::SETOGE:
3553   case ISD::SETGE:   return X86::COND_AE;
3554   case ISD::SETUGT:              // flipped
3555   case ISD::SETULT:
3556   case ISD::SETLT:   return X86::COND_B;
3557   case ISD::SETUGE:              // flipped
3558   case ISD::SETULE:
3559   case ISD::SETLE:   return X86::COND_BE;
3560   case ISD::SETONE:
3561   case ISD::SETNE:   return X86::COND_NE;
3562   case ISD::SETUO:   return X86::COND_P;
3563   case ISD::SETO:    return X86::COND_NP;
3564   case ISD::SETOEQ:
3565   case ISD::SETUNE:  return X86::COND_INVALID;
3566   }
3567 }
3568
3569 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3570 /// code. Current x86 isa includes the following FP cmov instructions:
3571 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3572 static bool hasFPCMov(unsigned X86CC) {
3573   switch (X86CC) {
3574   default:
3575     return false;
3576   case X86::COND_B:
3577   case X86::COND_BE:
3578   case X86::COND_E:
3579   case X86::COND_P:
3580   case X86::COND_A:
3581   case X86::COND_AE:
3582   case X86::COND_NE:
3583   case X86::COND_NP:
3584     return true;
3585   }
3586 }
3587
3588 /// isFPImmLegal - Returns true if the target can instruction select the
3589 /// specified FP immediate natively. If false, the legalizer will
3590 /// materialize the FP immediate as a load from a constant pool.
3591 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3592   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3593     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3594       return true;
3595   }
3596   return false;
3597 }
3598
3599 /// \brief Returns true if it is beneficial to convert a load of a constant
3600 /// to just the constant itself.
3601 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3602                                                           Type *Ty) const {
3603   assert(Ty->isIntegerTy());
3604
3605   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3606   if (BitSize == 0 || BitSize > 64)
3607     return false;
3608   return true;
3609 }
3610
3611 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3612 /// the specified range (L, H].
3613 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3614   return (Val < 0) || (Val >= Low && Val < Hi);
3615 }
3616
3617 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3618 /// specified value.
3619 static bool isUndefOrEqual(int Val, int CmpVal) {
3620   return (Val < 0 || Val == CmpVal);
3621 }
3622
3623 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3624 /// from position Pos and ending in Pos+Size, falls within the specified
3625 /// sequential range (L, L+Pos]. or is undef.
3626 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3627                                        unsigned Pos, unsigned Size, int Low) {
3628   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3629     if (!isUndefOrEqual(Mask[i], Low))
3630       return false;
3631   return true;
3632 }
3633
3634 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3635 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3636 /// the second operand.
3637 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3638   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3639     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3640   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3641     return (Mask[0] < 2 && Mask[1] < 2);
3642   return false;
3643 }
3644
3645 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3646 /// is suitable for input to PSHUFHW.
3647 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3648   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3649     return false;
3650
3651   // Lower quadword copied in order or undef.
3652   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3653     return false;
3654
3655   // Upper quadword shuffled.
3656   for (unsigned i = 4; i != 8; ++i)
3657     if (!isUndefOrInRange(Mask[i], 4, 8))
3658       return false;
3659
3660   if (VT == MVT::v16i16) {
3661     // Lower quadword copied in order or undef.
3662     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3663       return false;
3664
3665     // Upper quadword shuffled.
3666     for (unsigned i = 12; i != 16; ++i)
3667       if (!isUndefOrInRange(Mask[i], 12, 16))
3668         return false;
3669   }
3670
3671   return true;
3672 }
3673
3674 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3675 /// is suitable for input to PSHUFLW.
3676 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3677   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3678     return false;
3679
3680   // Upper quadword copied in order.
3681   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3682     return false;
3683
3684   // Lower quadword shuffled.
3685   for (unsigned i = 0; i != 4; ++i)
3686     if (!isUndefOrInRange(Mask[i], 0, 4))
3687       return false;
3688
3689   if (VT == MVT::v16i16) {
3690     // Upper quadword copied in order.
3691     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3692       return false;
3693
3694     // Lower quadword shuffled.
3695     for (unsigned i = 8; i != 12; ++i)
3696       if (!isUndefOrInRange(Mask[i], 8, 12))
3697         return false;
3698   }
3699
3700   return true;
3701 }
3702
3703 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3704 /// is suitable for input to PALIGNR.
3705 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3706                           const X86Subtarget *Subtarget) {
3707   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3708       (VT.is256BitVector() && !Subtarget->hasInt256()))
3709     return false;
3710
3711   unsigned NumElts = VT.getVectorNumElements();
3712   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3713   unsigned NumLaneElts = NumElts/NumLanes;
3714
3715   // Do not handle 64-bit element shuffles with palignr.
3716   if (NumLaneElts == 2)
3717     return false;
3718
3719   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3720     unsigned i;
3721     for (i = 0; i != NumLaneElts; ++i) {
3722       if (Mask[i+l] >= 0)
3723         break;
3724     }
3725
3726     // Lane is all undef, go to next lane
3727     if (i == NumLaneElts)
3728       continue;
3729
3730     int Start = Mask[i+l];
3731
3732     // Make sure its in this lane in one of the sources
3733     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3734         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3735       return false;
3736
3737     // If not lane 0, then we must match lane 0
3738     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3739       return false;
3740
3741     // Correct second source to be contiguous with first source
3742     if (Start >= (int)NumElts)
3743       Start -= NumElts - NumLaneElts;
3744
3745     // Make sure we're shifting in the right direction.
3746     if (Start <= (int)(i+l))
3747       return false;
3748
3749     Start -= i;
3750
3751     // Check the rest of the elements to see if they are consecutive.
3752     for (++i; i != NumLaneElts; ++i) {
3753       int Idx = Mask[i+l];
3754
3755       // Make sure its in this lane
3756       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3757           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3758         return false;
3759
3760       // If not lane 0, then we must match lane 0
3761       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3762         return false;
3763
3764       if (Idx >= (int)NumElts)
3765         Idx -= NumElts - NumLaneElts;
3766
3767       if (!isUndefOrEqual(Idx, Start+i))
3768         return false;
3769
3770     }
3771   }
3772
3773   return true;
3774 }
3775
3776 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3777 /// the two vector operands have swapped position.
3778 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3779                                      unsigned NumElems) {
3780   for (unsigned i = 0; i != NumElems; ++i) {
3781     int idx = Mask[i];
3782     if (idx < 0)
3783       continue;
3784     else if (idx < (int)NumElems)
3785       Mask[i] = idx + NumElems;
3786     else
3787       Mask[i] = idx - NumElems;
3788   }
3789 }
3790
3791 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3792 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3793 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3794 /// reverse of what x86 shuffles want.
3795 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3796
3797   unsigned NumElems = VT.getVectorNumElements();
3798   unsigned NumLanes = VT.getSizeInBits()/128;
3799   unsigned NumLaneElems = NumElems/NumLanes;
3800
3801   if (NumLaneElems != 2 && NumLaneElems != 4)
3802     return false;
3803
3804   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3805   bool symetricMaskRequired =
3806     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3807
3808   // VSHUFPSY divides the resulting vector into 4 chunks.
3809   // The sources are also splitted into 4 chunks, and each destination
3810   // chunk must come from a different source chunk.
3811   //
3812   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3813   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3814   //
3815   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3816   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3817   //
3818   // VSHUFPDY divides the resulting vector into 4 chunks.
3819   // The sources are also splitted into 4 chunks, and each destination
3820   // chunk must come from a different source chunk.
3821   //
3822   //  SRC1 =>      X3       X2       X1       X0
3823   //  SRC2 =>      Y3       Y2       Y1       Y0
3824   //
3825   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3826   //
3827   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3828   unsigned HalfLaneElems = NumLaneElems/2;
3829   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3830     for (unsigned i = 0; i != NumLaneElems; ++i) {
3831       int Idx = Mask[i+l];
3832       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3833       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3834         return false;
3835       // For VSHUFPSY, the mask of the second half must be the same as the
3836       // first but with the appropriate offsets. This works in the same way as
3837       // VPERMILPS works with masks.
3838       if (!symetricMaskRequired || Idx < 0)
3839         continue;
3840       if (MaskVal[i] < 0) {
3841         MaskVal[i] = Idx - l;
3842         continue;
3843       }
3844       if ((signed)(Idx - l) != MaskVal[i])
3845         return false;
3846     }
3847   }
3848
3849   return true;
3850 }
3851
3852 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3853 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3854 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3855   if (!VT.is128BitVector())
3856     return false;
3857
3858   unsigned NumElems = VT.getVectorNumElements();
3859
3860   if (NumElems != 4)
3861     return false;
3862
3863   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3864   return isUndefOrEqual(Mask[0], 6) &&
3865          isUndefOrEqual(Mask[1], 7) &&
3866          isUndefOrEqual(Mask[2], 2) &&
3867          isUndefOrEqual(Mask[3], 3);
3868 }
3869
3870 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3871 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3872 /// <2, 3, 2, 3>
3873 static bool isMOVHLPS_v_undef_Mask(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   return isUndefOrEqual(Mask[0], 2) &&
3883          isUndefOrEqual(Mask[1], 3) &&
3884          isUndefOrEqual(Mask[2], 2) &&
3885          isUndefOrEqual(Mask[3], 3);
3886 }
3887
3888 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3889 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3890 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3891   if (!VT.is128BitVector())
3892     return false;
3893
3894   unsigned NumElems = VT.getVectorNumElements();
3895
3896   if (NumElems != 2 && NumElems != 4)
3897     return false;
3898
3899   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3900     if (!isUndefOrEqual(Mask[i], i + NumElems))
3901       return false;
3902
3903   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3904     if (!isUndefOrEqual(Mask[i], i))
3905       return false;
3906
3907   return true;
3908 }
3909
3910 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3912 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3913   if (!VT.is128BitVector())
3914     return false;
3915
3916   unsigned NumElems = VT.getVectorNumElements();
3917
3918   if (NumElems != 2 && NumElems != 4)
3919     return false;
3920
3921   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3922     if (!isUndefOrEqual(Mask[i], i))
3923       return false;
3924
3925   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3926     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3927       return false;
3928
3929   return true;
3930 }
3931
3932 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3933 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3934 /// i. e: If all but one element come from the same vector.
3935 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3936   // TODO: Deal with AVX's VINSERTPS
3937   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3938     return false;
3939
3940   unsigned CorrectPosV1 = 0;
3941   unsigned CorrectPosV2 = 0;
3942   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3943     if (Mask[i] == i)
3944       ++CorrectPosV1;
3945     else if (Mask[i] == i + 4)
3946       ++CorrectPosV2;
3947
3948   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3949     // We have 3 elements from one vector, and one from another.
3950     return true;
3951
3952   return false;
3953 }
3954
3955 //
3956 // Some special combinations that can be optimized.
3957 //
3958 static
3959 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3960                                SelectionDAG &DAG) {
3961   MVT VT = SVOp->getSimpleValueType(0);
3962   SDLoc dl(SVOp);
3963
3964   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3965     return SDValue();
3966
3967   ArrayRef<int> Mask = SVOp->getMask();
3968
3969   // These are the special masks that may be optimized.
3970   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3971   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3972   bool MatchEvenMask = true;
3973   bool MatchOddMask  = true;
3974   for (int i=0; i<8; ++i) {
3975     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3976       MatchEvenMask = false;
3977     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3978       MatchOddMask = false;
3979   }
3980
3981   if (!MatchEvenMask && !MatchOddMask)
3982     return SDValue();
3983
3984   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3985
3986   SDValue Op0 = SVOp->getOperand(0);
3987   SDValue Op1 = SVOp->getOperand(1);
3988
3989   if (MatchEvenMask) {
3990     // Shift the second operand right to 32 bits.
3991     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3992     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3993   } else {
3994     // Shift the first operand left to 32 bits.
3995     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3996     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3997   }
3998   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3999   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4000 }
4001
4002 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4003 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4004 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4005                          bool HasInt256, bool V2IsSplat = false) {
4006
4007   assert(VT.getSizeInBits() >= 128 &&
4008          "Unsupported vector type for unpckl");
4009
4010   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4011   unsigned NumLanes;
4012   unsigned NumOf256BitLanes;
4013   unsigned NumElts = VT.getVectorNumElements();
4014   if (VT.is256BitVector()) {
4015     if (NumElts != 4 && NumElts != 8 &&
4016         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4017     return false;
4018     NumLanes = 2;
4019     NumOf256BitLanes = 1;
4020   } else if (VT.is512BitVector()) {
4021     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4022            "Unsupported vector type for unpckh");
4023     NumLanes = 2;
4024     NumOf256BitLanes = 2;
4025   } else {
4026     NumLanes = 1;
4027     NumOf256BitLanes = 1;
4028   }
4029
4030   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4031   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4032
4033   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4034     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4035       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4036         int BitI  = Mask[l256*NumEltsInStride+l+i];
4037         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4038         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4039           return false;
4040         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4041           return false;
4042         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4043           return false;
4044       }
4045     }
4046   }
4047   return true;
4048 }
4049
4050 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4051 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4052 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4053                          bool HasInt256, bool V2IsSplat = false) {
4054   assert(VT.getSizeInBits() >= 128 &&
4055          "Unsupported vector type for unpckh");
4056
4057   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4058   unsigned NumLanes;
4059   unsigned NumOf256BitLanes;
4060   unsigned NumElts = VT.getVectorNumElements();
4061   if (VT.is256BitVector()) {
4062     if (NumElts != 4 && NumElts != 8 &&
4063         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4064     return false;
4065     NumLanes = 2;
4066     NumOf256BitLanes = 1;
4067   } else if (VT.is512BitVector()) {
4068     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4069            "Unsupported vector type for unpckh");
4070     NumLanes = 2;
4071     NumOf256BitLanes = 2;
4072   } else {
4073     NumLanes = 1;
4074     NumOf256BitLanes = 1;
4075   }
4076
4077   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4078   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4079
4080   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4081     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4082       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4083         int BitI  = Mask[l256*NumEltsInStride+l+i];
4084         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4085         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4086           return false;
4087         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4088           return false;
4089         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4090           return false;
4091       }
4092     }
4093   }
4094   return true;
4095 }
4096
4097 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4098 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4099 /// <0, 0, 1, 1>
4100 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4101   unsigned NumElts = VT.getVectorNumElements();
4102   bool Is256BitVec = VT.is256BitVector();
4103
4104   if (VT.is512BitVector())
4105     return false;
4106   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4107          "Unsupported vector type for unpckh");
4108
4109   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4110       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4111     return false;
4112
4113   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4114   // FIXME: Need a better way to get rid of this, there's no latency difference
4115   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4116   // the former later. We should also remove the "_undef" special mask.
4117   if (NumElts == 4 && Is256BitVec)
4118     return false;
4119
4120   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4121   // independently on 128-bit lanes.
4122   unsigned NumLanes = VT.getSizeInBits()/128;
4123   unsigned NumLaneElts = NumElts/NumLanes;
4124
4125   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4126     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4127       int BitI  = Mask[l+i];
4128       int BitI1 = Mask[l+i+1];
4129
4130       if (!isUndefOrEqual(BitI, j))
4131         return false;
4132       if (!isUndefOrEqual(BitI1, j))
4133         return false;
4134     }
4135   }
4136
4137   return true;
4138 }
4139
4140 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4141 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4142 /// <2, 2, 3, 3>
4143 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4144   unsigned NumElts = VT.getVectorNumElements();
4145
4146   if (VT.is512BitVector())
4147     return false;
4148
4149   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4150          "Unsupported vector type for unpckh");
4151
4152   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4153       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4154     return false;
4155
4156   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4157   // independently on 128-bit lanes.
4158   unsigned NumLanes = VT.getSizeInBits()/128;
4159   unsigned NumLaneElts = NumElts/NumLanes;
4160
4161   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4162     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4163       int BitI  = Mask[l+i];
4164       int BitI1 = Mask[l+i+1];
4165       if (!isUndefOrEqual(BitI, j))
4166         return false;
4167       if (!isUndefOrEqual(BitI1, j))
4168         return false;
4169     }
4170   }
4171   return true;
4172 }
4173
4174 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4175 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4176 /// MOVSD, and MOVD, i.e. setting the lowest element.
4177 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4178   if (VT.getVectorElementType().getSizeInBits() < 32)
4179     return false;
4180   if (!VT.is128BitVector())
4181     return false;
4182
4183   unsigned NumElts = VT.getVectorNumElements();
4184
4185   if (!isUndefOrEqual(Mask[0], NumElts))
4186     return false;
4187
4188   for (unsigned i = 1; i != NumElts; ++i)
4189     if (!isUndefOrEqual(Mask[i], i))
4190       return false;
4191
4192   return true;
4193 }
4194
4195 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4196 /// as permutations between 128-bit chunks or halves. As an example: this
4197 /// shuffle bellow:
4198 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4199 /// The first half comes from the second half of V1 and the second half from the
4200 /// the second half of V2.
4201 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4202   if (!HasFp256 || !VT.is256BitVector())
4203     return false;
4204
4205   // The shuffle result is divided into half A and half B. In total the two
4206   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4207   // B must come from C, D, E or F.
4208   unsigned HalfSize = VT.getVectorNumElements()/2;
4209   bool MatchA = false, MatchB = false;
4210
4211   // Check if A comes from one of C, D, E, F.
4212   for (unsigned Half = 0; Half != 4; ++Half) {
4213     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4214       MatchA = true;
4215       break;
4216     }
4217   }
4218
4219   // Check if B comes from one of C, D, E, F.
4220   for (unsigned Half = 0; Half != 4; ++Half) {
4221     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4222       MatchB = true;
4223       break;
4224     }
4225   }
4226
4227   return MatchA && MatchB;
4228 }
4229
4230 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4231 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4232 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4233   MVT VT = SVOp->getSimpleValueType(0);
4234
4235   unsigned HalfSize = VT.getVectorNumElements()/2;
4236
4237   unsigned FstHalf = 0, SndHalf = 0;
4238   for (unsigned i = 0; i < HalfSize; ++i) {
4239     if (SVOp->getMaskElt(i) > 0) {
4240       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4241       break;
4242     }
4243   }
4244   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4245     if (SVOp->getMaskElt(i) > 0) {
4246       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4247       break;
4248     }
4249   }
4250
4251   return (FstHalf | (SndHalf << 4));
4252 }
4253
4254 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4255 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4256   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4257   if (EltSize < 32)
4258     return false;
4259
4260   unsigned NumElts = VT.getVectorNumElements();
4261   Imm8 = 0;
4262   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4263     for (unsigned i = 0; i != NumElts; ++i) {
4264       if (Mask[i] < 0)
4265         continue;
4266       Imm8 |= Mask[i] << (i*2);
4267     }
4268     return true;
4269   }
4270
4271   unsigned LaneSize = 4;
4272   SmallVector<int, 4> MaskVal(LaneSize, -1);
4273
4274   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4275     for (unsigned i = 0; i != LaneSize; ++i) {
4276       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4277         return false;
4278       if (Mask[i+l] < 0)
4279         continue;
4280       if (MaskVal[i] < 0) {
4281         MaskVal[i] = Mask[i+l] - l;
4282         Imm8 |= MaskVal[i] << (i*2);
4283         continue;
4284       }
4285       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4286         return false;
4287     }
4288   }
4289   return true;
4290 }
4291
4292 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4293 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4294 /// Note that VPERMIL mask matching is different depending whether theunderlying
4295 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4296 /// to the same elements of the low, but to the higher half of the source.
4297 /// In VPERMILPD the two lanes could be shuffled independently of each other
4298 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4299 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4300   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4301   if (VT.getSizeInBits() < 256 || EltSize < 32)
4302     return false;
4303   bool symetricMaskRequired = (EltSize == 32);
4304   unsigned NumElts = VT.getVectorNumElements();
4305
4306   unsigned NumLanes = VT.getSizeInBits()/128;
4307   unsigned LaneSize = NumElts/NumLanes;
4308   // 2 or 4 elements in one lane
4309
4310   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4311   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4312     for (unsigned i = 0; i != LaneSize; ++i) {
4313       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4314         return false;
4315       if (symetricMaskRequired) {
4316         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4317           ExpectedMaskVal[i] = Mask[i+l] - l;
4318           continue;
4319         }
4320         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4321           return false;
4322       }
4323     }
4324   }
4325   return true;
4326 }
4327
4328 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4329 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4330 /// element of vector 2 and the other elements to come from vector 1 in order.
4331 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4332                                bool V2IsSplat = false, bool V2IsUndef = false) {
4333   if (!VT.is128BitVector())
4334     return false;
4335
4336   unsigned NumOps = VT.getVectorNumElements();
4337   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4338     return false;
4339
4340   if (!isUndefOrEqual(Mask[0], 0))
4341     return false;
4342
4343   for (unsigned i = 1; i != NumOps; ++i)
4344     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4345           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4346           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4347       return false;
4348
4349   return true;
4350 }
4351
4352 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4353 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4354 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4355 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4356                            const X86Subtarget *Subtarget) {
4357   if (!Subtarget->hasSSE3())
4358     return false;
4359
4360   unsigned NumElems = VT.getVectorNumElements();
4361
4362   if ((VT.is128BitVector() && NumElems != 4) ||
4363       (VT.is256BitVector() && NumElems != 8) ||
4364       (VT.is512BitVector() && NumElems != 16))
4365     return false;
4366
4367   // "i+1" is the value the indexed mask element must have
4368   for (unsigned i = 0; i != NumElems; i += 2)
4369     if (!isUndefOrEqual(Mask[i], i+1) ||
4370         !isUndefOrEqual(Mask[i+1], i+1))
4371       return false;
4372
4373   return true;
4374 }
4375
4376 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4377 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4378 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4379 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4380                            const X86Subtarget *Subtarget) {
4381   if (!Subtarget->hasSSE3())
4382     return false;
4383
4384   unsigned NumElems = VT.getVectorNumElements();
4385
4386   if ((VT.is128BitVector() && NumElems != 4) ||
4387       (VT.is256BitVector() && NumElems != 8) ||
4388       (VT.is512BitVector() && NumElems != 16))
4389     return false;
4390
4391   // "i" is the value the indexed mask element must have
4392   for (unsigned i = 0; i != NumElems; i += 2)
4393     if (!isUndefOrEqual(Mask[i], i) ||
4394         !isUndefOrEqual(Mask[i+1], i))
4395       return false;
4396
4397   return true;
4398 }
4399
4400 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4401 /// specifies a shuffle of elements that is suitable for input to 256-bit
4402 /// version of MOVDDUP.
4403 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4404   if (!HasFp256 || !VT.is256BitVector())
4405     return false;
4406
4407   unsigned NumElts = VT.getVectorNumElements();
4408   if (NumElts != 4)
4409     return false;
4410
4411   for (unsigned i = 0; i != NumElts/2; ++i)
4412     if (!isUndefOrEqual(Mask[i], 0))
4413       return false;
4414   for (unsigned i = NumElts/2; i != NumElts; ++i)
4415     if (!isUndefOrEqual(Mask[i], NumElts/2))
4416       return false;
4417   return true;
4418 }
4419
4420 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4421 /// specifies a shuffle of elements that is suitable for input to 128-bit
4422 /// version of MOVDDUP.
4423 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4424   if (!VT.is128BitVector())
4425     return false;
4426
4427   unsigned e = VT.getVectorNumElements() / 2;
4428   for (unsigned i = 0; i != e; ++i)
4429     if (!isUndefOrEqual(Mask[i], i))
4430       return false;
4431   for (unsigned i = 0; i != e; ++i)
4432     if (!isUndefOrEqual(Mask[e+i], i))
4433       return false;
4434   return true;
4435 }
4436
4437 /// isVEXTRACTIndex - Return true if the specified
4438 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4439 /// suitable for instruction that extract 128 or 256 bit vectors
4440 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4441   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4442   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4443     return false;
4444
4445   // The index should be aligned on a vecWidth-bit boundary.
4446   uint64_t Index =
4447     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4448
4449   MVT VT = N->getSimpleValueType(0);
4450   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4451   bool Result = (Index * ElSize) % vecWidth == 0;
4452
4453   return Result;
4454 }
4455
4456 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4457 /// operand specifies a subvector insert that is suitable for input to
4458 /// insertion of 128 or 256-bit subvectors
4459 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4460   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4461   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4462     return false;
4463   // The index should be aligned on a vecWidth-bit boundary.
4464   uint64_t Index =
4465     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4466
4467   MVT VT = N->getSimpleValueType(0);
4468   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4469   bool Result = (Index * ElSize) % vecWidth == 0;
4470
4471   return Result;
4472 }
4473
4474 bool X86::isVINSERT128Index(SDNode *N) {
4475   return isVINSERTIndex(N, 128);
4476 }
4477
4478 bool X86::isVINSERT256Index(SDNode *N) {
4479   return isVINSERTIndex(N, 256);
4480 }
4481
4482 bool X86::isVEXTRACT128Index(SDNode *N) {
4483   return isVEXTRACTIndex(N, 128);
4484 }
4485
4486 bool X86::isVEXTRACT256Index(SDNode *N) {
4487   return isVEXTRACTIndex(N, 256);
4488 }
4489
4490 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4491 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4492 /// Handles 128-bit and 256-bit.
4493 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4494   MVT VT = N->getSimpleValueType(0);
4495
4496   assert((VT.getSizeInBits() >= 128) &&
4497          "Unsupported vector type for PSHUF/SHUFP");
4498
4499   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4500   // independently on 128-bit lanes.
4501   unsigned NumElts = VT.getVectorNumElements();
4502   unsigned NumLanes = VT.getSizeInBits()/128;
4503   unsigned NumLaneElts = NumElts/NumLanes;
4504
4505   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4506          "Only supports 2, 4 or 8 elements per lane");
4507
4508   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4509   unsigned Mask = 0;
4510   for (unsigned i = 0; i != NumElts; ++i) {
4511     int Elt = N->getMaskElt(i);
4512     if (Elt < 0) continue;
4513     Elt &= NumLaneElts - 1;
4514     unsigned ShAmt = (i << Shift) % 8;
4515     Mask |= Elt << ShAmt;
4516   }
4517
4518   return Mask;
4519 }
4520
4521 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4522 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4523 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4524   MVT VT = N->getSimpleValueType(0);
4525
4526   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4527          "Unsupported vector type for PSHUFHW");
4528
4529   unsigned NumElts = VT.getVectorNumElements();
4530
4531   unsigned Mask = 0;
4532   for (unsigned l = 0; l != NumElts; l += 8) {
4533     // 8 nodes per lane, but we only care about the last 4.
4534     for (unsigned i = 0; i < 4; ++i) {
4535       int Elt = N->getMaskElt(l+i+4);
4536       if (Elt < 0) continue;
4537       Elt &= 0x3; // only 2-bits.
4538       Mask |= Elt << (i * 2);
4539     }
4540   }
4541
4542   return Mask;
4543 }
4544
4545 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4546 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4547 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4548   MVT VT = N->getSimpleValueType(0);
4549
4550   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4551          "Unsupported vector type for PSHUFHW");
4552
4553   unsigned NumElts = VT.getVectorNumElements();
4554
4555   unsigned Mask = 0;
4556   for (unsigned l = 0; l != NumElts; l += 8) {
4557     // 8 nodes per lane, but we only care about the first 4.
4558     for (unsigned i = 0; i < 4; ++i) {
4559       int Elt = N->getMaskElt(l+i);
4560       if (Elt < 0) continue;
4561       Elt &= 0x3; // only 2-bits
4562       Mask |= Elt << (i * 2);
4563     }
4564   }
4565
4566   return Mask;
4567 }
4568
4569 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4570 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4571 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4572   MVT VT = SVOp->getSimpleValueType(0);
4573   unsigned EltSize = VT.is512BitVector() ? 1 :
4574     VT.getVectorElementType().getSizeInBits() >> 3;
4575
4576   unsigned NumElts = VT.getVectorNumElements();
4577   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4578   unsigned NumLaneElts = NumElts/NumLanes;
4579
4580   int Val = 0;
4581   unsigned i;
4582   for (i = 0; i != NumElts; ++i) {
4583     Val = SVOp->getMaskElt(i);
4584     if (Val >= 0)
4585       break;
4586   }
4587   if (Val >= (int)NumElts)
4588     Val -= NumElts - NumLaneElts;
4589
4590   assert(Val - i > 0 && "PALIGNR imm should be positive");
4591   return (Val - i) * EltSize;
4592 }
4593
4594 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4595   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4596   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4597     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4598
4599   uint64_t Index =
4600     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4601
4602   MVT VecVT = N->getOperand(0).getSimpleValueType();
4603   MVT ElVT = VecVT.getVectorElementType();
4604
4605   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4606   return Index / NumElemsPerChunk;
4607 }
4608
4609 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4610   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4611   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4612     llvm_unreachable("Illegal insert subvector for VINSERT");
4613
4614   uint64_t Index =
4615     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4616
4617   MVT VecVT = N->getSimpleValueType(0);
4618   MVT ElVT = VecVT.getVectorElementType();
4619
4620   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4621   return Index / NumElemsPerChunk;
4622 }
4623
4624 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4625 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4626 /// and VINSERTI128 instructions.
4627 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4628   return getExtractVEXTRACTImmediate(N, 128);
4629 }
4630
4631 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4632 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4633 /// and VINSERTI64x4 instructions.
4634 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4635   return getExtractVEXTRACTImmediate(N, 256);
4636 }
4637
4638 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4639 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4640 /// and VINSERTI128 instructions.
4641 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4642   return getInsertVINSERTImmediate(N, 128);
4643 }
4644
4645 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4646 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4647 /// and VINSERTI64x4 instructions.
4648 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4649   return getInsertVINSERTImmediate(N, 256);
4650 }
4651
4652 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4653 /// constant +0.0.
4654 bool X86::isZeroNode(SDValue Elt) {
4655   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4656     return CN->isNullValue();
4657   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4658     return CFP->getValueAPF().isPosZero();
4659   return false;
4660 }
4661
4662 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4663 /// their permute mask.
4664 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4665                                     SelectionDAG &DAG) {
4666   MVT VT = SVOp->getSimpleValueType(0);
4667   unsigned NumElems = VT.getVectorNumElements();
4668   SmallVector<int, 8> MaskVec;
4669
4670   for (unsigned i = 0; i != NumElems; ++i) {
4671     int Idx = SVOp->getMaskElt(i);
4672     if (Idx >= 0) {
4673       if (Idx < (int)NumElems)
4674         Idx += NumElems;
4675       else
4676         Idx -= NumElems;
4677     }
4678     MaskVec.push_back(Idx);
4679   }
4680   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4681                               SVOp->getOperand(0), &MaskVec[0]);
4682 }
4683
4684 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4685 /// match movhlps. The lower half elements should come from upper half of
4686 /// V1 (and in order), and the upper half elements should come from the upper
4687 /// half of V2 (and in order).
4688 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4689   if (!VT.is128BitVector())
4690     return false;
4691   if (VT.getVectorNumElements() != 4)
4692     return false;
4693   for (unsigned i = 0, e = 2; i != e; ++i)
4694     if (!isUndefOrEqual(Mask[i], i+2))
4695       return false;
4696   for (unsigned i = 2; i != 4; ++i)
4697     if (!isUndefOrEqual(Mask[i], i+4))
4698       return false;
4699   return true;
4700 }
4701
4702 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4703 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4704 /// required.
4705 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4706   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4707     return false;
4708   N = N->getOperand(0).getNode();
4709   if (!ISD::isNON_EXTLoad(N))
4710     return false;
4711   if (LD)
4712     *LD = cast<LoadSDNode>(N);
4713   return true;
4714 }
4715
4716 // Test whether the given value is a vector value which will be legalized
4717 // into a load.
4718 static bool WillBeConstantPoolLoad(SDNode *N) {
4719   if (N->getOpcode() != ISD::BUILD_VECTOR)
4720     return false;
4721
4722   // Check for any non-constant elements.
4723   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4724     switch (N->getOperand(i).getNode()->getOpcode()) {
4725     case ISD::UNDEF:
4726     case ISD::ConstantFP:
4727     case ISD::Constant:
4728       break;
4729     default:
4730       return false;
4731     }
4732
4733   // Vectors of all-zeros and all-ones are materialized with special
4734   // instructions rather than being loaded.
4735   return !ISD::isBuildVectorAllZeros(N) &&
4736          !ISD::isBuildVectorAllOnes(N);
4737 }
4738
4739 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4740 /// match movlp{s|d}. The lower half elements should come from lower half of
4741 /// V1 (and in order), and the upper half elements should come from the upper
4742 /// half of V2 (and in order). And since V1 will become the source of the
4743 /// MOVLP, it must be either a vector load or a scalar load to vector.
4744 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4745                                ArrayRef<int> Mask, MVT VT) {
4746   if (!VT.is128BitVector())
4747     return false;
4748
4749   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4750     return false;
4751   // Is V2 is a vector load, don't do this transformation. We will try to use
4752   // load folding shufps op.
4753   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4754     return false;
4755
4756   unsigned NumElems = VT.getVectorNumElements();
4757
4758   if (NumElems != 2 && NumElems != 4)
4759     return false;
4760   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4761     if (!isUndefOrEqual(Mask[i], i))
4762       return false;
4763   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4764     if (!isUndefOrEqual(Mask[i], i+NumElems))
4765       return false;
4766   return true;
4767 }
4768
4769 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4770 /// all the same.
4771 static bool isSplatVector(SDNode *N) {
4772   if (N->getOpcode() != ISD::BUILD_VECTOR)
4773     return false;
4774
4775   SDValue SplatValue = N->getOperand(0);
4776   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4777     if (N->getOperand(i) != SplatValue)
4778       return false;
4779   return true;
4780 }
4781
4782 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4783 /// to an zero vector.
4784 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4785 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4786   SDValue V1 = N->getOperand(0);
4787   SDValue V2 = N->getOperand(1);
4788   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4789   for (unsigned i = 0; i != NumElems; ++i) {
4790     int Idx = N->getMaskElt(i);
4791     if (Idx >= (int)NumElems) {
4792       unsigned Opc = V2.getOpcode();
4793       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4794         continue;
4795       if (Opc != ISD::BUILD_VECTOR ||
4796           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4797         return false;
4798     } else if (Idx >= 0) {
4799       unsigned Opc = V1.getOpcode();
4800       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4801         continue;
4802       if (Opc != ISD::BUILD_VECTOR ||
4803           !X86::isZeroNode(V1.getOperand(Idx)))
4804         return false;
4805     }
4806   }
4807   return true;
4808 }
4809
4810 /// getZeroVector - Returns a vector of specified type with all zero elements.
4811 ///
4812 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4813                              SelectionDAG &DAG, SDLoc dl) {
4814   assert(VT.isVector() && "Expected a vector type");
4815
4816   // Always build SSE zero vectors as <4 x i32> bitcasted
4817   // to their dest type. This ensures they get CSE'd.
4818   SDValue Vec;
4819   if (VT.is128BitVector()) {  // SSE
4820     if (Subtarget->hasSSE2()) {  // SSE2
4821       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4822       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4823     } else { // SSE1
4824       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4825       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4826     }
4827   } else if (VT.is256BitVector()) { // AVX
4828     if (Subtarget->hasInt256()) { // AVX2
4829       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4830       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4831       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4832     } else {
4833       // 256-bit logic and arithmetic instructions in AVX are all
4834       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4835       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4836       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4837       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4838     }
4839   } else if (VT.is512BitVector()) { // AVX-512
4840       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4841       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4842                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4843       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4844   } else if (VT.getScalarType() == MVT::i1) {
4845     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4846     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4847     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4848     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4849   } else
4850     llvm_unreachable("Unexpected vector type");
4851
4852   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4853 }
4854
4855 /// getOnesVector - Returns a vector of specified type with all bits set.
4856 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4857 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4858 /// Then bitcast to their original type, ensuring they get CSE'd.
4859 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4860                              SDLoc dl) {
4861   assert(VT.isVector() && "Expected a vector type");
4862
4863   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4864   SDValue Vec;
4865   if (VT.is256BitVector()) {
4866     if (HasInt256) { // AVX2
4867       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4868       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4869     } else { // AVX
4870       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4871       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4872     }
4873   } else if (VT.is128BitVector()) {
4874     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4875   } else
4876     llvm_unreachable("Unexpected vector type");
4877
4878   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4879 }
4880
4881 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4882 /// that point to V2 points to its first element.
4883 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4884   for (unsigned i = 0; i != NumElems; ++i) {
4885     if (Mask[i] > (int)NumElems) {
4886       Mask[i] = NumElems;
4887     }
4888   }
4889 }
4890
4891 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4892 /// operation of specified width.
4893 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4894                        SDValue V2) {
4895   unsigned NumElems = VT.getVectorNumElements();
4896   SmallVector<int, 8> Mask;
4897   Mask.push_back(NumElems);
4898   for (unsigned i = 1; i != NumElems; ++i)
4899     Mask.push_back(i);
4900   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4901 }
4902
4903 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4904 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4905                           SDValue V2) {
4906   unsigned NumElems = VT.getVectorNumElements();
4907   SmallVector<int, 8> Mask;
4908   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4909     Mask.push_back(i);
4910     Mask.push_back(i + NumElems);
4911   }
4912   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4913 }
4914
4915 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4916 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4917                           SDValue V2) {
4918   unsigned NumElems = VT.getVectorNumElements();
4919   SmallVector<int, 8> Mask;
4920   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4921     Mask.push_back(i + Half);
4922     Mask.push_back(i + NumElems + Half);
4923   }
4924   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4925 }
4926
4927 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4928 // a generic shuffle instruction because the target has no such instructions.
4929 // Generate shuffles which repeat i16 and i8 several times until they can be
4930 // represented by v4f32 and then be manipulated by target suported shuffles.
4931 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4932   MVT VT = V.getSimpleValueType();
4933   int NumElems = VT.getVectorNumElements();
4934   SDLoc dl(V);
4935
4936   while (NumElems > 4) {
4937     if (EltNo < NumElems/2) {
4938       V = getUnpackl(DAG, dl, VT, V, V);
4939     } else {
4940       V = getUnpackh(DAG, dl, VT, V, V);
4941       EltNo -= NumElems/2;
4942     }
4943     NumElems >>= 1;
4944   }
4945   return V;
4946 }
4947
4948 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4949 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4950   MVT VT = V.getSimpleValueType();
4951   SDLoc dl(V);
4952
4953   if (VT.is128BitVector()) {
4954     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4955     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4956     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4957                              &SplatMask[0]);
4958   } else if (VT.is256BitVector()) {
4959     // To use VPERMILPS to splat scalars, the second half of indicies must
4960     // refer to the higher part, which is a duplication of the lower one,
4961     // because VPERMILPS can only handle in-lane permutations.
4962     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4963                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4964
4965     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4966     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4967                              &SplatMask[0]);
4968   } else
4969     llvm_unreachable("Vector size not supported");
4970
4971   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4972 }
4973
4974 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4975 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4976   MVT SrcVT = SV->getSimpleValueType(0);
4977   SDValue V1 = SV->getOperand(0);
4978   SDLoc dl(SV);
4979
4980   int EltNo = SV->getSplatIndex();
4981   int NumElems = SrcVT.getVectorNumElements();
4982   bool Is256BitVec = SrcVT.is256BitVector();
4983
4984   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4985          "Unknown how to promote splat for type");
4986
4987   // Extract the 128-bit part containing the splat element and update
4988   // the splat element index when it refers to the higher register.
4989   if (Is256BitVec) {
4990     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4991     if (EltNo >= NumElems/2)
4992       EltNo -= NumElems/2;
4993   }
4994
4995   // All i16 and i8 vector types can't be used directly by a generic shuffle
4996   // instruction because the target has no such instruction. Generate shuffles
4997   // which repeat i16 and i8 several times until they fit in i32, and then can
4998   // be manipulated by target suported shuffles.
4999   MVT EltVT = SrcVT.getVectorElementType();
5000   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5001     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5002
5003   // Recreate the 256-bit vector and place the same 128-bit vector
5004   // into the low and high part. This is necessary because we want
5005   // to use VPERM* to shuffle the vectors
5006   if (Is256BitVec) {
5007     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5008   }
5009
5010   return getLegalSplat(DAG, V1, EltNo);
5011 }
5012
5013 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5014 /// vector of zero or undef vector.  This produces a shuffle where the low
5015 /// element of V2 is swizzled into the zero/undef vector, landing at element
5016 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5017 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5018                                            bool IsZero,
5019                                            const X86Subtarget *Subtarget,
5020                                            SelectionDAG &DAG) {
5021   MVT VT = V2.getSimpleValueType();
5022   SDValue V1 = IsZero
5023     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5024   unsigned NumElems = VT.getVectorNumElements();
5025   SmallVector<int, 16> MaskVec;
5026   for (unsigned i = 0; i != NumElems; ++i)
5027     // If this is the insertion idx, put the low elt of V2 here.
5028     MaskVec.push_back(i == Idx ? NumElems : i);
5029   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5030 }
5031
5032 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5033 /// target specific opcode. Returns true if the Mask could be calculated.
5034 /// Sets IsUnary to true if only uses one source.
5035 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5036                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5037   unsigned NumElems = VT.getVectorNumElements();
5038   SDValue ImmN;
5039
5040   IsUnary = false;
5041   switch(N->getOpcode()) {
5042   case X86ISD::SHUFP:
5043     ImmN = N->getOperand(N->getNumOperands()-1);
5044     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5045     break;
5046   case X86ISD::UNPCKH:
5047     DecodeUNPCKHMask(VT, Mask);
5048     break;
5049   case X86ISD::UNPCKL:
5050     DecodeUNPCKLMask(VT, Mask);
5051     break;
5052   case X86ISD::MOVHLPS:
5053     DecodeMOVHLPSMask(NumElems, Mask);
5054     break;
5055   case X86ISD::MOVLHPS:
5056     DecodeMOVLHPSMask(NumElems, Mask);
5057     break;
5058   case X86ISD::PALIGNR:
5059     ImmN = N->getOperand(N->getNumOperands()-1);
5060     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5061     break;
5062   case X86ISD::PSHUFD:
5063   case X86ISD::VPERMILP:
5064     ImmN = N->getOperand(N->getNumOperands()-1);
5065     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5066     IsUnary = true;
5067     break;
5068   case X86ISD::PSHUFHW:
5069     ImmN = N->getOperand(N->getNumOperands()-1);
5070     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5071     IsUnary = true;
5072     break;
5073   case X86ISD::PSHUFLW:
5074     ImmN = N->getOperand(N->getNumOperands()-1);
5075     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5076     IsUnary = true;
5077     break;
5078   case X86ISD::VPERMI:
5079     ImmN = N->getOperand(N->getNumOperands()-1);
5080     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5081     IsUnary = true;
5082     break;
5083   case X86ISD::MOVSS:
5084   case X86ISD::MOVSD: {
5085     // The index 0 always comes from the first element of the second source,
5086     // this is why MOVSS and MOVSD are used in the first place. The other
5087     // elements come from the other positions of the first source vector
5088     Mask.push_back(NumElems);
5089     for (unsigned i = 1; i != NumElems; ++i) {
5090       Mask.push_back(i);
5091     }
5092     break;
5093   }
5094   case X86ISD::VPERM2X128:
5095     ImmN = N->getOperand(N->getNumOperands()-1);
5096     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5097     if (Mask.empty()) return false;
5098     break;
5099   case X86ISD::MOVDDUP:
5100   case X86ISD::MOVLHPD:
5101   case X86ISD::MOVLPD:
5102   case X86ISD::MOVLPS:
5103   case X86ISD::MOVSHDUP:
5104   case X86ISD::MOVSLDUP:
5105     // Not yet implemented
5106     return false;
5107   default: llvm_unreachable("unknown target shuffle node");
5108   }
5109
5110   return true;
5111 }
5112
5113 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5114 /// element of the result of the vector shuffle.
5115 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5116                                    unsigned Depth) {
5117   if (Depth == 6)
5118     return SDValue();  // Limit search depth.
5119
5120   SDValue V = SDValue(N, 0);
5121   EVT VT = V.getValueType();
5122   unsigned Opcode = V.getOpcode();
5123
5124   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5125   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5126     int Elt = SV->getMaskElt(Index);
5127
5128     if (Elt < 0)
5129       return DAG.getUNDEF(VT.getVectorElementType());
5130
5131     unsigned NumElems = VT.getVectorNumElements();
5132     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5133                                          : SV->getOperand(1);
5134     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5135   }
5136
5137   // Recurse into target specific vector shuffles to find scalars.
5138   if (isTargetShuffle(Opcode)) {
5139     MVT ShufVT = V.getSimpleValueType();
5140     unsigned NumElems = ShufVT.getVectorNumElements();
5141     SmallVector<int, 16> ShuffleMask;
5142     bool IsUnary;
5143
5144     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5145       return SDValue();
5146
5147     int Elt = ShuffleMask[Index];
5148     if (Elt < 0)
5149       return DAG.getUNDEF(ShufVT.getVectorElementType());
5150
5151     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5152                                          : N->getOperand(1);
5153     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5154                                Depth+1);
5155   }
5156
5157   // Actual nodes that may contain scalar elements
5158   if (Opcode == ISD::BITCAST) {
5159     V = V.getOperand(0);
5160     EVT SrcVT = V.getValueType();
5161     unsigned NumElems = VT.getVectorNumElements();
5162
5163     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5164       return SDValue();
5165   }
5166
5167   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5168     return (Index == 0) ? V.getOperand(0)
5169                         : DAG.getUNDEF(VT.getVectorElementType());
5170
5171   if (V.getOpcode() == ISD::BUILD_VECTOR)
5172     return V.getOperand(Index);
5173
5174   return SDValue();
5175 }
5176
5177 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5178 /// shuffle operation which come from a consecutively from a zero. The
5179 /// search can start in two different directions, from left or right.
5180 /// We count undefs as zeros until PreferredNum is reached.
5181 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5182                                          unsigned NumElems, bool ZerosFromLeft,
5183                                          SelectionDAG &DAG,
5184                                          unsigned PreferredNum = -1U) {
5185   unsigned NumZeros = 0;
5186   for (unsigned i = 0; i != NumElems; ++i) {
5187     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5188     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5189     if (!Elt.getNode())
5190       break;
5191
5192     if (X86::isZeroNode(Elt))
5193       ++NumZeros;
5194     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5195       NumZeros = std::min(NumZeros + 1, PreferredNum);
5196     else
5197       break;
5198   }
5199
5200   return NumZeros;
5201 }
5202
5203 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5204 /// correspond consecutively to elements from one of the vector operands,
5205 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5206 static
5207 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5208                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5209                               unsigned NumElems, unsigned &OpNum) {
5210   bool SeenV1 = false;
5211   bool SeenV2 = false;
5212
5213   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5214     int Idx = SVOp->getMaskElt(i);
5215     // Ignore undef indicies
5216     if (Idx < 0)
5217       continue;
5218
5219     if (Idx < (int)NumElems)
5220       SeenV1 = true;
5221     else
5222       SeenV2 = true;
5223
5224     // Only accept consecutive elements from the same vector
5225     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5226       return false;
5227   }
5228
5229   OpNum = SeenV1 ? 0 : 1;
5230   return true;
5231 }
5232
5233 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5234 /// logical left shift of a vector.
5235 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5236                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5237   unsigned NumElems =
5238     SVOp->getSimpleValueType(0).getVectorNumElements();
5239   unsigned NumZeros = getNumOfConsecutiveZeros(
5240       SVOp, NumElems, false /* check zeros from right */, DAG,
5241       SVOp->getMaskElt(0));
5242   unsigned OpSrc;
5243
5244   if (!NumZeros)
5245     return false;
5246
5247   // Considering the elements in the mask that are not consecutive zeros,
5248   // check if they consecutively come from only one of the source vectors.
5249   //
5250   //               V1 = {X, A, B, C}     0
5251   //                         \  \  \    /
5252   //   vector_shuffle V1, V2 <1, 2, 3, X>
5253   //
5254   if (!isShuffleMaskConsecutive(SVOp,
5255             0,                   // Mask Start Index
5256             NumElems-NumZeros,   // Mask End Index(exclusive)
5257             NumZeros,            // Where to start looking in the src vector
5258             NumElems,            // Number of elements in vector
5259             OpSrc))              // Which source operand ?
5260     return false;
5261
5262   isLeft = false;
5263   ShAmt = NumZeros;
5264   ShVal = SVOp->getOperand(OpSrc);
5265   return true;
5266 }
5267
5268 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5269 /// logical left shift of a vector.
5270 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5271                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5272   unsigned NumElems =
5273     SVOp->getSimpleValueType(0).getVectorNumElements();
5274   unsigned NumZeros = getNumOfConsecutiveZeros(
5275       SVOp, NumElems, true /* check zeros from left */, DAG,
5276       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5277   unsigned OpSrc;
5278
5279   if (!NumZeros)
5280     return false;
5281
5282   // Considering the elements in the mask that are not consecutive zeros,
5283   // check if they consecutively come from only one of the source vectors.
5284   //
5285   //                           0    { A, B, X, X } = V2
5286   //                          / \    /  /
5287   //   vector_shuffle V1, V2 <X, X, 4, 5>
5288   //
5289   if (!isShuffleMaskConsecutive(SVOp,
5290             NumZeros,     // Mask Start Index
5291             NumElems,     // Mask End Index(exclusive)
5292             0,            // Where to start looking in the src vector
5293             NumElems,     // Number of elements in vector
5294             OpSrc))       // Which source operand ?
5295     return false;
5296
5297   isLeft = true;
5298   ShAmt = NumZeros;
5299   ShVal = SVOp->getOperand(OpSrc);
5300   return true;
5301 }
5302
5303 /// isVectorShift - Returns true if the shuffle can be implemented as a
5304 /// logical left or right shift of a vector.
5305 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5306                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5307   // Although the logic below support any bitwidth size, there are no
5308   // shift instructions which handle more than 128-bit vectors.
5309   if (!SVOp->getSimpleValueType(0).is128BitVector())
5310     return false;
5311
5312   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5313       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5314     return true;
5315
5316   return false;
5317 }
5318
5319 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5320 ///
5321 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5322                                        unsigned NumNonZero, unsigned NumZero,
5323                                        SelectionDAG &DAG,
5324                                        const X86Subtarget* Subtarget,
5325                                        const TargetLowering &TLI) {
5326   if (NumNonZero > 8)
5327     return SDValue();
5328
5329   SDLoc dl(Op);
5330   SDValue V;
5331   bool First = true;
5332   for (unsigned i = 0; i < 16; ++i) {
5333     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5334     if (ThisIsNonZero && First) {
5335       if (NumZero)
5336         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5337       else
5338         V = DAG.getUNDEF(MVT::v8i16);
5339       First = false;
5340     }
5341
5342     if ((i & 1) != 0) {
5343       SDValue ThisElt, LastElt;
5344       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5345       if (LastIsNonZero) {
5346         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5347                               MVT::i16, Op.getOperand(i-1));
5348       }
5349       if (ThisIsNonZero) {
5350         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5351         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5352                               ThisElt, DAG.getConstant(8, MVT::i8));
5353         if (LastIsNonZero)
5354           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5355       } else
5356         ThisElt = LastElt;
5357
5358       if (ThisElt.getNode())
5359         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5360                         DAG.getIntPtrConstant(i/2));
5361     }
5362   }
5363
5364   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5365 }
5366
5367 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5368 ///
5369 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5370                                      unsigned NumNonZero, unsigned NumZero,
5371                                      SelectionDAG &DAG,
5372                                      const X86Subtarget* Subtarget,
5373                                      const TargetLowering &TLI) {
5374   if (NumNonZero > 4)
5375     return SDValue();
5376
5377   SDLoc dl(Op);
5378   SDValue V;
5379   bool First = true;
5380   for (unsigned i = 0; i < 8; ++i) {
5381     bool isNonZero = (NonZeros & (1 << i)) != 0;
5382     if (isNonZero) {
5383       if (First) {
5384         if (NumZero)
5385           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5386         else
5387           V = DAG.getUNDEF(MVT::v8i16);
5388         First = false;
5389       }
5390       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5391                       MVT::v8i16, V, Op.getOperand(i),
5392                       DAG.getIntPtrConstant(i));
5393     }
5394   }
5395
5396   return V;
5397 }
5398
5399 /// getVShift - Return a vector logical shift node.
5400 ///
5401 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5402                          unsigned NumBits, SelectionDAG &DAG,
5403                          const TargetLowering &TLI, SDLoc dl) {
5404   assert(VT.is128BitVector() && "Unknown type for VShift");
5405   EVT ShVT = MVT::v2i64;
5406   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5407   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5408   return DAG.getNode(ISD::BITCAST, dl, VT,
5409                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5410                              DAG.getConstant(NumBits,
5411                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5412 }
5413
5414 static SDValue
5415 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5416
5417   // Check if the scalar load can be widened into a vector load. And if
5418   // the address is "base + cst" see if the cst can be "absorbed" into
5419   // the shuffle mask.
5420   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5421     SDValue Ptr = LD->getBasePtr();
5422     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5423       return SDValue();
5424     EVT PVT = LD->getValueType(0);
5425     if (PVT != MVT::i32 && PVT != MVT::f32)
5426       return SDValue();
5427
5428     int FI = -1;
5429     int64_t Offset = 0;
5430     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5431       FI = FINode->getIndex();
5432       Offset = 0;
5433     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5434                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5435       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5436       Offset = Ptr.getConstantOperandVal(1);
5437       Ptr = Ptr.getOperand(0);
5438     } else {
5439       return SDValue();
5440     }
5441
5442     // FIXME: 256-bit vector instructions don't require a strict alignment,
5443     // improve this code to support it better.
5444     unsigned RequiredAlign = VT.getSizeInBits()/8;
5445     SDValue Chain = LD->getChain();
5446     // Make sure the stack object alignment is at least 16 or 32.
5447     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5448     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5449       if (MFI->isFixedObjectIndex(FI)) {
5450         // Can't change the alignment. FIXME: It's possible to compute
5451         // the exact stack offset and reference FI + adjust offset instead.
5452         // If someone *really* cares about this. That's the way to implement it.
5453         return SDValue();
5454       } else {
5455         MFI->setObjectAlignment(FI, RequiredAlign);
5456       }
5457     }
5458
5459     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5460     // Ptr + (Offset & ~15).
5461     if (Offset < 0)
5462       return SDValue();
5463     if ((Offset % RequiredAlign) & 3)
5464       return SDValue();
5465     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5466     if (StartOffset)
5467       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5468                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5469
5470     int EltNo = (Offset - StartOffset) >> 2;
5471     unsigned NumElems = VT.getVectorNumElements();
5472
5473     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5474     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5475                              LD->getPointerInfo().getWithOffset(StartOffset),
5476                              false, false, false, 0);
5477
5478     SmallVector<int, 8> Mask;
5479     for (unsigned i = 0; i != NumElems; ++i)
5480       Mask.push_back(EltNo);
5481
5482     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5483   }
5484
5485   return SDValue();
5486 }
5487
5488 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5489 /// vector of type 'VT', see if the elements can be replaced by a single large
5490 /// load which has the same value as a build_vector whose operands are 'elts'.
5491 ///
5492 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5493 ///
5494 /// FIXME: we'd also like to handle the case where the last elements are zero
5495 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5496 /// There's even a handy isZeroNode for that purpose.
5497 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5498                                         SDLoc &DL, SelectionDAG &DAG,
5499                                         bool isAfterLegalize) {
5500   EVT EltVT = VT.getVectorElementType();
5501   unsigned NumElems = Elts.size();
5502
5503   LoadSDNode *LDBase = nullptr;
5504   unsigned LastLoadedElt = -1U;
5505
5506   // For each element in the initializer, see if we've found a load or an undef.
5507   // If we don't find an initial load element, or later load elements are
5508   // non-consecutive, bail out.
5509   for (unsigned i = 0; i < NumElems; ++i) {
5510     SDValue Elt = Elts[i];
5511
5512     if (!Elt.getNode() ||
5513         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5514       return SDValue();
5515     if (!LDBase) {
5516       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5517         return SDValue();
5518       LDBase = cast<LoadSDNode>(Elt.getNode());
5519       LastLoadedElt = i;
5520       continue;
5521     }
5522     if (Elt.getOpcode() == ISD::UNDEF)
5523       continue;
5524
5525     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5526     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5527       return SDValue();
5528     LastLoadedElt = i;
5529   }
5530
5531   // If we have found an entire vector of loads and undefs, then return a large
5532   // load of the entire vector width starting at the base pointer.  If we found
5533   // consecutive loads for the low half, generate a vzext_load node.
5534   if (LastLoadedElt == NumElems - 1) {
5535
5536     if (isAfterLegalize &&
5537         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5538       return SDValue();
5539
5540     SDValue NewLd = SDValue();
5541
5542     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5543       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5544                           LDBase->getPointerInfo(),
5545                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5546                           LDBase->isInvariant(), 0);
5547     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5548                         LDBase->getPointerInfo(),
5549                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5550                         LDBase->isInvariant(), LDBase->getAlignment());
5551
5552     if (LDBase->hasAnyUseOfValue(1)) {
5553       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5554                                      SDValue(LDBase, 1),
5555                                      SDValue(NewLd.getNode(), 1));
5556       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5557       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5558                              SDValue(NewLd.getNode(), 1));
5559     }
5560
5561     return NewLd;
5562   }
5563   if (NumElems == 4 && LastLoadedElt == 1 &&
5564       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5565     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5566     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5567     SDValue ResNode =
5568         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5569                                 array_lengthof(Ops), MVT::i64,
5570                                 LDBase->getPointerInfo(),
5571                                 LDBase->getAlignment(),
5572                                 false/*isVolatile*/, true/*ReadMem*/,
5573                                 false/*WriteMem*/);
5574
5575     // Make sure the newly-created LOAD is in the same position as LDBase in
5576     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5577     // update uses of LDBase's output chain to use the TokenFactor.
5578     if (LDBase->hasAnyUseOfValue(1)) {
5579       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5580                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5581       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5582       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5583                              SDValue(ResNode.getNode(), 1));
5584     }
5585
5586     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5587   }
5588   return SDValue();
5589 }
5590
5591 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5592 /// to generate a splat value for the following cases:
5593 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5594 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5595 /// a scalar load, or a constant.
5596 /// The VBROADCAST node is returned when a pattern is found,
5597 /// or SDValue() otherwise.
5598 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5599                                     SelectionDAG &DAG) {
5600   if (!Subtarget->hasFp256())
5601     return SDValue();
5602
5603   MVT VT = Op.getSimpleValueType();
5604   SDLoc dl(Op);
5605
5606   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5607          "Unsupported vector type for broadcast.");
5608
5609   SDValue Ld;
5610   bool ConstSplatVal;
5611
5612   switch (Op.getOpcode()) {
5613     default:
5614       // Unknown pattern found.
5615       return SDValue();
5616
5617     case ISD::BUILD_VECTOR: {
5618       // The BUILD_VECTOR node must be a splat.
5619       if (!isSplatVector(Op.getNode()))
5620         return SDValue();
5621
5622       Ld = Op.getOperand(0);
5623       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5624                      Ld.getOpcode() == ISD::ConstantFP);
5625
5626       // The suspected load node has several users. Make sure that all
5627       // of its users are from the BUILD_VECTOR node.
5628       // Constants may have multiple users.
5629       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5630         return SDValue();
5631       break;
5632     }
5633
5634     case ISD::VECTOR_SHUFFLE: {
5635       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5636
5637       // Shuffles must have a splat mask where the first element is
5638       // broadcasted.
5639       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5640         return SDValue();
5641
5642       SDValue Sc = Op.getOperand(0);
5643       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5644           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5645
5646         if (!Subtarget->hasInt256())
5647           return SDValue();
5648
5649         // Use the register form of the broadcast instruction available on AVX2.
5650         if (VT.getSizeInBits() >= 256)
5651           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5652         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5653       }
5654
5655       Ld = Sc.getOperand(0);
5656       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5657                        Ld.getOpcode() == ISD::ConstantFP);
5658
5659       // The scalar_to_vector node and the suspected
5660       // load node must have exactly one user.
5661       // Constants may have multiple users.
5662
5663       // AVX-512 has register version of the broadcast
5664       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5665         Ld.getValueType().getSizeInBits() >= 32;
5666       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5667           !hasRegVer))
5668         return SDValue();
5669       break;
5670     }
5671   }
5672
5673   bool IsGE256 = (VT.getSizeInBits() >= 256);
5674
5675   // Handle the broadcasting a single constant scalar from the constant pool
5676   // into a vector. On Sandybridge it is still better to load a constant vector
5677   // from the constant pool and not to broadcast it from a scalar.
5678   if (ConstSplatVal && Subtarget->hasInt256()) {
5679     EVT CVT = Ld.getValueType();
5680     assert(!CVT.isVector() && "Must not broadcast a vector type");
5681     unsigned ScalarSize = CVT.getSizeInBits();
5682
5683     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5684       const Constant *C = nullptr;
5685       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5686         C = CI->getConstantIntValue();
5687       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5688         C = CF->getConstantFPValue();
5689
5690       assert(C && "Invalid constant type");
5691
5692       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5693       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5694       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5695       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5696                        MachinePointerInfo::getConstantPool(),
5697                        false, false, false, Alignment);
5698
5699       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5700     }
5701   }
5702
5703   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5704   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5705
5706   // Handle AVX2 in-register broadcasts.
5707   if (!IsLoad && Subtarget->hasInt256() &&
5708       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5709     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5710
5711   // The scalar source must be a normal load.
5712   if (!IsLoad)
5713     return SDValue();
5714
5715   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5716     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5717
5718   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5719   // double since there is no vbroadcastsd xmm
5720   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5721     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5722       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5723   }
5724
5725   // Unsupported broadcast.
5726   return SDValue();
5727 }
5728
5729 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5730 /// underlying vector and index.
5731 ///
5732 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5733 /// index.
5734 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5735                                          SDValue ExtIdx) {
5736   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5737   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5738     return Idx;
5739
5740   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5741   // lowered this:
5742   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5743   // to:
5744   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5745   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5746   //                           undef)
5747   //                       Constant<0>)
5748   // In this case the vector is the extract_subvector expression and the index
5749   // is 2, as specified by the shuffle.
5750   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5751   SDValue ShuffleVec = SVOp->getOperand(0);
5752   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5753   assert(ShuffleVecVT.getVectorElementType() ==
5754          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5755
5756   int ShuffleIdx = SVOp->getMaskElt(Idx);
5757   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5758     ExtractedFromVec = ShuffleVec;
5759     return ShuffleIdx;
5760   }
5761   return Idx;
5762 }
5763
5764 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5765   MVT VT = Op.getSimpleValueType();
5766
5767   // Skip if insert_vec_elt is not supported.
5768   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5769   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5770     return SDValue();
5771
5772   SDLoc DL(Op);
5773   unsigned NumElems = Op.getNumOperands();
5774
5775   SDValue VecIn1;
5776   SDValue VecIn2;
5777   SmallVector<unsigned, 4> InsertIndices;
5778   SmallVector<int, 8> Mask(NumElems, -1);
5779
5780   for (unsigned i = 0; i != NumElems; ++i) {
5781     unsigned Opc = Op.getOperand(i).getOpcode();
5782
5783     if (Opc == ISD::UNDEF)
5784       continue;
5785
5786     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5787       // Quit if more than 1 elements need inserting.
5788       if (InsertIndices.size() > 1)
5789         return SDValue();
5790
5791       InsertIndices.push_back(i);
5792       continue;
5793     }
5794
5795     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5796     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5797     // Quit if non-constant index.
5798     if (!isa<ConstantSDNode>(ExtIdx))
5799       return SDValue();
5800     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5801
5802     // Quit if extracted from vector of different type.
5803     if (ExtractedFromVec.getValueType() != VT)
5804       return SDValue();
5805
5806     if (!VecIn1.getNode())
5807       VecIn1 = ExtractedFromVec;
5808     else if (VecIn1 != ExtractedFromVec) {
5809       if (!VecIn2.getNode())
5810         VecIn2 = ExtractedFromVec;
5811       else if (VecIn2 != ExtractedFromVec)
5812         // Quit if more than 2 vectors to shuffle
5813         return SDValue();
5814     }
5815
5816     if (ExtractedFromVec == VecIn1)
5817       Mask[i] = Idx;
5818     else if (ExtractedFromVec == VecIn2)
5819       Mask[i] = Idx + NumElems;
5820   }
5821
5822   if (!VecIn1.getNode())
5823     return SDValue();
5824
5825   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5826   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5827   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5828     unsigned Idx = InsertIndices[i];
5829     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5830                      DAG.getIntPtrConstant(Idx));
5831   }
5832
5833   return NV;
5834 }
5835
5836 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5837 SDValue
5838 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5839
5840   MVT VT = Op.getSimpleValueType();
5841   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5842          "Unexpected type in LowerBUILD_VECTORvXi1!");
5843
5844   SDLoc dl(Op);
5845   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5846     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5847     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5848     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5849   }
5850
5851   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5852     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5853     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5854     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5855   }
5856
5857   bool AllContants = true;
5858   uint64_t Immediate = 0;
5859   int NonConstIdx = -1;
5860   bool IsSplat = true;
5861   unsigned NumNonConsts = 0;
5862   unsigned NumConsts = 0;
5863   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5864     SDValue In = Op.getOperand(idx);
5865     if (In.getOpcode() == ISD::UNDEF)
5866       continue;
5867     if (!isa<ConstantSDNode>(In)) {
5868       AllContants = false;
5869       NonConstIdx = idx;
5870       NumNonConsts++;
5871     }
5872     else {
5873       NumConsts++;
5874       if (cast<ConstantSDNode>(In)->getZExtValue())
5875       Immediate |= (1ULL << idx);
5876     }
5877     if (In != Op.getOperand(0))
5878       IsSplat = false;
5879   }
5880
5881   if (AllContants) {
5882     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5883       DAG.getConstant(Immediate, MVT::i16));
5884     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5885                        DAG.getIntPtrConstant(0));
5886   }
5887
5888   if (NumNonConsts == 1 && NonConstIdx != 0) {
5889     SDValue DstVec;
5890     if (NumConsts) {
5891       SDValue VecAsImm = DAG.getConstant(Immediate,
5892                                          MVT::getIntegerVT(VT.getSizeInBits()));
5893       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5894     }
5895     else 
5896       DstVec = DAG.getUNDEF(VT);
5897     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5898                        Op.getOperand(NonConstIdx),
5899                        DAG.getIntPtrConstant(NonConstIdx));
5900   }
5901   if (!IsSplat && (NonConstIdx != 0))
5902     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5903   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5904   SDValue Select;
5905   if (IsSplat)
5906     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5907                           DAG.getConstant(-1, SelectVT),
5908                           DAG.getConstant(0, SelectVT));
5909   else
5910     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5911                          DAG.getConstant((Immediate | 1), SelectVT),
5912                          DAG.getConstant(Immediate, SelectVT));
5913   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5914 }
5915
5916 SDValue
5917 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5918   SDLoc dl(Op);
5919
5920   MVT VT = Op.getSimpleValueType();
5921   MVT ExtVT = VT.getVectorElementType();
5922   unsigned NumElems = Op.getNumOperands();
5923
5924   // Generate vectors for predicate vectors.
5925   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5926     return LowerBUILD_VECTORvXi1(Op, DAG);
5927
5928   // Vectors containing all zeros can be matched by pxor and xorps later
5929   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5930     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5931     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5932     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5933       return Op;
5934
5935     return getZeroVector(VT, Subtarget, DAG, dl);
5936   }
5937
5938   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5939   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5940   // vpcmpeqd on 256-bit vectors.
5941   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5942     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5943       return Op;
5944
5945     if (!VT.is512BitVector())
5946       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5947   }
5948
5949   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5950   if (Broadcast.getNode())
5951     return Broadcast;
5952
5953   unsigned EVTBits = ExtVT.getSizeInBits();
5954
5955   unsigned NumZero  = 0;
5956   unsigned NumNonZero = 0;
5957   unsigned NonZeros = 0;
5958   bool IsAllConstants = true;
5959   SmallSet<SDValue, 8> Values;
5960   for (unsigned i = 0; i < NumElems; ++i) {
5961     SDValue Elt = Op.getOperand(i);
5962     if (Elt.getOpcode() == ISD::UNDEF)
5963       continue;
5964     Values.insert(Elt);
5965     if (Elt.getOpcode() != ISD::Constant &&
5966         Elt.getOpcode() != ISD::ConstantFP)
5967       IsAllConstants = false;
5968     if (X86::isZeroNode(Elt))
5969       NumZero++;
5970     else {
5971       NonZeros |= (1 << i);
5972       NumNonZero++;
5973     }
5974   }
5975
5976   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5977   if (NumNonZero == 0)
5978     return DAG.getUNDEF(VT);
5979
5980   // Special case for single non-zero, non-undef, element.
5981   if (NumNonZero == 1) {
5982     unsigned Idx = countTrailingZeros(NonZeros);
5983     SDValue Item = Op.getOperand(Idx);
5984
5985     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5986     // the value are obviously zero, truncate the value to i32 and do the
5987     // insertion that way.  Only do this if the value is non-constant or if the
5988     // value is a constant being inserted into element 0.  It is cheaper to do
5989     // a constant pool load than it is to do a movd + shuffle.
5990     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5991         (!IsAllConstants || Idx == 0)) {
5992       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5993         // Handle SSE only.
5994         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5995         EVT VecVT = MVT::v4i32;
5996         unsigned VecElts = 4;
5997
5998         // Truncate the value (which may itself be a constant) to i32, and
5999         // convert it to a vector with movd (S2V+shuffle to zero extend).
6000         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6001         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6002         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6003
6004         // Now we have our 32-bit value zero extended in the low element of
6005         // a vector.  If Idx != 0, swizzle it into place.
6006         if (Idx != 0) {
6007           SmallVector<int, 4> Mask;
6008           Mask.push_back(Idx);
6009           for (unsigned i = 1; i != VecElts; ++i)
6010             Mask.push_back(i);
6011           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6012                                       &Mask[0]);
6013         }
6014         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6015       }
6016     }
6017
6018     // If we have a constant or non-constant insertion into the low element of
6019     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6020     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6021     // depending on what the source datatype is.
6022     if (Idx == 0) {
6023       if (NumZero == 0)
6024         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6025
6026       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6027           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6028         if (VT.is256BitVector() || VT.is512BitVector()) {
6029           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6030           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6031                              Item, DAG.getIntPtrConstant(0));
6032         }
6033         assert(VT.is128BitVector() && "Expected an SSE value type!");
6034         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6035         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6036         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6037       }
6038
6039       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6040         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6041         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6042         if (VT.is256BitVector()) {
6043           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6044           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6045         } else {
6046           assert(VT.is128BitVector() && "Expected an SSE value type!");
6047           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6048         }
6049         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6050       }
6051     }
6052
6053     // Is it a vector logical left shift?
6054     if (NumElems == 2 && Idx == 1 &&
6055         X86::isZeroNode(Op.getOperand(0)) &&
6056         !X86::isZeroNode(Op.getOperand(1))) {
6057       unsigned NumBits = VT.getSizeInBits();
6058       return getVShift(true, VT,
6059                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6060                                    VT, Op.getOperand(1)),
6061                        NumBits/2, DAG, *this, dl);
6062     }
6063
6064     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6065       return SDValue();
6066
6067     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6068     // is a non-constant being inserted into an element other than the low one,
6069     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6070     // movd/movss) to move this into the low element, then shuffle it into
6071     // place.
6072     if (EVTBits == 32) {
6073       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6074
6075       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6076       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6077       SmallVector<int, 8> MaskVec;
6078       for (unsigned i = 0; i != NumElems; ++i)
6079         MaskVec.push_back(i == Idx ? 0 : 1);
6080       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6081     }
6082   }
6083
6084   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6085   if (Values.size() == 1) {
6086     if (EVTBits == 32) {
6087       // Instead of a shuffle like this:
6088       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6089       // Check if it's possible to issue this instead.
6090       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6091       unsigned Idx = countTrailingZeros(NonZeros);
6092       SDValue Item = Op.getOperand(Idx);
6093       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6094         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6095     }
6096     return SDValue();
6097   }
6098
6099   // A vector full of immediates; various special cases are already
6100   // handled, so this is best done with a single constant-pool load.
6101   if (IsAllConstants)
6102     return SDValue();
6103
6104   // For AVX-length vectors, build the individual 128-bit pieces and use
6105   // shuffles to put them in place.
6106   if (VT.is256BitVector() || VT.is512BitVector()) {
6107     SmallVector<SDValue, 64> V;
6108     for (unsigned i = 0; i != NumElems; ++i)
6109       V.push_back(Op.getOperand(i));
6110
6111     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6112
6113     // Build both the lower and upper subvector.
6114     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6115                                 ArrayRef<SDValue>(&V[0], NumElems/2));
6116     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6117                                 ArrayRef<SDValue>(&V[NumElems / 2],
6118                                                   NumElems/2));
6119
6120     // Recreate the wider vector with the lower and upper part.
6121     if (VT.is256BitVector())
6122       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6123     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6124   }
6125
6126   // Let legalizer expand 2-wide build_vectors.
6127   if (EVTBits == 64) {
6128     if (NumNonZero == 1) {
6129       // One half is zero or undef.
6130       unsigned Idx = countTrailingZeros(NonZeros);
6131       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6132                                  Op.getOperand(Idx));
6133       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6134     }
6135     return SDValue();
6136   }
6137
6138   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6139   if (EVTBits == 8 && NumElems == 16) {
6140     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6141                                         Subtarget, *this);
6142     if (V.getNode()) return V;
6143   }
6144
6145   if (EVTBits == 16 && NumElems == 8) {
6146     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6147                                       Subtarget, *this);
6148     if (V.getNode()) return V;
6149   }
6150
6151   // If element VT is == 32 bits, turn it into a number of shuffles.
6152   SmallVector<SDValue, 8> V(NumElems);
6153   if (NumElems == 4 && NumZero > 0) {
6154     for (unsigned i = 0; i < 4; ++i) {
6155       bool isZero = !(NonZeros & (1 << i));
6156       if (isZero)
6157         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6158       else
6159         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6160     }
6161
6162     for (unsigned i = 0; i < 2; ++i) {
6163       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6164         default: break;
6165         case 0:
6166           V[i] = V[i*2];  // Must be a zero vector.
6167           break;
6168         case 1:
6169           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6170           break;
6171         case 2:
6172           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6173           break;
6174         case 3:
6175           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6176           break;
6177       }
6178     }
6179
6180     bool Reverse1 = (NonZeros & 0x3) == 2;
6181     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6182     int MaskVec[] = {
6183       Reverse1 ? 1 : 0,
6184       Reverse1 ? 0 : 1,
6185       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6186       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6187     };
6188     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6189   }
6190
6191   if (Values.size() > 1 && VT.is128BitVector()) {
6192     // Check for a build vector of consecutive loads.
6193     for (unsigned i = 0; i < NumElems; ++i)
6194       V[i] = Op.getOperand(i);
6195
6196     // Check for elements which are consecutive loads.
6197     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6198     if (LD.getNode())
6199       return LD;
6200
6201     // Check for a build vector from mostly shuffle plus few inserting.
6202     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6203     if (Sh.getNode())
6204       return Sh;
6205
6206     // For SSE 4.1, use insertps to put the high elements into the low element.
6207     if (getSubtarget()->hasSSE41()) {
6208       SDValue Result;
6209       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6210         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6211       else
6212         Result = DAG.getUNDEF(VT);
6213
6214       for (unsigned i = 1; i < NumElems; ++i) {
6215         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6216         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6217                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6218       }
6219       return Result;
6220     }
6221
6222     // Otherwise, expand into a number of unpckl*, start by extending each of
6223     // our (non-undef) elements to the full vector width with the element in the
6224     // bottom slot of the vector (which generates no code for SSE).
6225     for (unsigned i = 0; i < NumElems; ++i) {
6226       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6227         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6228       else
6229         V[i] = DAG.getUNDEF(VT);
6230     }
6231
6232     // Next, we iteratively mix elements, e.g. for v4f32:
6233     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6234     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6235     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6236     unsigned EltStride = NumElems >> 1;
6237     while (EltStride != 0) {
6238       for (unsigned i = 0; i < EltStride; ++i) {
6239         // If V[i+EltStride] is undef and this is the first round of mixing,
6240         // then it is safe to just drop this shuffle: V[i] is already in the
6241         // right place, the one element (since it's the first round) being
6242         // inserted as undef can be dropped.  This isn't safe for successive
6243         // rounds because they will permute elements within both vectors.
6244         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6245             EltStride == NumElems/2)
6246           continue;
6247
6248         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6249       }
6250       EltStride >>= 1;
6251     }
6252     return V[0];
6253   }
6254   return SDValue();
6255 }
6256
6257 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6258 // to create 256-bit vectors from two other 128-bit ones.
6259 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6260   SDLoc dl(Op);
6261   MVT ResVT = Op.getSimpleValueType();
6262
6263   assert((ResVT.is256BitVector() ||
6264           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6265
6266   SDValue V1 = Op.getOperand(0);
6267   SDValue V2 = Op.getOperand(1);
6268   unsigned NumElems = ResVT.getVectorNumElements();
6269   if(ResVT.is256BitVector())
6270     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6271
6272   if (Op.getNumOperands() == 4) {
6273     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6274                                 ResVT.getVectorNumElements()/2);
6275     SDValue V3 = Op.getOperand(2);
6276     SDValue V4 = Op.getOperand(3);
6277     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6278       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6279   }
6280   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6281 }
6282
6283 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6284   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6285   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6286          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6287           Op.getNumOperands() == 4)));
6288
6289   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6290   // from two other 128-bit ones.
6291
6292   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6293   return LowerAVXCONCAT_VECTORS(Op, DAG);
6294 }
6295
6296 // Try to lower a shuffle node into a simple blend instruction.
6297 static SDValue
6298 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6299                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6300   SDValue V1 = SVOp->getOperand(0);
6301   SDValue V2 = SVOp->getOperand(1);
6302   SDLoc dl(SVOp);
6303   MVT VT = SVOp->getSimpleValueType(0);
6304   MVT EltVT = VT.getVectorElementType();
6305   unsigned NumElems = VT.getVectorNumElements();
6306
6307   // There is no blend with immediate in AVX-512.
6308   if (VT.is512BitVector())
6309     return SDValue();
6310
6311   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6312     return SDValue();
6313   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6314     return SDValue();
6315
6316   // Check the mask for BLEND and build the value.
6317   unsigned MaskValue = 0;
6318   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6319   unsigned NumLanes = (NumElems-1)/8 + 1;
6320   unsigned NumElemsInLane = NumElems / NumLanes;
6321
6322   // Blend for v16i16 should be symetric for the both lanes.
6323   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6324
6325     int SndLaneEltIdx = (NumLanes == 2) ?
6326       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6327     int EltIdx = SVOp->getMaskElt(i);
6328
6329     if ((EltIdx < 0 || EltIdx == (int)i) &&
6330         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6331       continue;
6332
6333     if (((unsigned)EltIdx == (i + NumElems)) &&
6334         (SndLaneEltIdx < 0 ||
6335          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6336       MaskValue |= (1<<i);
6337     else
6338       return SDValue();
6339   }
6340
6341   // Convert i32 vectors to floating point if it is not AVX2.
6342   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6343   MVT BlendVT = VT;
6344   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6345     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6346                                NumElems);
6347     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6348     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6349   }
6350
6351   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6352                             DAG.getConstant(MaskValue, MVT::i32));
6353   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6354 }
6355
6356 /// In vector type \p VT, return true if the element at index \p InputIdx
6357 /// falls on a different 128-bit lane than \p OutputIdx.
6358 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6359                                      unsigned OutputIdx) {
6360   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6361   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6362 }
6363
6364 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6365 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6366 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6367 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6368 /// zero.
6369 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6370                          SelectionDAG &DAG) {
6371   MVT VT = V1.getSimpleValueType();
6372   assert(VT.is128BitVector() || VT.is256BitVector());
6373
6374   MVT EltVT = VT.getVectorElementType();
6375   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6376   unsigned NumElts = VT.getVectorNumElements();
6377
6378   SmallVector<SDValue, 32> PshufbMask;
6379   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6380     int InputIdx = MaskVals[OutputIdx];
6381     unsigned InputByteIdx;
6382
6383     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6384       InputByteIdx = 0x80;
6385     else {
6386       // Cross lane is not allowed.
6387       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6388         return SDValue();
6389       InputByteIdx = InputIdx * EltSizeInBytes;
6390       // Index is an byte offset within the 128-bit lane.
6391       InputByteIdx &= 0xf;
6392     }
6393
6394     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6395       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6396       if (InputByteIdx != 0x80)
6397         ++InputByteIdx;
6398     }
6399   }
6400
6401   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6402   if (ShufVT != VT)
6403     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6404   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6405                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6406 }
6407
6408 // v8i16 shuffles - Prefer shuffles in the following order:
6409 // 1. [all]   pshuflw, pshufhw, optional move
6410 // 2. [ssse3] 1 x pshufb
6411 // 3. [ssse3] 2 x pshufb + 1 x por
6412 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6413 static SDValue
6414 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6415                          SelectionDAG &DAG) {
6416   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6417   SDValue V1 = SVOp->getOperand(0);
6418   SDValue V2 = SVOp->getOperand(1);
6419   SDLoc dl(SVOp);
6420   SmallVector<int, 8> MaskVals;
6421
6422   // Determine if more than 1 of the words in each of the low and high quadwords
6423   // of the result come from the same quadword of one of the two inputs.  Undef
6424   // mask values count as coming from any quadword, for better codegen.
6425   //
6426   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6427   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6428   unsigned LoQuad[] = { 0, 0, 0, 0 };
6429   unsigned HiQuad[] = { 0, 0, 0, 0 };
6430   // Indices of quads used.
6431   std::bitset<4> InputQuads;
6432   for (unsigned i = 0; i < 8; ++i) {
6433     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6434     int EltIdx = SVOp->getMaskElt(i);
6435     MaskVals.push_back(EltIdx);
6436     if (EltIdx < 0) {
6437       ++Quad[0];
6438       ++Quad[1];
6439       ++Quad[2];
6440       ++Quad[3];
6441       continue;
6442     }
6443     ++Quad[EltIdx / 4];
6444     InputQuads.set(EltIdx / 4);
6445   }
6446
6447   int BestLoQuad = -1;
6448   unsigned MaxQuad = 1;
6449   for (unsigned i = 0; i < 4; ++i) {
6450     if (LoQuad[i] > MaxQuad) {
6451       BestLoQuad = i;
6452       MaxQuad = LoQuad[i];
6453     }
6454   }
6455
6456   int BestHiQuad = -1;
6457   MaxQuad = 1;
6458   for (unsigned i = 0; i < 4; ++i) {
6459     if (HiQuad[i] > MaxQuad) {
6460       BestHiQuad = i;
6461       MaxQuad = HiQuad[i];
6462     }
6463   }
6464
6465   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6466   // of the two input vectors, shuffle them into one input vector so only a
6467   // single pshufb instruction is necessary. If there are more than 2 input
6468   // quads, disable the next transformation since it does not help SSSE3.
6469   bool V1Used = InputQuads[0] || InputQuads[1];
6470   bool V2Used = InputQuads[2] || InputQuads[3];
6471   if (Subtarget->hasSSSE3()) {
6472     if (InputQuads.count() == 2 && V1Used && V2Used) {
6473       BestLoQuad = InputQuads[0] ? 0 : 1;
6474       BestHiQuad = InputQuads[2] ? 2 : 3;
6475     }
6476     if (InputQuads.count() > 2) {
6477       BestLoQuad = -1;
6478       BestHiQuad = -1;
6479     }
6480   }
6481
6482   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6483   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6484   // words from all 4 input quadwords.
6485   SDValue NewV;
6486   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6487     int MaskV[] = {
6488       BestLoQuad < 0 ? 0 : BestLoQuad,
6489       BestHiQuad < 0 ? 1 : BestHiQuad
6490     };
6491     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6492                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6493                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6494     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6495
6496     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6497     // source words for the shuffle, to aid later transformations.
6498     bool AllWordsInNewV = true;
6499     bool InOrder[2] = { true, true };
6500     for (unsigned i = 0; i != 8; ++i) {
6501       int idx = MaskVals[i];
6502       if (idx != (int)i)
6503         InOrder[i/4] = false;
6504       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6505         continue;
6506       AllWordsInNewV = false;
6507       break;
6508     }
6509
6510     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6511     if (AllWordsInNewV) {
6512       for (int i = 0; i != 8; ++i) {
6513         int idx = MaskVals[i];
6514         if (idx < 0)
6515           continue;
6516         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6517         if ((idx != i) && idx < 4)
6518           pshufhw = false;
6519         if ((idx != i) && idx > 3)
6520           pshuflw = false;
6521       }
6522       V1 = NewV;
6523       V2Used = false;
6524       BestLoQuad = 0;
6525       BestHiQuad = 1;
6526     }
6527
6528     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6529     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6530     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6531       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6532       unsigned TargetMask = 0;
6533       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6534                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6535       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6536       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6537                              getShufflePSHUFLWImmediate(SVOp);
6538       V1 = NewV.getOperand(0);
6539       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6540     }
6541   }
6542
6543   // Promote splats to a larger type which usually leads to more efficient code.
6544   // FIXME: Is this true if pshufb is available?
6545   if (SVOp->isSplat())
6546     return PromoteSplat(SVOp, DAG);
6547
6548   // If we have SSSE3, and all words of the result are from 1 input vector,
6549   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6550   // is present, fall back to case 4.
6551   if (Subtarget->hasSSSE3()) {
6552     SmallVector<SDValue,16> pshufbMask;
6553
6554     // If we have elements from both input vectors, set the high bit of the
6555     // shuffle mask element to zero out elements that come from V2 in the V1
6556     // mask, and elements that come from V1 in the V2 mask, so that the two
6557     // results can be OR'd together.
6558     bool TwoInputs = V1Used && V2Used;
6559     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6560     if (!TwoInputs)
6561       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6562
6563     // Calculate the shuffle mask for the second input, shuffle it, and
6564     // OR it with the first shuffled input.
6565     CommuteVectorShuffleMask(MaskVals, 8);
6566     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6567     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6568     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6569   }
6570
6571   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6572   // and update MaskVals with new element order.
6573   std::bitset<8> InOrder;
6574   if (BestLoQuad >= 0) {
6575     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6576     for (int i = 0; i != 4; ++i) {
6577       int idx = MaskVals[i];
6578       if (idx < 0) {
6579         InOrder.set(i);
6580       } else if ((idx / 4) == BestLoQuad) {
6581         MaskV[i] = idx & 3;
6582         InOrder.set(i);
6583       }
6584     }
6585     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6586                                 &MaskV[0]);
6587
6588     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6589       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6590       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6591                                   NewV.getOperand(0),
6592                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6593     }
6594   }
6595
6596   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6597   // and update MaskVals with the new element order.
6598   if (BestHiQuad >= 0) {
6599     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6600     for (unsigned i = 4; i != 8; ++i) {
6601       int idx = MaskVals[i];
6602       if (idx < 0) {
6603         InOrder.set(i);
6604       } else if ((idx / 4) == BestHiQuad) {
6605         MaskV[i] = (idx & 3) + 4;
6606         InOrder.set(i);
6607       }
6608     }
6609     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6610                                 &MaskV[0]);
6611
6612     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6613       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6614       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6615                                   NewV.getOperand(0),
6616                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6617     }
6618   }
6619
6620   // In case BestHi & BestLo were both -1, which means each quadword has a word
6621   // from each of the four input quadwords, calculate the InOrder bitvector now
6622   // before falling through to the insert/extract cleanup.
6623   if (BestLoQuad == -1 && BestHiQuad == -1) {
6624     NewV = V1;
6625     for (int i = 0; i != 8; ++i)
6626       if (MaskVals[i] < 0 || MaskVals[i] == i)
6627         InOrder.set(i);
6628   }
6629
6630   // The other elements are put in the right place using pextrw and pinsrw.
6631   for (unsigned i = 0; i != 8; ++i) {
6632     if (InOrder[i])
6633       continue;
6634     int EltIdx = MaskVals[i];
6635     if (EltIdx < 0)
6636       continue;
6637     SDValue ExtOp = (EltIdx < 8) ?
6638       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6639                   DAG.getIntPtrConstant(EltIdx)) :
6640       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6641                   DAG.getIntPtrConstant(EltIdx - 8));
6642     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6643                        DAG.getIntPtrConstant(i));
6644   }
6645   return NewV;
6646 }
6647
6648 /// \brief v16i16 shuffles
6649 ///
6650 /// FIXME: We only support generation of a single pshufb currently.  We can
6651 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6652 /// well (e.g 2 x pshufb + 1 x por).
6653 static SDValue
6654 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6655   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6656   SDValue V1 = SVOp->getOperand(0);
6657   SDValue V2 = SVOp->getOperand(1);
6658   SDLoc dl(SVOp);
6659
6660   if (V2.getOpcode() != ISD::UNDEF)
6661     return SDValue();
6662
6663   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6664   return getPSHUFB(MaskVals, V1, dl, DAG);
6665 }
6666
6667 // v16i8 shuffles - Prefer shuffles in the following order:
6668 // 1. [ssse3] 1 x pshufb
6669 // 2. [ssse3] 2 x pshufb + 1 x por
6670 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6671 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6672                                         const X86Subtarget* Subtarget,
6673                                         SelectionDAG &DAG) {
6674   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6675   SDValue V1 = SVOp->getOperand(0);
6676   SDValue V2 = SVOp->getOperand(1);
6677   SDLoc dl(SVOp);
6678   ArrayRef<int> MaskVals = SVOp->getMask();
6679
6680   // Promote splats to a larger type which usually leads to more efficient code.
6681   // FIXME: Is this true if pshufb is available?
6682   if (SVOp->isSplat())
6683     return PromoteSplat(SVOp, DAG);
6684
6685   // If we have SSSE3, case 1 is generated when all result bytes come from
6686   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6687   // present, fall back to case 3.
6688
6689   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6690   if (Subtarget->hasSSSE3()) {
6691     SmallVector<SDValue,16> pshufbMask;
6692
6693     // If all result elements are from one input vector, then only translate
6694     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6695     //
6696     // Otherwise, we have elements from both input vectors, and must zero out
6697     // elements that come from V2 in the first mask, and V1 in the second mask
6698     // so that we can OR them together.
6699     for (unsigned i = 0; i != 16; ++i) {
6700       int EltIdx = MaskVals[i];
6701       if (EltIdx < 0 || EltIdx >= 16)
6702         EltIdx = 0x80;
6703       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6704     }
6705     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6706                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6707                                  MVT::v16i8, pshufbMask));
6708
6709     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6710     // the 2nd operand if it's undefined or zero.
6711     if (V2.getOpcode() == ISD::UNDEF ||
6712         ISD::isBuildVectorAllZeros(V2.getNode()))
6713       return V1;
6714
6715     // Calculate the shuffle mask for the second input, shuffle it, and
6716     // OR it with the first shuffled input.
6717     pshufbMask.clear();
6718     for (unsigned i = 0; i != 16; ++i) {
6719       int EltIdx = MaskVals[i];
6720       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6721       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6722     }
6723     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6724                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6725                                  MVT::v16i8, pshufbMask));
6726     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6727   }
6728
6729   // No SSSE3 - Calculate in place words and then fix all out of place words
6730   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6731   // the 16 different words that comprise the two doublequadword input vectors.
6732   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6733   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6734   SDValue NewV = V1;
6735   for (int i = 0; i != 8; ++i) {
6736     int Elt0 = MaskVals[i*2];
6737     int Elt1 = MaskVals[i*2+1];
6738
6739     // This word of the result is all undef, skip it.
6740     if (Elt0 < 0 && Elt1 < 0)
6741       continue;
6742
6743     // This word of the result is already in the correct place, skip it.
6744     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6745       continue;
6746
6747     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6748     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6749     SDValue InsElt;
6750
6751     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6752     // using a single extract together, load it and store it.
6753     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6754       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6755                            DAG.getIntPtrConstant(Elt1 / 2));
6756       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6757                         DAG.getIntPtrConstant(i));
6758       continue;
6759     }
6760
6761     // If Elt1 is defined, extract it from the appropriate source.  If the
6762     // source byte is not also odd, shift the extracted word left 8 bits
6763     // otherwise clear the bottom 8 bits if we need to do an or.
6764     if (Elt1 >= 0) {
6765       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6766                            DAG.getIntPtrConstant(Elt1 / 2));
6767       if ((Elt1 & 1) == 0)
6768         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6769                              DAG.getConstant(8,
6770                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6771       else if (Elt0 >= 0)
6772         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6773                              DAG.getConstant(0xFF00, MVT::i16));
6774     }
6775     // If Elt0 is defined, extract it from the appropriate source.  If the
6776     // source byte is not also even, shift the extracted word right 8 bits. If
6777     // Elt1 was also defined, OR the extracted values together before
6778     // inserting them in the result.
6779     if (Elt0 >= 0) {
6780       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6781                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6782       if ((Elt0 & 1) != 0)
6783         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6784                               DAG.getConstant(8,
6785                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6786       else if (Elt1 >= 0)
6787         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6788                              DAG.getConstant(0x00FF, MVT::i16));
6789       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6790                          : InsElt0;
6791     }
6792     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6793                        DAG.getIntPtrConstant(i));
6794   }
6795   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6796 }
6797
6798 // v32i8 shuffles - Translate to VPSHUFB if possible.
6799 static
6800 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6801                                  const X86Subtarget *Subtarget,
6802                                  SelectionDAG &DAG) {
6803   MVT VT = SVOp->getSimpleValueType(0);
6804   SDValue V1 = SVOp->getOperand(0);
6805   SDValue V2 = SVOp->getOperand(1);
6806   SDLoc dl(SVOp);
6807   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6808
6809   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6810   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6811   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6812
6813   // VPSHUFB may be generated if
6814   // (1) one of input vector is undefined or zeroinitializer.
6815   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6816   // And (2) the mask indexes don't cross the 128-bit lane.
6817   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6818       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6819     return SDValue();
6820
6821   if (V1IsAllZero && !V2IsAllZero) {
6822     CommuteVectorShuffleMask(MaskVals, 32);
6823     V1 = V2;
6824   }
6825   return getPSHUFB(MaskVals, V1, dl, DAG);
6826 }
6827
6828 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6829 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6830 /// done when every pair / quad of shuffle mask elements point to elements in
6831 /// the right sequence. e.g.
6832 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6833 static
6834 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6835                                  SelectionDAG &DAG) {
6836   MVT VT = SVOp->getSimpleValueType(0);
6837   SDLoc dl(SVOp);
6838   unsigned NumElems = VT.getVectorNumElements();
6839   MVT NewVT;
6840   unsigned Scale;
6841   switch (VT.SimpleTy) {
6842   default: llvm_unreachable("Unexpected!");
6843   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6844   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6845   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6846   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6847   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6848   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6849   }
6850
6851   SmallVector<int, 8> MaskVec;
6852   for (unsigned i = 0; i != NumElems; i += Scale) {
6853     int StartIdx = -1;
6854     for (unsigned j = 0; j != Scale; ++j) {
6855       int EltIdx = SVOp->getMaskElt(i+j);
6856       if (EltIdx < 0)
6857         continue;
6858       if (StartIdx < 0)
6859         StartIdx = (EltIdx / Scale);
6860       if (EltIdx != (int)(StartIdx*Scale + j))
6861         return SDValue();
6862     }
6863     MaskVec.push_back(StartIdx);
6864   }
6865
6866   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6867   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6868   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6869 }
6870
6871 /// getVZextMovL - Return a zero-extending vector move low node.
6872 ///
6873 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6874                             SDValue SrcOp, SelectionDAG &DAG,
6875                             const X86Subtarget *Subtarget, SDLoc dl) {
6876   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6877     LoadSDNode *LD = nullptr;
6878     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6879       LD = dyn_cast<LoadSDNode>(SrcOp);
6880     if (!LD) {
6881       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6882       // instead.
6883       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6884       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6885           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6886           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6887           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6888         // PR2108
6889         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6890         return DAG.getNode(ISD::BITCAST, dl, VT,
6891                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6892                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6893                                                    OpVT,
6894                                                    SrcOp.getOperand(0)
6895                                                           .getOperand(0))));
6896       }
6897     }
6898   }
6899
6900   return DAG.getNode(ISD::BITCAST, dl, VT,
6901                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6902                                  DAG.getNode(ISD::BITCAST, dl,
6903                                              OpVT, SrcOp)));
6904 }
6905
6906 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6907 /// which could not be matched by any known target speficic shuffle
6908 static SDValue
6909 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6910
6911   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6912   if (NewOp.getNode())
6913     return NewOp;
6914
6915   MVT VT = SVOp->getSimpleValueType(0);
6916
6917   unsigned NumElems = VT.getVectorNumElements();
6918   unsigned NumLaneElems = NumElems / 2;
6919
6920   SDLoc dl(SVOp);
6921   MVT EltVT = VT.getVectorElementType();
6922   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6923   SDValue Output[2];
6924
6925   SmallVector<int, 16> Mask;
6926   for (unsigned l = 0; l < 2; ++l) {
6927     // Build a shuffle mask for the output, discovering on the fly which
6928     // input vectors to use as shuffle operands (recorded in InputUsed).
6929     // If building a suitable shuffle vector proves too hard, then bail
6930     // out with UseBuildVector set.
6931     bool UseBuildVector = false;
6932     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6933     unsigned LaneStart = l * NumLaneElems;
6934     for (unsigned i = 0; i != NumLaneElems; ++i) {
6935       // The mask element.  This indexes into the input.
6936       int Idx = SVOp->getMaskElt(i+LaneStart);
6937       if (Idx < 0) {
6938         // the mask element does not index into any input vector.
6939         Mask.push_back(-1);
6940         continue;
6941       }
6942
6943       // The input vector this mask element indexes into.
6944       int Input = Idx / NumLaneElems;
6945
6946       // Turn the index into an offset from the start of the input vector.
6947       Idx -= Input * NumLaneElems;
6948
6949       // Find or create a shuffle vector operand to hold this input.
6950       unsigned OpNo;
6951       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6952         if (InputUsed[OpNo] == Input)
6953           // This input vector is already an operand.
6954           break;
6955         if (InputUsed[OpNo] < 0) {
6956           // Create a new operand for this input vector.
6957           InputUsed[OpNo] = Input;
6958           break;
6959         }
6960       }
6961
6962       if (OpNo >= array_lengthof(InputUsed)) {
6963         // More than two input vectors used!  Give up on trying to create a
6964         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6965         UseBuildVector = true;
6966         break;
6967       }
6968
6969       // Add the mask index for the new shuffle vector.
6970       Mask.push_back(Idx + OpNo * NumLaneElems);
6971     }
6972
6973     if (UseBuildVector) {
6974       SmallVector<SDValue, 16> SVOps;
6975       for (unsigned i = 0; i != NumLaneElems; ++i) {
6976         // The mask element.  This indexes into the input.
6977         int Idx = SVOp->getMaskElt(i+LaneStart);
6978         if (Idx < 0) {
6979           SVOps.push_back(DAG.getUNDEF(EltVT));
6980           continue;
6981         }
6982
6983         // The input vector this mask element indexes into.
6984         int Input = Idx / NumElems;
6985
6986         // Turn the index into an offset from the start of the input vector.
6987         Idx -= Input * NumElems;
6988
6989         // Extract the vector element by hand.
6990         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6991                                     SVOp->getOperand(Input),
6992                                     DAG.getIntPtrConstant(Idx)));
6993       }
6994
6995       // Construct the output using a BUILD_VECTOR.
6996       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
6997     } else if (InputUsed[0] < 0) {
6998       // No input vectors were used! The result is undefined.
6999       Output[l] = DAG.getUNDEF(NVT);
7000     } else {
7001       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7002                                         (InputUsed[0] % 2) * NumLaneElems,
7003                                         DAG, dl);
7004       // If only one input was used, use an undefined vector for the other.
7005       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7006         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7007                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7008       // At least one input vector was used. Create a new shuffle vector.
7009       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7010     }
7011
7012     Mask.clear();
7013   }
7014
7015   // Concatenate the result back
7016   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7017 }
7018
7019 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7020 /// 4 elements, and match them with several different shuffle types.
7021 static SDValue
7022 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7023   SDValue V1 = SVOp->getOperand(0);
7024   SDValue V2 = SVOp->getOperand(1);
7025   SDLoc dl(SVOp);
7026   MVT VT = SVOp->getSimpleValueType(0);
7027
7028   assert(VT.is128BitVector() && "Unsupported vector size");
7029
7030   std::pair<int, int> Locs[4];
7031   int Mask1[] = { -1, -1, -1, -1 };
7032   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7033
7034   unsigned NumHi = 0;
7035   unsigned NumLo = 0;
7036   for (unsigned i = 0; i != 4; ++i) {
7037     int Idx = PermMask[i];
7038     if (Idx < 0) {
7039       Locs[i] = std::make_pair(-1, -1);
7040     } else {
7041       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7042       if (Idx < 4) {
7043         Locs[i] = std::make_pair(0, NumLo);
7044         Mask1[NumLo] = Idx;
7045         NumLo++;
7046       } else {
7047         Locs[i] = std::make_pair(1, NumHi);
7048         if (2+NumHi < 4)
7049           Mask1[2+NumHi] = Idx;
7050         NumHi++;
7051       }
7052     }
7053   }
7054
7055   if (NumLo <= 2 && NumHi <= 2) {
7056     // If no more than two elements come from either vector. This can be
7057     // implemented with two shuffles. First shuffle gather the elements.
7058     // The second shuffle, which takes the first shuffle as both of its
7059     // vector operands, put the elements into the right order.
7060     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7061
7062     int Mask2[] = { -1, -1, -1, -1 };
7063
7064     for (unsigned i = 0; i != 4; ++i)
7065       if (Locs[i].first != -1) {
7066         unsigned Idx = (i < 2) ? 0 : 4;
7067         Idx += Locs[i].first * 2 + Locs[i].second;
7068         Mask2[i] = Idx;
7069       }
7070
7071     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7072   }
7073
7074   if (NumLo == 3 || NumHi == 3) {
7075     // Otherwise, we must have three elements from one vector, call it X, and
7076     // one element from the other, call it Y.  First, use a shufps to build an
7077     // intermediate vector with the one element from Y and the element from X
7078     // that will be in the same half in the final destination (the indexes don't
7079     // matter). Then, use a shufps to build the final vector, taking the half
7080     // containing the element from Y from the intermediate, and the other half
7081     // from X.
7082     if (NumHi == 3) {
7083       // Normalize it so the 3 elements come from V1.
7084       CommuteVectorShuffleMask(PermMask, 4);
7085       std::swap(V1, V2);
7086     }
7087
7088     // Find the element from V2.
7089     unsigned HiIndex;
7090     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7091       int Val = PermMask[HiIndex];
7092       if (Val < 0)
7093         continue;
7094       if (Val >= 4)
7095         break;
7096     }
7097
7098     Mask1[0] = PermMask[HiIndex];
7099     Mask1[1] = -1;
7100     Mask1[2] = PermMask[HiIndex^1];
7101     Mask1[3] = -1;
7102     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7103
7104     if (HiIndex >= 2) {
7105       Mask1[0] = PermMask[0];
7106       Mask1[1] = PermMask[1];
7107       Mask1[2] = HiIndex & 1 ? 6 : 4;
7108       Mask1[3] = HiIndex & 1 ? 4 : 6;
7109       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7110     }
7111
7112     Mask1[0] = HiIndex & 1 ? 2 : 0;
7113     Mask1[1] = HiIndex & 1 ? 0 : 2;
7114     Mask1[2] = PermMask[2];
7115     Mask1[3] = PermMask[3];
7116     if (Mask1[2] >= 0)
7117       Mask1[2] += 4;
7118     if (Mask1[3] >= 0)
7119       Mask1[3] += 4;
7120     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7121   }
7122
7123   // Break it into (shuffle shuffle_hi, shuffle_lo).
7124   int LoMask[] = { -1, -1, -1, -1 };
7125   int HiMask[] = { -1, -1, -1, -1 };
7126
7127   int *MaskPtr = LoMask;
7128   unsigned MaskIdx = 0;
7129   unsigned LoIdx = 0;
7130   unsigned HiIdx = 2;
7131   for (unsigned i = 0; i != 4; ++i) {
7132     if (i == 2) {
7133       MaskPtr = HiMask;
7134       MaskIdx = 1;
7135       LoIdx = 0;
7136       HiIdx = 2;
7137     }
7138     int Idx = PermMask[i];
7139     if (Idx < 0) {
7140       Locs[i] = std::make_pair(-1, -1);
7141     } else if (Idx < 4) {
7142       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7143       MaskPtr[LoIdx] = Idx;
7144       LoIdx++;
7145     } else {
7146       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7147       MaskPtr[HiIdx] = Idx;
7148       HiIdx++;
7149     }
7150   }
7151
7152   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7153   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7154   int MaskOps[] = { -1, -1, -1, -1 };
7155   for (unsigned i = 0; i != 4; ++i)
7156     if (Locs[i].first != -1)
7157       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7158   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7159 }
7160
7161 static bool MayFoldVectorLoad(SDValue V) {
7162   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7163     V = V.getOperand(0);
7164
7165   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7166     V = V.getOperand(0);
7167   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7168       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7169     // BUILD_VECTOR (load), undef
7170     V = V.getOperand(0);
7171
7172   return MayFoldLoad(V);
7173 }
7174
7175 static
7176 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7177   MVT VT = Op.getSimpleValueType();
7178
7179   // Canonizalize to v2f64.
7180   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7181   return DAG.getNode(ISD::BITCAST, dl, VT,
7182                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7183                                           V1, DAG));
7184 }
7185
7186 static
7187 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7188                         bool HasSSE2) {
7189   SDValue V1 = Op.getOperand(0);
7190   SDValue V2 = Op.getOperand(1);
7191   MVT VT = Op.getSimpleValueType();
7192
7193   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7194
7195   if (HasSSE2 && VT == MVT::v2f64)
7196     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7197
7198   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7199   return DAG.getNode(ISD::BITCAST, dl, VT,
7200                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7201                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7202                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7203 }
7204
7205 static
7206 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7207   SDValue V1 = Op.getOperand(0);
7208   SDValue V2 = Op.getOperand(1);
7209   MVT VT = Op.getSimpleValueType();
7210
7211   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7212          "unsupported shuffle type");
7213
7214   if (V2.getOpcode() == ISD::UNDEF)
7215     V2 = V1;
7216
7217   // v4i32 or v4f32
7218   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7219 }
7220
7221 static
7222 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7223   SDValue V1 = Op.getOperand(0);
7224   SDValue V2 = Op.getOperand(1);
7225   MVT VT = Op.getSimpleValueType();
7226   unsigned NumElems = VT.getVectorNumElements();
7227
7228   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7229   // operand of these instructions is only memory, so check if there's a
7230   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7231   // same masks.
7232   bool CanFoldLoad = false;
7233
7234   // Trivial case, when V2 comes from a load.
7235   if (MayFoldVectorLoad(V2))
7236     CanFoldLoad = true;
7237
7238   // When V1 is a load, it can be folded later into a store in isel, example:
7239   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7240   //    turns into:
7241   //  (MOVLPSmr addr:$src1, VR128:$src2)
7242   // So, recognize this potential and also use MOVLPS or MOVLPD
7243   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7244     CanFoldLoad = true;
7245
7246   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7247   if (CanFoldLoad) {
7248     if (HasSSE2 && NumElems == 2)
7249       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7250
7251     if (NumElems == 4)
7252       // If we don't care about the second element, proceed to use movss.
7253       if (SVOp->getMaskElt(1) != -1)
7254         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7255   }
7256
7257   // movl and movlp will both match v2i64, but v2i64 is never matched by
7258   // movl earlier because we make it strict to avoid messing with the movlp load
7259   // folding logic (see the code above getMOVLP call). Match it here then,
7260   // this is horrible, but will stay like this until we move all shuffle
7261   // matching to x86 specific nodes. Note that for the 1st condition all
7262   // types are matched with movsd.
7263   if (HasSSE2) {
7264     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7265     // as to remove this logic from here, as much as possible
7266     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7267       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7268     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7269   }
7270
7271   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7272
7273   // Invert the operand order and use SHUFPS to match it.
7274   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7275                               getShuffleSHUFImmediate(SVOp), DAG);
7276 }
7277
7278 // It is only safe to call this function if isINSERTPSMask is true for
7279 // this shufflevector mask.
7280 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7281                            SelectionDAG &DAG) {
7282   // Generate an insertps instruction when inserting an f32 from memory onto a
7283   // v4f32 or when copying a member from one v4f32 to another.
7284   // We also use it for transferring i32 from one register to another,
7285   // since it simply copies the same bits.
7286   // If we're transfering an i32 from memory to a specific element in a
7287   // register, we output a generic DAG that will match the PINSRD
7288   // instruction.
7289   // TODO: Optimize for AVX cases too (VINSERTPS)
7290   MVT VT = SVOp->getSimpleValueType(0);
7291   MVT EVT = VT.getVectorElementType();
7292   SDValue V1 = SVOp->getOperand(0);
7293   SDValue V2 = SVOp->getOperand(1);
7294   auto Mask = SVOp->getMask();
7295   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7296          "unsupported vector type for insertps/pinsrd");
7297
7298   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7299                              [](const int &i) { return i < 4; });
7300
7301   SDValue From;
7302   SDValue To;
7303   unsigned DestIndex;
7304   if (FromV1 == 1) {
7305     From = V1;
7306     To = V2;
7307     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7308                              [](const int &i) { return i < 4; }) -
7309                 Mask.begin();
7310   } else {
7311     From = V2;
7312     To = V1;
7313     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7314                              [](const int &i) { return i >= 4; }) -
7315                 Mask.begin();
7316   }
7317
7318   if (MayFoldLoad(From)) {
7319     // Trivial case, when From comes from a load and is only used by the
7320     // shuffle. Make it use insertps from the vector that we need from that
7321     // load.
7322     SDValue Addr = From.getOperand(1);
7323     SDValue NewAddr =
7324         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7325                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7326                                     Addr.getSimpleValueType()));
7327
7328     LoadSDNode *Load = cast<LoadSDNode>(From);
7329     SDValue NewLoad =
7330         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7331                     DAG.getMachineFunction().getMachineMemOperand(
7332                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7333
7334     if (EVT == MVT::f32) {
7335       // Create this as a scalar to vector to match the instruction pattern.
7336       SDValue LoadScalarToVector =
7337           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7338       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7339       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7340                          InsertpsMask);
7341     } else { // EVT == MVT::i32
7342       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7343       // instruction, to match the PINSRD instruction, which loads an i32 to a
7344       // certain vector element.
7345       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7346                          DAG.getConstant(DestIndex, MVT::i32));
7347     }
7348   }
7349
7350   // Vector-element-to-vector
7351   unsigned SrcIndex = Mask[DestIndex] % 4;
7352   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7353   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7354 }
7355
7356 // Reduce a vector shuffle to zext.
7357 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7358                                     SelectionDAG &DAG) {
7359   // PMOVZX is only available from SSE41.
7360   if (!Subtarget->hasSSE41())
7361     return SDValue();
7362
7363   MVT VT = Op.getSimpleValueType();
7364
7365   // Only AVX2 support 256-bit vector integer extending.
7366   if (!Subtarget->hasInt256() && VT.is256BitVector())
7367     return SDValue();
7368
7369   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7370   SDLoc DL(Op);
7371   SDValue V1 = Op.getOperand(0);
7372   SDValue V2 = Op.getOperand(1);
7373   unsigned NumElems = VT.getVectorNumElements();
7374
7375   // Extending is an unary operation and the element type of the source vector
7376   // won't be equal to or larger than i64.
7377   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7378       VT.getVectorElementType() == MVT::i64)
7379     return SDValue();
7380
7381   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7382   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7383   while ((1U << Shift) < NumElems) {
7384     if (SVOp->getMaskElt(1U << Shift) == 1)
7385       break;
7386     Shift += 1;
7387     // The maximal ratio is 8, i.e. from i8 to i64.
7388     if (Shift > 3)
7389       return SDValue();
7390   }
7391
7392   // Check the shuffle mask.
7393   unsigned Mask = (1U << Shift) - 1;
7394   for (unsigned i = 0; i != NumElems; ++i) {
7395     int EltIdx = SVOp->getMaskElt(i);
7396     if ((i & Mask) != 0 && EltIdx != -1)
7397       return SDValue();
7398     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7399       return SDValue();
7400   }
7401
7402   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7403   MVT NeVT = MVT::getIntegerVT(NBits);
7404   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7405
7406   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7407     return SDValue();
7408
7409   // Simplify the operand as it's prepared to be fed into shuffle.
7410   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7411   if (V1.getOpcode() == ISD::BITCAST &&
7412       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7413       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7414       V1.getOperand(0).getOperand(0)
7415         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7416     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7417     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7418     ConstantSDNode *CIdx =
7419       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7420     // If it's foldable, i.e. normal load with single use, we will let code
7421     // selection to fold it. Otherwise, we will short the conversion sequence.
7422     if (CIdx && CIdx->getZExtValue() == 0 &&
7423         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7424       MVT FullVT = V.getSimpleValueType();
7425       MVT V1VT = V1.getSimpleValueType();
7426       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7427         // The "ext_vec_elt" node is wider than the result node.
7428         // In this case we should extract subvector from V.
7429         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7430         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7431         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7432                                         FullVT.getVectorNumElements()/Ratio);
7433         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7434                         DAG.getIntPtrConstant(0));
7435       }
7436       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7437     }
7438   }
7439
7440   return DAG.getNode(ISD::BITCAST, DL, VT,
7441                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7442 }
7443
7444 static SDValue
7445 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7446                        SelectionDAG &DAG) {
7447   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7448   MVT VT = Op.getSimpleValueType();
7449   SDLoc dl(Op);
7450   SDValue V1 = Op.getOperand(0);
7451   SDValue V2 = Op.getOperand(1);
7452
7453   if (isZeroShuffle(SVOp))
7454     return getZeroVector(VT, Subtarget, DAG, dl);
7455
7456   // Handle splat operations
7457   if (SVOp->isSplat()) {
7458     // Use vbroadcast whenever the splat comes from a foldable load
7459     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7460     if (Broadcast.getNode())
7461       return Broadcast;
7462   }
7463
7464   // Check integer expanding shuffles.
7465   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7466   if (NewOp.getNode())
7467     return NewOp;
7468
7469   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7470   // do it!
7471   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7472       VT == MVT::v16i16 || VT == MVT::v32i8) {
7473     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7474     if (NewOp.getNode())
7475       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7476   } else if ((VT == MVT::v4i32 ||
7477              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7478     // FIXME: Figure out a cleaner way to do this.
7479     // Try to make use of movq to zero out the top part.
7480     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7481       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7482       if (NewOp.getNode()) {
7483         MVT NewVT = NewOp.getSimpleValueType();
7484         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7485                                NewVT, true, false))
7486           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7487                               DAG, Subtarget, dl);
7488       }
7489     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7490       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7491       if (NewOp.getNode()) {
7492         MVT NewVT = NewOp.getSimpleValueType();
7493         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7494           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7495                               DAG, Subtarget, dl);
7496       }
7497     }
7498   }
7499   return SDValue();
7500 }
7501
7502 SDValue
7503 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7504   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7505   SDValue V1 = Op.getOperand(0);
7506   SDValue V2 = Op.getOperand(1);
7507   MVT VT = Op.getSimpleValueType();
7508   SDLoc dl(Op);
7509   unsigned NumElems = VT.getVectorNumElements();
7510   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7511   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7512   bool V1IsSplat = false;
7513   bool V2IsSplat = false;
7514   bool HasSSE2 = Subtarget->hasSSE2();
7515   bool HasFp256    = Subtarget->hasFp256();
7516   bool HasInt256   = Subtarget->hasInt256();
7517   MachineFunction &MF = DAG.getMachineFunction();
7518   bool OptForSize = MF.getFunction()->getAttributes().
7519     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7520
7521   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7522
7523   if (V1IsUndef && V2IsUndef)
7524     return DAG.getUNDEF(VT);
7525
7526   // When we create a shuffle node we put the UNDEF node to second operand,
7527   // but in some cases the first operand may be transformed to UNDEF.
7528   // In this case we should just commute the node.
7529   if (V1IsUndef)
7530     return CommuteVectorShuffle(SVOp, DAG);
7531
7532   // Vector shuffle lowering takes 3 steps:
7533   //
7534   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7535   //    narrowing and commutation of operands should be handled.
7536   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7537   //    shuffle nodes.
7538   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7539   //    so the shuffle can be broken into other shuffles and the legalizer can
7540   //    try the lowering again.
7541   //
7542   // The general idea is that no vector_shuffle operation should be left to
7543   // be matched during isel, all of them must be converted to a target specific
7544   // node here.
7545
7546   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7547   // narrowing and commutation of operands should be handled. The actual code
7548   // doesn't include all of those, work in progress...
7549   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7550   if (NewOp.getNode())
7551     return NewOp;
7552
7553   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7554
7555   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7556   // unpckh_undef). Only use pshufd if speed is more important than size.
7557   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7558     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7559   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7560     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7561
7562   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7563       V2IsUndef && MayFoldVectorLoad(V1))
7564     return getMOVDDup(Op, dl, V1, DAG);
7565
7566   if (isMOVHLPS_v_undef_Mask(M, VT))
7567     return getMOVHighToLow(Op, dl, DAG);
7568
7569   // Use to match splats
7570   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7571       (VT == MVT::v2f64 || VT == MVT::v2i64))
7572     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7573
7574   if (isPSHUFDMask(M, VT)) {
7575     // The actual implementation will match the mask in the if above and then
7576     // during isel it can match several different instructions, not only pshufd
7577     // as its name says, sad but true, emulate the behavior for now...
7578     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7579       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7580
7581     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7582
7583     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7584       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7585
7586     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7587       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7588                                   DAG);
7589
7590     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7591                                 TargetMask, DAG);
7592   }
7593
7594   if (isPALIGNRMask(M, VT, Subtarget))
7595     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7596                                 getShufflePALIGNRImmediate(SVOp),
7597                                 DAG);
7598
7599   // Check if this can be converted into a logical shift.
7600   bool isLeft = false;
7601   unsigned ShAmt = 0;
7602   SDValue ShVal;
7603   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7604   if (isShift && ShVal.hasOneUse()) {
7605     // If the shifted value has multiple uses, it may be cheaper to use
7606     // v_set0 + movlhps or movhlps, etc.
7607     MVT EltVT = VT.getVectorElementType();
7608     ShAmt *= EltVT.getSizeInBits();
7609     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7610   }
7611
7612   if (isMOVLMask(M, VT)) {
7613     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7614       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7615     if (!isMOVLPMask(M, VT)) {
7616       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7617         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7618
7619       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7620         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7621     }
7622   }
7623
7624   // FIXME: fold these into legal mask.
7625   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7626     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7627
7628   if (isMOVHLPSMask(M, VT))
7629     return getMOVHighToLow(Op, dl, DAG);
7630
7631   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7632     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7633
7634   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7635     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7636
7637   if (isMOVLPMask(M, VT))
7638     return getMOVLP(Op, dl, DAG, HasSSE2);
7639
7640   if (ShouldXformToMOVHLPS(M, VT) ||
7641       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7642     return CommuteVectorShuffle(SVOp, DAG);
7643
7644   if (isShift) {
7645     // No better options. Use a vshldq / vsrldq.
7646     MVT EltVT = VT.getVectorElementType();
7647     ShAmt *= EltVT.getSizeInBits();
7648     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7649   }
7650
7651   bool Commuted = false;
7652   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7653   // 1,1,1,1 -> v8i16 though.
7654   V1IsSplat = isSplatVector(V1.getNode());
7655   V2IsSplat = isSplatVector(V2.getNode());
7656
7657   // Canonicalize the splat or undef, if present, to be on the RHS.
7658   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7659     CommuteVectorShuffleMask(M, NumElems);
7660     std::swap(V1, V2);
7661     std::swap(V1IsSplat, V2IsSplat);
7662     Commuted = true;
7663   }
7664
7665   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7666     // Shuffling low element of v1 into undef, just return v1.
7667     if (V2IsUndef)
7668       return V1;
7669     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7670     // the instruction selector will not match, so get a canonical MOVL with
7671     // swapped operands to undo the commute.
7672     return getMOVL(DAG, dl, VT, V2, V1);
7673   }
7674
7675   if (isUNPCKLMask(M, VT, HasInt256))
7676     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7677
7678   if (isUNPCKHMask(M, VT, HasInt256))
7679     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7680
7681   if (V2IsSplat) {
7682     // Normalize mask so all entries that point to V2 points to its first
7683     // element then try to match unpck{h|l} again. If match, return a
7684     // new vector_shuffle with the corrected mask.p
7685     SmallVector<int, 8> NewMask(M.begin(), M.end());
7686     NormalizeMask(NewMask, NumElems);
7687     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7688       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7689     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7690       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7691   }
7692
7693   if (Commuted) {
7694     // Commute is back and try unpck* again.
7695     // FIXME: this seems wrong.
7696     CommuteVectorShuffleMask(M, NumElems);
7697     std::swap(V1, V2);
7698     std::swap(V1IsSplat, V2IsSplat);
7699
7700     if (isUNPCKLMask(M, VT, HasInt256))
7701       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7702
7703     if (isUNPCKHMask(M, VT, HasInt256))
7704       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7705   }
7706
7707   // Normalize the node to match x86 shuffle ops if needed
7708   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7709     return CommuteVectorShuffle(SVOp, DAG);
7710
7711   // The checks below are all present in isShuffleMaskLegal, but they are
7712   // inlined here right now to enable us to directly emit target specific
7713   // nodes, and remove one by one until they don't return Op anymore.
7714
7715   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7716       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7717     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7718       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7719   }
7720
7721   if (isPSHUFHWMask(M, VT, HasInt256))
7722     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7723                                 getShufflePSHUFHWImmediate(SVOp),
7724                                 DAG);
7725
7726   if (isPSHUFLWMask(M, VT, HasInt256))
7727     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7728                                 getShufflePSHUFLWImmediate(SVOp),
7729                                 DAG);
7730
7731   if (isSHUFPMask(M, VT))
7732     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7733                                 getShuffleSHUFImmediate(SVOp), DAG);
7734
7735   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7736     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7737   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7738     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7739
7740   //===--------------------------------------------------------------------===//
7741   // Generate target specific nodes for 128 or 256-bit shuffles only
7742   // supported in the AVX instruction set.
7743   //
7744
7745   // Handle VMOVDDUPY permutations
7746   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7747     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7748
7749   // Handle VPERMILPS/D* permutations
7750   if (isVPERMILPMask(M, VT)) {
7751     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7752       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7753                                   getShuffleSHUFImmediate(SVOp), DAG);
7754     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7755                                 getShuffleSHUFImmediate(SVOp), DAG);
7756   }
7757
7758   // Handle VPERM2F128/VPERM2I128 permutations
7759   if (isVPERM2X128Mask(M, VT, HasFp256))
7760     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7761                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7762
7763   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7764   if (BlendOp.getNode())
7765     return BlendOp;
7766
7767   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7768     return getINSERTPS(SVOp, dl, DAG);
7769
7770   unsigned Imm8;
7771   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7772     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7773
7774   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7775       VT.is512BitVector()) {
7776     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7777     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7778     SmallVector<SDValue, 16> permclMask;
7779     for (unsigned i = 0; i != NumElems; ++i) {
7780       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7781     }
7782
7783     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7784     if (V2IsUndef)
7785       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7786       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7787                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7788     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7789                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7790   }
7791
7792   //===--------------------------------------------------------------------===//
7793   // Since no target specific shuffle was selected for this generic one,
7794   // lower it into other known shuffles. FIXME: this isn't true yet, but
7795   // this is the plan.
7796   //
7797
7798   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7799   if (VT == MVT::v8i16) {
7800     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7801     if (NewOp.getNode())
7802       return NewOp;
7803   }
7804
7805   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7806     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7807     if (NewOp.getNode())
7808       return NewOp;
7809   }
7810
7811   if (VT == MVT::v16i8) {
7812     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7813     if (NewOp.getNode())
7814       return NewOp;
7815   }
7816
7817   if (VT == MVT::v32i8) {
7818     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7819     if (NewOp.getNode())
7820       return NewOp;
7821   }
7822
7823   // Handle all 128-bit wide vectors with 4 elements, and match them with
7824   // several different shuffle types.
7825   if (NumElems == 4 && VT.is128BitVector())
7826     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7827
7828   // Handle general 256-bit shuffles
7829   if (VT.is256BitVector())
7830     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7831
7832   return SDValue();
7833 }
7834
7835 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7836   MVT VT = Op.getSimpleValueType();
7837   SDLoc dl(Op);
7838
7839   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7840     return SDValue();
7841
7842   if (VT.getSizeInBits() == 8) {
7843     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7844                                   Op.getOperand(0), Op.getOperand(1));
7845     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7846                                   DAG.getValueType(VT));
7847     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7848   }
7849
7850   if (VT.getSizeInBits() == 16) {
7851     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7852     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7853     if (Idx == 0)
7854       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7855                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7856                                      DAG.getNode(ISD::BITCAST, dl,
7857                                                  MVT::v4i32,
7858                                                  Op.getOperand(0)),
7859                                      Op.getOperand(1)));
7860     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7861                                   Op.getOperand(0), Op.getOperand(1));
7862     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7863                                   DAG.getValueType(VT));
7864     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7865   }
7866
7867   if (VT == MVT::f32) {
7868     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7869     // the result back to FR32 register. It's only worth matching if the
7870     // result has a single use which is a store or a bitcast to i32.  And in
7871     // the case of a store, it's not worth it if the index is a constant 0,
7872     // because a MOVSSmr can be used instead, which is smaller and faster.
7873     if (!Op.hasOneUse())
7874       return SDValue();
7875     SDNode *User = *Op.getNode()->use_begin();
7876     if ((User->getOpcode() != ISD::STORE ||
7877          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7878           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7879         (User->getOpcode() != ISD::BITCAST ||
7880          User->getValueType(0) != MVT::i32))
7881       return SDValue();
7882     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7883                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7884                                               Op.getOperand(0)),
7885                                               Op.getOperand(1));
7886     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7887   }
7888
7889   if (VT == MVT::i32 || VT == MVT::i64) {
7890     // ExtractPS/pextrq works with constant index.
7891     if (isa<ConstantSDNode>(Op.getOperand(1)))
7892       return Op;
7893   }
7894   return SDValue();
7895 }
7896
7897 /// Extract one bit from mask vector, like v16i1 or v8i1.
7898 /// AVX-512 feature.
7899 SDValue
7900 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7901   SDValue Vec = Op.getOperand(0);
7902   SDLoc dl(Vec);
7903   MVT VecVT = Vec.getSimpleValueType();
7904   SDValue Idx = Op.getOperand(1);
7905   MVT EltVT = Op.getSimpleValueType();
7906
7907   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7908
7909   // variable index can't be handled in mask registers,
7910   // extend vector to VR512
7911   if (!isa<ConstantSDNode>(Idx)) {
7912     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7913     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7914     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7915                               ExtVT.getVectorElementType(), Ext, Idx);
7916     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7917   }
7918
7919   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7920   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7921   unsigned MaxSift = rc->getSize()*8 - 1;
7922   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7923                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7924   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7925                     DAG.getConstant(MaxSift, MVT::i8));
7926   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7927                        DAG.getIntPtrConstant(0));
7928 }
7929
7930 SDValue
7931 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7932                                            SelectionDAG &DAG) const {
7933   SDLoc dl(Op);
7934   SDValue Vec = Op.getOperand(0);
7935   MVT VecVT = Vec.getSimpleValueType();
7936   SDValue Idx = Op.getOperand(1);
7937
7938   if (Op.getSimpleValueType() == MVT::i1)
7939     return ExtractBitFromMaskVector(Op, DAG);
7940
7941   if (!isa<ConstantSDNode>(Idx)) {
7942     if (VecVT.is512BitVector() ||
7943         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7944          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7945
7946       MVT MaskEltVT =
7947         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7948       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7949                                     MaskEltVT.getSizeInBits());
7950
7951       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7952       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7953                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7954                                 Idx, DAG.getConstant(0, getPointerTy()));
7955       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7956       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7957                         Perm, DAG.getConstant(0, getPointerTy()));
7958     }
7959     return SDValue();
7960   }
7961
7962   // If this is a 256-bit vector result, first extract the 128-bit vector and
7963   // then extract the element from the 128-bit vector.
7964   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7965
7966     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7967     // Get the 128-bit vector.
7968     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7969     MVT EltVT = VecVT.getVectorElementType();
7970
7971     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7972
7973     //if (IdxVal >= NumElems/2)
7974     //  IdxVal -= NumElems/2;
7975     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7976     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7977                        DAG.getConstant(IdxVal, MVT::i32));
7978   }
7979
7980   assert(VecVT.is128BitVector() && "Unexpected vector length");
7981
7982   if (Subtarget->hasSSE41()) {
7983     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7984     if (Res.getNode())
7985       return Res;
7986   }
7987
7988   MVT VT = Op.getSimpleValueType();
7989   // TODO: handle v16i8.
7990   if (VT.getSizeInBits() == 16) {
7991     SDValue Vec = Op.getOperand(0);
7992     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7993     if (Idx == 0)
7994       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7995                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7996                                      DAG.getNode(ISD::BITCAST, dl,
7997                                                  MVT::v4i32, Vec),
7998                                      Op.getOperand(1)));
7999     // Transform it so it match pextrw which produces a 32-bit result.
8000     MVT EltVT = MVT::i32;
8001     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8002                                   Op.getOperand(0), Op.getOperand(1));
8003     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8004                                   DAG.getValueType(VT));
8005     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8006   }
8007
8008   if (VT.getSizeInBits() == 32) {
8009     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8010     if (Idx == 0)
8011       return Op;
8012
8013     // SHUFPS the element to the lowest double word, then movss.
8014     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8015     MVT VVT = Op.getOperand(0).getSimpleValueType();
8016     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8017                                        DAG.getUNDEF(VVT), Mask);
8018     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8019                        DAG.getIntPtrConstant(0));
8020   }
8021
8022   if (VT.getSizeInBits() == 64) {
8023     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8024     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8025     //        to match extract_elt for f64.
8026     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8027     if (Idx == 0)
8028       return Op;
8029
8030     // UNPCKHPD the element to the lowest double word, then movsd.
8031     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8032     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8033     int Mask[2] = { 1, -1 };
8034     MVT VVT = Op.getOperand(0).getSimpleValueType();
8035     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8036                                        DAG.getUNDEF(VVT), Mask);
8037     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8038                        DAG.getIntPtrConstant(0));
8039   }
8040
8041   return SDValue();
8042 }
8043
8044 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8045   MVT VT = Op.getSimpleValueType();
8046   MVT EltVT = VT.getVectorElementType();
8047   SDLoc dl(Op);
8048
8049   SDValue N0 = Op.getOperand(0);
8050   SDValue N1 = Op.getOperand(1);
8051   SDValue N2 = Op.getOperand(2);
8052
8053   if (!VT.is128BitVector())
8054     return SDValue();
8055
8056   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8057       isa<ConstantSDNode>(N2)) {
8058     unsigned Opc;
8059     if (VT == MVT::v8i16)
8060       Opc = X86ISD::PINSRW;
8061     else if (VT == MVT::v16i8)
8062       Opc = X86ISD::PINSRB;
8063     else
8064       Opc = X86ISD::PINSRB;
8065
8066     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8067     // argument.
8068     if (N1.getValueType() != MVT::i32)
8069       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8070     if (N2.getValueType() != MVT::i32)
8071       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8072     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8073   }
8074
8075   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8076     // Bits [7:6] of the constant are the source select.  This will always be
8077     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8078     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8079     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8080     // Bits [5:4] of the constant are the destination select.  This is the
8081     //  value of the incoming immediate.
8082     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8083     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8084     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8085     // Create this as a scalar to vector..
8086     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8087     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8088   }
8089
8090   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8091     // PINSR* works with constant index.
8092     return Op;
8093   }
8094   return SDValue();
8095 }
8096
8097 /// Insert one bit to mask vector, like v16i1 or v8i1.
8098 /// AVX-512 feature.
8099 SDValue 
8100 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8101   SDLoc dl(Op);
8102   SDValue Vec = Op.getOperand(0);
8103   SDValue Elt = Op.getOperand(1);
8104   SDValue Idx = Op.getOperand(2);
8105   MVT VecVT = Vec.getSimpleValueType();
8106
8107   if (!isa<ConstantSDNode>(Idx)) {
8108     // Non constant index. Extend source and destination,
8109     // insert element and then truncate the result.
8110     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8111     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8112     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8113       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8114       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8115     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8116   }
8117
8118   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8119   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8120   if (Vec.getOpcode() == ISD::UNDEF)
8121     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8122                        DAG.getConstant(IdxVal, MVT::i8));
8123   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8124   unsigned MaxSift = rc->getSize()*8 - 1;
8125   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8126                     DAG.getConstant(MaxSift, MVT::i8));
8127   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8128                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8129   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8130 }
8131 SDValue
8132 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8133   MVT VT = Op.getSimpleValueType();
8134   MVT EltVT = VT.getVectorElementType();
8135   
8136   if (EltVT == MVT::i1)
8137     return InsertBitToMaskVector(Op, DAG);
8138
8139   SDLoc dl(Op);
8140   SDValue N0 = Op.getOperand(0);
8141   SDValue N1 = Op.getOperand(1);
8142   SDValue N2 = Op.getOperand(2);
8143
8144   // If this is a 256-bit vector result, first extract the 128-bit vector,
8145   // insert the element into the extracted half and then place it back.
8146   if (VT.is256BitVector() || VT.is512BitVector()) {
8147     if (!isa<ConstantSDNode>(N2))
8148       return SDValue();
8149
8150     // Get the desired 128-bit vector half.
8151     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8152     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8153
8154     // Insert the element into the desired half.
8155     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8156     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8157
8158     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8159                     DAG.getConstant(IdxIn128, MVT::i32));
8160
8161     // Insert the changed part back to the 256-bit vector
8162     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8163   }
8164
8165   if (Subtarget->hasSSE41())
8166     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8167
8168   if (EltVT == MVT::i8)
8169     return SDValue();
8170
8171   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8172     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8173     // as its second argument.
8174     if (N1.getValueType() != MVT::i32)
8175       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8176     if (N2.getValueType() != MVT::i32)
8177       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8178     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8179   }
8180   return SDValue();
8181 }
8182
8183 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8184   SDLoc dl(Op);
8185   MVT OpVT = Op.getSimpleValueType();
8186
8187   // If this is a 256-bit vector result, first insert into a 128-bit
8188   // vector and then insert into the 256-bit vector.
8189   if (!OpVT.is128BitVector()) {
8190     // Insert into a 128-bit vector.
8191     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8192     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8193                                  OpVT.getVectorNumElements() / SizeFactor);
8194
8195     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8196
8197     // Insert the 128-bit vector.
8198     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8199   }
8200
8201   if (OpVT == MVT::v1i64 &&
8202       Op.getOperand(0).getValueType() == MVT::i64)
8203     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8204
8205   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8206   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8207   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8208                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8209 }
8210
8211 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8212 // a simple subregister reference or explicit instructions to grab
8213 // upper bits of a vector.
8214 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8215                                       SelectionDAG &DAG) {
8216   SDLoc dl(Op);
8217   SDValue In =  Op.getOperand(0);
8218   SDValue Idx = Op.getOperand(1);
8219   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8220   MVT ResVT   = Op.getSimpleValueType();
8221   MVT InVT    = In.getSimpleValueType();
8222
8223   if (Subtarget->hasFp256()) {
8224     if (ResVT.is128BitVector() &&
8225         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8226         isa<ConstantSDNode>(Idx)) {
8227       return Extract128BitVector(In, IdxVal, DAG, dl);
8228     }
8229     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8230         isa<ConstantSDNode>(Idx)) {
8231       return Extract256BitVector(In, IdxVal, DAG, dl);
8232     }
8233   }
8234   return SDValue();
8235 }
8236
8237 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8238 // simple superregister reference or explicit instructions to insert
8239 // the upper bits of a vector.
8240 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8241                                      SelectionDAG &DAG) {
8242   if (Subtarget->hasFp256()) {
8243     SDLoc dl(Op.getNode());
8244     SDValue Vec = Op.getNode()->getOperand(0);
8245     SDValue SubVec = Op.getNode()->getOperand(1);
8246     SDValue Idx = Op.getNode()->getOperand(2);
8247
8248     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8249          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8250         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8251         isa<ConstantSDNode>(Idx)) {
8252       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8253       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8254     }
8255
8256     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8257         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8258         isa<ConstantSDNode>(Idx)) {
8259       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8260       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8261     }
8262   }
8263   return SDValue();
8264 }
8265
8266 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8267 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8268 // one of the above mentioned nodes. It has to be wrapped because otherwise
8269 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8270 // be used to form addressing mode. These wrapped nodes will be selected
8271 // into MOV32ri.
8272 SDValue
8273 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8274   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8275
8276   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8277   // global base reg.
8278   unsigned char OpFlag = 0;
8279   unsigned WrapperKind = X86ISD::Wrapper;
8280   CodeModel::Model M = getTargetMachine().getCodeModel();
8281
8282   if (Subtarget->isPICStyleRIPRel() &&
8283       (M == CodeModel::Small || M == CodeModel::Kernel))
8284     WrapperKind = X86ISD::WrapperRIP;
8285   else if (Subtarget->isPICStyleGOT())
8286     OpFlag = X86II::MO_GOTOFF;
8287   else if (Subtarget->isPICStyleStubPIC())
8288     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8289
8290   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8291                                              CP->getAlignment(),
8292                                              CP->getOffset(), OpFlag);
8293   SDLoc DL(CP);
8294   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8295   // With PIC, the address is actually $g + Offset.
8296   if (OpFlag) {
8297     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8298                          DAG.getNode(X86ISD::GlobalBaseReg,
8299                                      SDLoc(), getPointerTy()),
8300                          Result);
8301   }
8302
8303   return Result;
8304 }
8305
8306 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8307   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8308
8309   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8310   // global base reg.
8311   unsigned char OpFlag = 0;
8312   unsigned WrapperKind = X86ISD::Wrapper;
8313   CodeModel::Model M = getTargetMachine().getCodeModel();
8314
8315   if (Subtarget->isPICStyleRIPRel() &&
8316       (M == CodeModel::Small || M == CodeModel::Kernel))
8317     WrapperKind = X86ISD::WrapperRIP;
8318   else if (Subtarget->isPICStyleGOT())
8319     OpFlag = X86II::MO_GOTOFF;
8320   else if (Subtarget->isPICStyleStubPIC())
8321     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8322
8323   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8324                                           OpFlag);
8325   SDLoc DL(JT);
8326   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8327
8328   // With PIC, the address is actually $g + Offset.
8329   if (OpFlag)
8330     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8331                          DAG.getNode(X86ISD::GlobalBaseReg,
8332                                      SDLoc(), getPointerTy()),
8333                          Result);
8334
8335   return Result;
8336 }
8337
8338 SDValue
8339 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8340   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8341
8342   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8343   // global base reg.
8344   unsigned char OpFlag = 0;
8345   unsigned WrapperKind = X86ISD::Wrapper;
8346   CodeModel::Model M = getTargetMachine().getCodeModel();
8347
8348   if (Subtarget->isPICStyleRIPRel() &&
8349       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8350     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8351       OpFlag = X86II::MO_GOTPCREL;
8352     WrapperKind = X86ISD::WrapperRIP;
8353   } else if (Subtarget->isPICStyleGOT()) {
8354     OpFlag = X86II::MO_GOT;
8355   } else if (Subtarget->isPICStyleStubPIC()) {
8356     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8357   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8358     OpFlag = X86II::MO_DARWIN_NONLAZY;
8359   }
8360
8361   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8362
8363   SDLoc DL(Op);
8364   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8365
8366   // With PIC, the address is actually $g + Offset.
8367   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8368       !Subtarget->is64Bit()) {
8369     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8370                          DAG.getNode(X86ISD::GlobalBaseReg,
8371                                      SDLoc(), getPointerTy()),
8372                          Result);
8373   }
8374
8375   // For symbols that require a load from a stub to get the address, emit the
8376   // load.
8377   if (isGlobalStubReference(OpFlag))
8378     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8379                          MachinePointerInfo::getGOT(), false, false, false, 0);
8380
8381   return Result;
8382 }
8383
8384 SDValue
8385 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8386   // Create the TargetBlockAddressAddress node.
8387   unsigned char OpFlags =
8388     Subtarget->ClassifyBlockAddressReference();
8389   CodeModel::Model M = getTargetMachine().getCodeModel();
8390   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8391   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8392   SDLoc dl(Op);
8393   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8394                                              OpFlags);
8395
8396   if (Subtarget->isPICStyleRIPRel() &&
8397       (M == CodeModel::Small || M == CodeModel::Kernel))
8398     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8399   else
8400     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8401
8402   // With PIC, the address is actually $g + Offset.
8403   if (isGlobalRelativeToPICBase(OpFlags)) {
8404     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8405                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8406                          Result);
8407   }
8408
8409   return Result;
8410 }
8411
8412 SDValue
8413 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8414                                       int64_t Offset, SelectionDAG &DAG) const {
8415   // Create the TargetGlobalAddress node, folding in the constant
8416   // offset if it is legal.
8417   unsigned char OpFlags =
8418     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8419   CodeModel::Model M = getTargetMachine().getCodeModel();
8420   SDValue Result;
8421   if (OpFlags == X86II::MO_NO_FLAG &&
8422       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8423     // A direct static reference to a global.
8424     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8425     Offset = 0;
8426   } else {
8427     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8428   }
8429
8430   if (Subtarget->isPICStyleRIPRel() &&
8431       (M == CodeModel::Small || M == CodeModel::Kernel))
8432     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8433   else
8434     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8435
8436   // With PIC, the address is actually $g + Offset.
8437   if (isGlobalRelativeToPICBase(OpFlags)) {
8438     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8439                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8440                          Result);
8441   }
8442
8443   // For globals that require a load from a stub to get the address, emit the
8444   // load.
8445   if (isGlobalStubReference(OpFlags))
8446     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8447                          MachinePointerInfo::getGOT(), false, false, false, 0);
8448
8449   // If there was a non-zero offset that we didn't fold, create an explicit
8450   // addition for it.
8451   if (Offset != 0)
8452     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8453                          DAG.getConstant(Offset, getPointerTy()));
8454
8455   return Result;
8456 }
8457
8458 SDValue
8459 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8460   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8461   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8462   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8463 }
8464
8465 static SDValue
8466 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8467            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8468            unsigned char OperandFlags, bool LocalDynamic = false) {
8469   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8470   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8471   SDLoc dl(GA);
8472   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8473                                            GA->getValueType(0),
8474                                            GA->getOffset(),
8475                                            OperandFlags);
8476
8477   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8478                                            : X86ISD::TLSADDR;
8479
8480   if (InFlag) {
8481     SDValue Ops[] = { Chain,  TGA, *InFlag };
8482     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8483   } else {
8484     SDValue Ops[]  = { Chain, TGA };
8485     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8486   }
8487
8488   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8489   MFI->setAdjustsStack(true);
8490
8491   SDValue Flag = Chain.getValue(1);
8492   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8493 }
8494
8495 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8496 static SDValue
8497 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8498                                 const EVT PtrVT) {
8499   SDValue InFlag;
8500   SDLoc dl(GA);  // ? function entry point might be better
8501   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8502                                    DAG.getNode(X86ISD::GlobalBaseReg,
8503                                                SDLoc(), PtrVT), InFlag);
8504   InFlag = Chain.getValue(1);
8505
8506   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8507 }
8508
8509 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8510 static SDValue
8511 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8512                                 const EVT PtrVT) {
8513   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8514                     X86::RAX, X86II::MO_TLSGD);
8515 }
8516
8517 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8518                                            SelectionDAG &DAG,
8519                                            const EVT PtrVT,
8520                                            bool is64Bit) {
8521   SDLoc dl(GA);
8522
8523   // Get the start address of the TLS block for this module.
8524   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8525       .getInfo<X86MachineFunctionInfo>();
8526   MFI->incNumLocalDynamicTLSAccesses();
8527
8528   SDValue Base;
8529   if (is64Bit) {
8530     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8531                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8532   } else {
8533     SDValue InFlag;
8534     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8535         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8536     InFlag = Chain.getValue(1);
8537     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8538                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8539   }
8540
8541   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8542   // of Base.
8543
8544   // Build x@dtpoff.
8545   unsigned char OperandFlags = X86II::MO_DTPOFF;
8546   unsigned WrapperKind = X86ISD::Wrapper;
8547   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8548                                            GA->getValueType(0),
8549                                            GA->getOffset(), OperandFlags);
8550   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8551
8552   // Add x@dtpoff with the base.
8553   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8554 }
8555
8556 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8557 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8558                                    const EVT PtrVT, TLSModel::Model model,
8559                                    bool is64Bit, bool isPIC) {
8560   SDLoc dl(GA);
8561
8562   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8563   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8564                                                          is64Bit ? 257 : 256));
8565
8566   SDValue ThreadPointer =
8567       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8568                   MachinePointerInfo(Ptr), false, false, false, 0);
8569
8570   unsigned char OperandFlags = 0;
8571   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8572   // initialexec.
8573   unsigned WrapperKind = X86ISD::Wrapper;
8574   if (model == TLSModel::LocalExec) {
8575     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8576   } else if (model == TLSModel::InitialExec) {
8577     if (is64Bit) {
8578       OperandFlags = X86II::MO_GOTTPOFF;
8579       WrapperKind = X86ISD::WrapperRIP;
8580     } else {
8581       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8582     }
8583   } else {
8584     llvm_unreachable("Unexpected model");
8585   }
8586
8587   // emit "addl x@ntpoff,%eax" (local exec)
8588   // or "addl x@indntpoff,%eax" (initial exec)
8589   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8590   SDValue TGA =
8591       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8592                                  GA->getOffset(), OperandFlags);
8593   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8594
8595   if (model == TLSModel::InitialExec) {
8596     if (isPIC && !is64Bit) {
8597       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8598                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8599                            Offset);
8600     }
8601
8602     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8603                          MachinePointerInfo::getGOT(), false, false, false, 0);
8604   }
8605
8606   // The address of the thread local variable is the add of the thread
8607   // pointer with the offset of the variable.
8608   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8609 }
8610
8611 SDValue
8612 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8613
8614   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8615   const GlobalValue *GV = GA->getGlobal();
8616
8617   if (Subtarget->isTargetELF()) {
8618     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8619
8620     switch (model) {
8621       case TLSModel::GeneralDynamic:
8622         if (Subtarget->is64Bit())
8623           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8624         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8625       case TLSModel::LocalDynamic:
8626         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8627                                            Subtarget->is64Bit());
8628       case TLSModel::InitialExec:
8629       case TLSModel::LocalExec:
8630         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8631                                    Subtarget->is64Bit(),
8632                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8633     }
8634     llvm_unreachable("Unknown TLS model.");
8635   }
8636
8637   if (Subtarget->isTargetDarwin()) {
8638     // Darwin only has one model of TLS.  Lower to that.
8639     unsigned char OpFlag = 0;
8640     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8641                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8642
8643     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8644     // global base reg.
8645     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8646                   !Subtarget->is64Bit();
8647     if (PIC32)
8648       OpFlag = X86II::MO_TLVP_PIC_BASE;
8649     else
8650       OpFlag = X86II::MO_TLVP;
8651     SDLoc DL(Op);
8652     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8653                                                 GA->getValueType(0),
8654                                                 GA->getOffset(), OpFlag);
8655     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8656
8657     // With PIC32, the address is actually $g + Offset.
8658     if (PIC32)
8659       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8660                            DAG.getNode(X86ISD::GlobalBaseReg,
8661                                        SDLoc(), getPointerTy()),
8662                            Offset);
8663
8664     // Lowering the machine isd will make sure everything is in the right
8665     // location.
8666     SDValue Chain = DAG.getEntryNode();
8667     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8668     SDValue Args[] = { Chain, Offset };
8669     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8670
8671     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8672     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8673     MFI->setAdjustsStack(true);
8674
8675     // And our return value (tls address) is in the standard call return value
8676     // location.
8677     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8678     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8679                               Chain.getValue(1));
8680   }
8681
8682   if (Subtarget->isTargetKnownWindowsMSVC() ||
8683       Subtarget->isTargetWindowsGNU()) {
8684     // Just use the implicit TLS architecture
8685     // Need to generate someting similar to:
8686     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8687     //                                  ; from TEB
8688     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8689     //   mov     rcx, qword [rdx+rcx*8]
8690     //   mov     eax, .tls$:tlsvar
8691     //   [rax+rcx] contains the address
8692     // Windows 64bit: gs:0x58
8693     // Windows 32bit: fs:__tls_array
8694
8695     // If GV is an alias then use the aliasee for determining
8696     // thread-localness.
8697     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8698       GV = GA->getAliasedGlobal();
8699     SDLoc dl(GA);
8700     SDValue Chain = DAG.getEntryNode();
8701
8702     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8703     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8704     // use its literal value of 0x2C.
8705     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8706                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8707                                                              256)
8708                                         : Type::getInt32PtrTy(*DAG.getContext(),
8709                                                               257));
8710
8711     SDValue TlsArray =
8712         Subtarget->is64Bit()
8713             ? DAG.getIntPtrConstant(0x58)
8714             : (Subtarget->isTargetWindowsGNU()
8715                    ? DAG.getIntPtrConstant(0x2C)
8716                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8717
8718     SDValue ThreadPointer =
8719         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8720                     MachinePointerInfo(Ptr), false, false, false, 0);
8721
8722     // Load the _tls_index variable
8723     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8724     if (Subtarget->is64Bit())
8725       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8726                            IDX, MachinePointerInfo(), MVT::i32,
8727                            false, false, 0);
8728     else
8729       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8730                         false, false, false, 0);
8731
8732     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8733                                     getPointerTy());
8734     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8735
8736     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8737     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8738                       false, false, false, 0);
8739
8740     // Get the offset of start of .tls section
8741     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8742                                              GA->getValueType(0),
8743                                              GA->getOffset(), X86II::MO_SECREL);
8744     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8745
8746     // The address of the thread local variable is the add of the thread
8747     // pointer with the offset of the variable.
8748     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8749   }
8750
8751   llvm_unreachable("TLS not implemented for this target.");
8752 }
8753
8754 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8755 /// and take a 2 x i32 value to shift plus a shift amount.
8756 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8757   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8758   MVT VT = Op.getSimpleValueType();
8759   unsigned VTBits = VT.getSizeInBits();
8760   SDLoc dl(Op);
8761   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8762   SDValue ShOpLo = Op.getOperand(0);
8763   SDValue ShOpHi = Op.getOperand(1);
8764   SDValue ShAmt  = Op.getOperand(2);
8765   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8766   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8767   // during isel.
8768   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8769                                   DAG.getConstant(VTBits - 1, MVT::i8));
8770   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8771                                      DAG.getConstant(VTBits - 1, MVT::i8))
8772                        : DAG.getConstant(0, VT);
8773
8774   SDValue Tmp2, Tmp3;
8775   if (Op.getOpcode() == ISD::SHL_PARTS) {
8776     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8777     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8778   } else {
8779     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8780     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8781   }
8782
8783   // If the shift amount is larger or equal than the width of a part we can't
8784   // rely on the results of shld/shrd. Insert a test and select the appropriate
8785   // values for large shift amounts.
8786   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8787                                 DAG.getConstant(VTBits, MVT::i8));
8788   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8789                              AndNode, DAG.getConstant(0, MVT::i8));
8790
8791   SDValue Hi, Lo;
8792   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8793   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8794   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8795
8796   if (Op.getOpcode() == ISD::SHL_PARTS) {
8797     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8798     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8799   } else {
8800     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8801     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8802   }
8803
8804   SDValue Ops[2] = { Lo, Hi };
8805   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8806 }
8807
8808 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8809                                            SelectionDAG &DAG) const {
8810   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8811
8812   if (SrcVT.isVector())
8813     return SDValue();
8814
8815   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8816          "Unknown SINT_TO_FP to lower!");
8817
8818   // These are really Legal; return the operand so the caller accepts it as
8819   // Legal.
8820   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8821     return Op;
8822   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8823       Subtarget->is64Bit()) {
8824     return Op;
8825   }
8826
8827   SDLoc dl(Op);
8828   unsigned Size = SrcVT.getSizeInBits()/8;
8829   MachineFunction &MF = DAG.getMachineFunction();
8830   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8831   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8832   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8833                                StackSlot,
8834                                MachinePointerInfo::getFixedStack(SSFI),
8835                                false, false, 0);
8836   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8837 }
8838
8839 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8840                                      SDValue StackSlot,
8841                                      SelectionDAG &DAG) const {
8842   // Build the FILD
8843   SDLoc DL(Op);
8844   SDVTList Tys;
8845   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8846   if (useSSE)
8847     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8848   else
8849     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8850
8851   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8852
8853   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8854   MachineMemOperand *MMO;
8855   if (FI) {
8856     int SSFI = FI->getIndex();
8857     MMO =
8858       DAG.getMachineFunction()
8859       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8860                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8861   } else {
8862     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8863     StackSlot = StackSlot.getOperand(1);
8864   }
8865   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8866   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8867                                            X86ISD::FILD, DL,
8868                                            Tys, Ops, array_lengthof(Ops),
8869                                            SrcVT, MMO);
8870
8871   if (useSSE) {
8872     Chain = Result.getValue(1);
8873     SDValue InFlag = Result.getValue(2);
8874
8875     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8876     // shouldn't be necessary except that RFP cannot be live across
8877     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8878     MachineFunction &MF = DAG.getMachineFunction();
8879     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8880     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8881     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8882     Tys = DAG.getVTList(MVT::Other);
8883     SDValue Ops[] = {
8884       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8885     };
8886     MachineMemOperand *MMO =
8887       DAG.getMachineFunction()
8888       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8889                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8890
8891     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8892                                     Ops, array_lengthof(Ops),
8893                                     Op.getValueType(), MMO);
8894     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8895                          MachinePointerInfo::getFixedStack(SSFI),
8896                          false, false, false, 0);
8897   }
8898
8899   return Result;
8900 }
8901
8902 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8903 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8904                                                SelectionDAG &DAG) const {
8905   // This algorithm is not obvious. Here it is what we're trying to output:
8906   /*
8907      movq       %rax,  %xmm0
8908      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8909      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8910      #ifdef __SSE3__
8911        haddpd   %xmm0, %xmm0
8912      #else
8913        pshufd   $0x4e, %xmm0, %xmm1
8914        addpd    %xmm1, %xmm0
8915      #endif
8916   */
8917
8918   SDLoc dl(Op);
8919   LLVMContext *Context = DAG.getContext();
8920
8921   // Build some magic constants.
8922   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8923   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8924   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8925
8926   SmallVector<Constant*,2> CV1;
8927   CV1.push_back(
8928     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8929                                       APInt(64, 0x4330000000000000ULL))));
8930   CV1.push_back(
8931     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8932                                       APInt(64, 0x4530000000000000ULL))));
8933   Constant *C1 = ConstantVector::get(CV1);
8934   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8935
8936   // Load the 64-bit value into an XMM register.
8937   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8938                             Op.getOperand(0));
8939   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8940                               MachinePointerInfo::getConstantPool(),
8941                               false, false, false, 16);
8942   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8943                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8944                               CLod0);
8945
8946   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8947                               MachinePointerInfo::getConstantPool(),
8948                               false, false, false, 16);
8949   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8950   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8951   SDValue Result;
8952
8953   if (Subtarget->hasSSE3()) {
8954     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8955     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8956   } else {
8957     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8958     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8959                                            S2F, 0x4E, DAG);
8960     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8961                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8962                          Sub);
8963   }
8964
8965   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8966                      DAG.getIntPtrConstant(0));
8967 }
8968
8969 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8970 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8971                                                SelectionDAG &DAG) const {
8972   SDLoc dl(Op);
8973   // FP constant to bias correct the final result.
8974   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8975                                    MVT::f64);
8976
8977   // Load the 32-bit value into an XMM register.
8978   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8979                              Op.getOperand(0));
8980
8981   // Zero out the upper parts of the register.
8982   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8983
8984   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8985                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8986                      DAG.getIntPtrConstant(0));
8987
8988   // Or the load with the bias.
8989   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8990                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8991                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8992                                                    MVT::v2f64, Load)),
8993                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8994                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8995                                                    MVT::v2f64, Bias)));
8996   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8997                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8998                    DAG.getIntPtrConstant(0));
8999
9000   // Subtract the bias.
9001   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9002
9003   // Handle final rounding.
9004   EVT DestVT = Op.getValueType();
9005
9006   if (DestVT.bitsLT(MVT::f64))
9007     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9008                        DAG.getIntPtrConstant(0));
9009   if (DestVT.bitsGT(MVT::f64))
9010     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9011
9012   // Handle final rounding.
9013   return Sub;
9014 }
9015
9016 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9017                                                SelectionDAG &DAG) const {
9018   SDValue N0 = Op.getOperand(0);
9019   MVT SVT = N0.getSimpleValueType();
9020   SDLoc dl(Op);
9021
9022   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9023           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9024          "Custom UINT_TO_FP is not supported!");
9025
9026   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9027   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9028                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9029 }
9030
9031 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9032                                            SelectionDAG &DAG) const {
9033   SDValue N0 = Op.getOperand(0);
9034   SDLoc dl(Op);
9035
9036   if (Op.getValueType().isVector())
9037     return lowerUINT_TO_FP_vec(Op, DAG);
9038
9039   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9040   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9041   // the optimization here.
9042   if (DAG.SignBitIsZero(N0))
9043     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9044
9045   MVT SrcVT = N0.getSimpleValueType();
9046   MVT DstVT = Op.getSimpleValueType();
9047   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9048     return LowerUINT_TO_FP_i64(Op, DAG);
9049   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9050     return LowerUINT_TO_FP_i32(Op, DAG);
9051   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9052     return SDValue();
9053
9054   // Make a 64-bit buffer, and use it to build an FILD.
9055   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9056   if (SrcVT == MVT::i32) {
9057     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9058     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9059                                      getPointerTy(), StackSlot, WordOff);
9060     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9061                                   StackSlot, MachinePointerInfo(),
9062                                   false, false, 0);
9063     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9064                                   OffsetSlot, MachinePointerInfo(),
9065                                   false, false, 0);
9066     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9067     return Fild;
9068   }
9069
9070   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9071   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9072                                StackSlot, MachinePointerInfo(),
9073                                false, false, 0);
9074   // For i64 source, we need to add the appropriate power of 2 if the input
9075   // was negative.  This is the same as the optimization in
9076   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9077   // we must be careful to do the computation in x87 extended precision, not
9078   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9079   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9080   MachineMemOperand *MMO =
9081     DAG.getMachineFunction()
9082     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9083                           MachineMemOperand::MOLoad, 8, 8);
9084
9085   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9086   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9087   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9088                                          array_lengthof(Ops), MVT::i64, MMO);
9089
9090   APInt FF(32, 0x5F800000ULL);
9091
9092   // Check whether the sign bit is set.
9093   SDValue SignSet = DAG.getSetCC(dl,
9094                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9095                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9096                                  ISD::SETLT);
9097
9098   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9099   SDValue FudgePtr = DAG.getConstantPool(
9100                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9101                                          getPointerTy());
9102
9103   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9104   SDValue Zero = DAG.getIntPtrConstant(0);
9105   SDValue Four = DAG.getIntPtrConstant(4);
9106   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9107                                Zero, Four);
9108   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9109
9110   // Load the value out, extending it from f32 to f80.
9111   // FIXME: Avoid the extend by constructing the right constant pool?
9112   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9113                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9114                                  MVT::f32, false, false, 4);
9115   // Extend everything to 80 bits to force it to be done on x87.
9116   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9117   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9118 }
9119
9120 std::pair<SDValue,SDValue>
9121 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9122                                     bool IsSigned, bool IsReplace) const {
9123   SDLoc DL(Op);
9124
9125   EVT DstTy = Op.getValueType();
9126
9127   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9128     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9129     DstTy = MVT::i64;
9130   }
9131
9132   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9133          DstTy.getSimpleVT() >= MVT::i16 &&
9134          "Unknown FP_TO_INT to lower!");
9135
9136   // These are really Legal.
9137   if (DstTy == MVT::i32 &&
9138       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9139     return std::make_pair(SDValue(), SDValue());
9140   if (Subtarget->is64Bit() &&
9141       DstTy == MVT::i64 &&
9142       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9143     return std::make_pair(SDValue(), SDValue());
9144
9145   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9146   // stack slot, or into the FTOL runtime function.
9147   MachineFunction &MF = DAG.getMachineFunction();
9148   unsigned MemSize = DstTy.getSizeInBits()/8;
9149   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9150   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9151
9152   unsigned Opc;
9153   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9154     Opc = X86ISD::WIN_FTOL;
9155   else
9156     switch (DstTy.getSimpleVT().SimpleTy) {
9157     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9158     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9159     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9160     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9161     }
9162
9163   SDValue Chain = DAG.getEntryNode();
9164   SDValue Value = Op.getOperand(0);
9165   EVT TheVT = Op.getOperand(0).getValueType();
9166   // FIXME This causes a redundant load/store if the SSE-class value is already
9167   // in memory, such as if it is on the callstack.
9168   if (isScalarFPTypeInSSEReg(TheVT)) {
9169     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9170     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9171                          MachinePointerInfo::getFixedStack(SSFI),
9172                          false, false, 0);
9173     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9174     SDValue Ops[] = {
9175       Chain, StackSlot, DAG.getValueType(TheVT)
9176     };
9177
9178     MachineMemOperand *MMO =
9179       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9180                               MachineMemOperand::MOLoad, MemSize, MemSize);
9181     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
9182                                     array_lengthof(Ops), DstTy, MMO);
9183     Chain = Value.getValue(1);
9184     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9185     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9186   }
9187
9188   MachineMemOperand *MMO =
9189     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9190                             MachineMemOperand::MOStore, MemSize, MemSize);
9191
9192   if (Opc != X86ISD::WIN_FTOL) {
9193     // Build the FP_TO_INT*_IN_MEM
9194     SDValue Ops[] = { Chain, Value, StackSlot };
9195     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9196                                            Ops, array_lengthof(Ops), DstTy,
9197                                            MMO);
9198     return std::make_pair(FIST, StackSlot);
9199   } else {
9200     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9201       DAG.getVTList(MVT::Other, MVT::Glue),
9202       Chain, Value);
9203     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9204       MVT::i32, ftol.getValue(1));
9205     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9206       MVT::i32, eax.getValue(2));
9207     SDValue Ops[] = { eax, edx };
9208     SDValue pair = IsReplace
9209       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9210       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9211     return std::make_pair(pair, SDValue());
9212   }
9213 }
9214
9215 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9216                               const X86Subtarget *Subtarget) {
9217   MVT VT = Op->getSimpleValueType(0);
9218   SDValue In = Op->getOperand(0);
9219   MVT InVT = In.getSimpleValueType();
9220   SDLoc dl(Op);
9221
9222   // Optimize vectors in AVX mode:
9223   //
9224   //   v8i16 -> v8i32
9225   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9226   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9227   //   Concat upper and lower parts.
9228   //
9229   //   v4i32 -> v4i64
9230   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9231   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9232   //   Concat upper and lower parts.
9233   //
9234
9235   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9236       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9237       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9238     return SDValue();
9239
9240   if (Subtarget->hasInt256())
9241     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9242
9243   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9244   SDValue Undef = DAG.getUNDEF(InVT);
9245   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9246   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9247   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9248
9249   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9250                              VT.getVectorNumElements()/2);
9251
9252   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9253   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9254
9255   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9256 }
9257
9258 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9259                                         SelectionDAG &DAG) {
9260   MVT VT = Op->getSimpleValueType(0);
9261   SDValue In = Op->getOperand(0);
9262   MVT InVT = In.getSimpleValueType();
9263   SDLoc DL(Op);
9264   unsigned int NumElts = VT.getVectorNumElements();
9265   if (NumElts != 8 && NumElts != 16)
9266     return SDValue();
9267
9268   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9269     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9270
9271   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9272   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9273   // Now we have only mask extension
9274   assert(InVT.getVectorElementType() == MVT::i1);
9275   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9276   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9277   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9278   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9279   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9280                            MachinePointerInfo::getConstantPool(),
9281                            false, false, false, Alignment);
9282
9283   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9284   if (VT.is512BitVector())
9285     return Brcst;
9286   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9287 }
9288
9289 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9290                                SelectionDAG &DAG) {
9291   if (Subtarget->hasFp256()) {
9292     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9293     if (Res.getNode())
9294       return Res;
9295   }
9296
9297   return SDValue();
9298 }
9299
9300 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9301                                 SelectionDAG &DAG) {
9302   SDLoc DL(Op);
9303   MVT VT = Op.getSimpleValueType();
9304   SDValue In = Op.getOperand(0);
9305   MVT SVT = In.getSimpleValueType();
9306
9307   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9308     return LowerZERO_EXTEND_AVX512(Op, DAG);
9309
9310   if (Subtarget->hasFp256()) {
9311     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9312     if (Res.getNode())
9313       return Res;
9314   }
9315
9316   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9317          VT.getVectorNumElements() != SVT.getVectorNumElements());
9318   return SDValue();
9319 }
9320
9321 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9322   SDLoc DL(Op);
9323   MVT VT = Op.getSimpleValueType();
9324   SDValue In = Op.getOperand(0);
9325   MVT InVT = In.getSimpleValueType();
9326
9327   if (VT == MVT::i1) {
9328     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9329            "Invalid scalar TRUNCATE operation");
9330     if (InVT == MVT::i32)
9331       return SDValue();
9332     if (InVT.getSizeInBits() == 64)
9333       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9334     else if (InVT.getSizeInBits() < 32)
9335       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9336     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9337   }
9338   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9339          "Invalid TRUNCATE operation");
9340
9341   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9342     if (VT.getVectorElementType().getSizeInBits() >=8)
9343       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9344
9345     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9346     unsigned NumElts = InVT.getVectorNumElements();
9347     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9348     if (InVT.getSizeInBits() < 512) {
9349       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9350       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9351       InVT = ExtVT;
9352     }
9353     
9354     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9355     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9356     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9357     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9358     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9359                            MachinePointerInfo::getConstantPool(),
9360                            false, false, false, Alignment);
9361     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9362     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9363     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9364   }
9365
9366   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9367     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9368     if (Subtarget->hasInt256()) {
9369       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9370       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9371       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9372                                 ShufMask);
9373       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9374                          DAG.getIntPtrConstant(0));
9375     }
9376
9377     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9378                                DAG.getIntPtrConstant(0));
9379     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9380                                DAG.getIntPtrConstant(2));
9381     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9382     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9383     static const int ShufMask[] = {0, 2, 4, 6};
9384     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9385   }
9386
9387   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9388     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9389     if (Subtarget->hasInt256()) {
9390       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9391
9392       SmallVector<SDValue,32> pshufbMask;
9393       for (unsigned i = 0; i < 2; ++i) {
9394         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9395         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9396         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9397         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9398         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9399         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9400         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9401         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9402         for (unsigned j = 0; j < 8; ++j)
9403           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9404       }
9405       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9406       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9407       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9408
9409       static const int ShufMask[] = {0,  2,  -1,  -1};
9410       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9411                                 &ShufMask[0]);
9412       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9413                        DAG.getIntPtrConstant(0));
9414       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9415     }
9416
9417     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9418                                DAG.getIntPtrConstant(0));
9419
9420     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9421                                DAG.getIntPtrConstant(4));
9422
9423     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9424     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9425
9426     // The PSHUFB mask:
9427     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9428                                    -1, -1, -1, -1, -1, -1, -1, -1};
9429
9430     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9431     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9432     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9433
9434     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9435     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9436
9437     // The MOVLHPS Mask:
9438     static const int ShufMask2[] = {0, 1, 4, 5};
9439     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9440     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9441   }
9442
9443   // Handle truncation of V256 to V128 using shuffles.
9444   if (!VT.is128BitVector() || !InVT.is256BitVector())
9445     return SDValue();
9446
9447   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9448
9449   unsigned NumElems = VT.getVectorNumElements();
9450   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9451
9452   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9453   // Prepare truncation shuffle mask
9454   for (unsigned i = 0; i != NumElems; ++i)
9455     MaskVec[i] = i * 2;
9456   SDValue V = DAG.getVectorShuffle(NVT, DL,
9457                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9458                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9459   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9460                      DAG.getIntPtrConstant(0));
9461 }
9462
9463 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9464                                            SelectionDAG &DAG) const {
9465   assert(!Op.getSimpleValueType().isVector());
9466
9467   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9468     /*IsSigned=*/ true, /*IsReplace=*/ false);
9469   SDValue FIST = Vals.first, StackSlot = Vals.second;
9470   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9471   if (!FIST.getNode()) return Op;
9472
9473   if (StackSlot.getNode())
9474     // Load the result.
9475     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9476                        FIST, StackSlot, MachinePointerInfo(),
9477                        false, false, false, 0);
9478
9479   // The node is the result.
9480   return FIST;
9481 }
9482
9483 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9484                                            SelectionDAG &DAG) const {
9485   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9486     /*IsSigned=*/ false, /*IsReplace=*/ false);
9487   SDValue FIST = Vals.first, StackSlot = Vals.second;
9488   assert(FIST.getNode() && "Unexpected failure");
9489
9490   if (StackSlot.getNode())
9491     // Load the result.
9492     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9493                        FIST, StackSlot, MachinePointerInfo(),
9494                        false, false, false, 0);
9495
9496   // The node is the result.
9497   return FIST;
9498 }
9499
9500 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9501   SDLoc DL(Op);
9502   MVT VT = Op.getSimpleValueType();
9503   SDValue In = Op.getOperand(0);
9504   MVT SVT = In.getSimpleValueType();
9505
9506   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9507
9508   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9509                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9510                                  In, DAG.getUNDEF(SVT)));
9511 }
9512
9513 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9514   LLVMContext *Context = DAG.getContext();
9515   SDLoc dl(Op);
9516   MVT VT = Op.getSimpleValueType();
9517   MVT EltVT = VT;
9518   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9519   if (VT.isVector()) {
9520     EltVT = VT.getVectorElementType();
9521     NumElts = VT.getVectorNumElements();
9522   }
9523   Constant *C;
9524   if (EltVT == MVT::f64)
9525     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9526                                           APInt(64, ~(1ULL << 63))));
9527   else
9528     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9529                                           APInt(32, ~(1U << 31))));
9530   C = ConstantVector::getSplat(NumElts, C);
9531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9532   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9533   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9534   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9535                              MachinePointerInfo::getConstantPool(),
9536                              false, false, false, Alignment);
9537   if (VT.isVector()) {
9538     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9539     return DAG.getNode(ISD::BITCAST, dl, VT,
9540                        DAG.getNode(ISD::AND, dl, ANDVT,
9541                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9542                                                Op.getOperand(0)),
9543                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9544   }
9545   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9546 }
9547
9548 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9549   LLVMContext *Context = DAG.getContext();
9550   SDLoc dl(Op);
9551   MVT VT = Op.getSimpleValueType();
9552   MVT EltVT = VT;
9553   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9554   if (VT.isVector()) {
9555     EltVT = VT.getVectorElementType();
9556     NumElts = VT.getVectorNumElements();
9557   }
9558   Constant *C;
9559   if (EltVT == MVT::f64)
9560     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9561                                           APInt(64, 1ULL << 63)));
9562   else
9563     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9564                                           APInt(32, 1U << 31)));
9565   C = ConstantVector::getSplat(NumElts, C);
9566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9567   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9568   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9569   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9570                              MachinePointerInfo::getConstantPool(),
9571                              false, false, false, Alignment);
9572   if (VT.isVector()) {
9573     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9574     return DAG.getNode(ISD::BITCAST, dl, VT,
9575                        DAG.getNode(ISD::XOR, dl, XORVT,
9576                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9577                                                Op.getOperand(0)),
9578                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9579   }
9580
9581   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9582 }
9583
9584 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9586   LLVMContext *Context = DAG.getContext();
9587   SDValue Op0 = Op.getOperand(0);
9588   SDValue Op1 = Op.getOperand(1);
9589   SDLoc dl(Op);
9590   MVT VT = Op.getSimpleValueType();
9591   MVT SrcVT = Op1.getSimpleValueType();
9592
9593   // If second operand is smaller, extend it first.
9594   if (SrcVT.bitsLT(VT)) {
9595     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9596     SrcVT = VT;
9597   }
9598   // And if it is bigger, shrink it first.
9599   if (SrcVT.bitsGT(VT)) {
9600     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9601     SrcVT = VT;
9602   }
9603
9604   // At this point the operands and the result should have the same
9605   // type, and that won't be f80 since that is not custom lowered.
9606
9607   // First get the sign bit of second operand.
9608   SmallVector<Constant*,4> CV;
9609   if (SrcVT == MVT::f64) {
9610     const fltSemantics &Sem = APFloat::IEEEdouble;
9611     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9612     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9613   } else {
9614     const fltSemantics &Sem = APFloat::IEEEsingle;
9615     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9616     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9617     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9618     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9619   }
9620   Constant *C = ConstantVector::get(CV);
9621   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9622   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9623                               MachinePointerInfo::getConstantPool(),
9624                               false, false, false, 16);
9625   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9626
9627   // Shift sign bit right or left if the two operands have different types.
9628   if (SrcVT.bitsGT(VT)) {
9629     // Op0 is MVT::f32, Op1 is MVT::f64.
9630     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9631     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9632                           DAG.getConstant(32, MVT::i32));
9633     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9634     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9635                           DAG.getIntPtrConstant(0));
9636   }
9637
9638   // Clear first operand sign bit.
9639   CV.clear();
9640   if (VT == MVT::f64) {
9641     const fltSemantics &Sem = APFloat::IEEEdouble;
9642     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9643                                                    APInt(64, ~(1ULL << 63)))));
9644     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9645   } else {
9646     const fltSemantics &Sem = APFloat::IEEEsingle;
9647     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9648                                                    APInt(32, ~(1U << 31)))));
9649     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9650     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9651     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9652   }
9653   C = ConstantVector::get(CV);
9654   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9655   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9656                               MachinePointerInfo::getConstantPool(),
9657                               false, false, false, 16);
9658   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9659
9660   // Or the value with the sign bit.
9661   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9662 }
9663
9664 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9665   SDValue N0 = Op.getOperand(0);
9666   SDLoc dl(Op);
9667   MVT VT = Op.getSimpleValueType();
9668
9669   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9670   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9671                                   DAG.getConstant(1, VT));
9672   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9673 }
9674
9675 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9676 //
9677 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9678                                       SelectionDAG &DAG) {
9679   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9680
9681   if (!Subtarget->hasSSE41())
9682     return SDValue();
9683
9684   if (!Op->hasOneUse())
9685     return SDValue();
9686
9687   SDNode *N = Op.getNode();
9688   SDLoc DL(N);
9689
9690   SmallVector<SDValue, 8> Opnds;
9691   DenseMap<SDValue, unsigned> VecInMap;
9692   SmallVector<SDValue, 8> VecIns;
9693   EVT VT = MVT::Other;
9694
9695   // Recognize a special case where a vector is casted into wide integer to
9696   // test all 0s.
9697   Opnds.push_back(N->getOperand(0));
9698   Opnds.push_back(N->getOperand(1));
9699
9700   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9701     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9702     // BFS traverse all OR'd operands.
9703     if (I->getOpcode() == ISD::OR) {
9704       Opnds.push_back(I->getOperand(0));
9705       Opnds.push_back(I->getOperand(1));
9706       // Re-evaluate the number of nodes to be traversed.
9707       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9708       continue;
9709     }
9710
9711     // Quit if a non-EXTRACT_VECTOR_ELT
9712     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9713       return SDValue();
9714
9715     // Quit if without a constant index.
9716     SDValue Idx = I->getOperand(1);
9717     if (!isa<ConstantSDNode>(Idx))
9718       return SDValue();
9719
9720     SDValue ExtractedFromVec = I->getOperand(0);
9721     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9722     if (M == VecInMap.end()) {
9723       VT = ExtractedFromVec.getValueType();
9724       // Quit if not 128/256-bit vector.
9725       if (!VT.is128BitVector() && !VT.is256BitVector())
9726         return SDValue();
9727       // Quit if not the same type.
9728       if (VecInMap.begin() != VecInMap.end() &&
9729           VT != VecInMap.begin()->first.getValueType())
9730         return SDValue();
9731       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9732       VecIns.push_back(ExtractedFromVec);
9733     }
9734     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9735   }
9736
9737   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9738          "Not extracted from 128-/256-bit vector.");
9739
9740   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9741
9742   for (DenseMap<SDValue, unsigned>::const_iterator
9743         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9744     // Quit if not all elements are used.
9745     if (I->second != FullMask)
9746       return SDValue();
9747   }
9748
9749   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9750
9751   // Cast all vectors into TestVT for PTEST.
9752   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9753     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9754
9755   // If more than one full vectors are evaluated, OR them first before PTEST.
9756   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9757     // Each iteration will OR 2 nodes and append the result until there is only
9758     // 1 node left, i.e. the final OR'd value of all vectors.
9759     SDValue LHS = VecIns[Slot];
9760     SDValue RHS = VecIns[Slot + 1];
9761     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9762   }
9763
9764   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9765                      VecIns.back(), VecIns.back());
9766 }
9767
9768 /// \brief return true if \c Op has a use that doesn't just read flags.
9769 static bool hasNonFlagsUse(SDValue Op) {
9770   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9771        ++UI) {
9772     SDNode *User = *UI;
9773     unsigned UOpNo = UI.getOperandNo();
9774     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9775       // Look pass truncate.
9776       UOpNo = User->use_begin().getOperandNo();
9777       User = *User->use_begin();
9778     }
9779
9780     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9781         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9782       return true;
9783   }
9784   return false;
9785 }
9786
9787 /// Emit nodes that will be selected as "test Op0,Op0", or something
9788 /// equivalent.
9789 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9790                                     SelectionDAG &DAG) const {
9791   if (Op.getValueType() == MVT::i1)
9792     // KORTEST instruction should be selected
9793     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9794                        DAG.getConstant(0, Op.getValueType()));
9795
9796   // CF and OF aren't always set the way we want. Determine which
9797   // of these we need.
9798   bool NeedCF = false;
9799   bool NeedOF = false;
9800   switch (X86CC) {
9801   default: break;
9802   case X86::COND_A: case X86::COND_AE:
9803   case X86::COND_B: case X86::COND_BE:
9804     NeedCF = true;
9805     break;
9806   case X86::COND_G: case X86::COND_GE:
9807   case X86::COND_L: case X86::COND_LE:
9808   case X86::COND_O: case X86::COND_NO:
9809     NeedOF = true;
9810     break;
9811   }
9812   // See if we can use the EFLAGS value from the operand instead of
9813   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9814   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9815   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9816     // Emit a CMP with 0, which is the TEST pattern.
9817     //if (Op.getValueType() == MVT::i1)
9818     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9819     //                     DAG.getConstant(0, MVT::i1));
9820     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9821                        DAG.getConstant(0, Op.getValueType()));
9822   }
9823   unsigned Opcode = 0;
9824   unsigned NumOperands = 0;
9825
9826   // Truncate operations may prevent the merge of the SETCC instruction
9827   // and the arithmetic instruction before it. Attempt to truncate the operands
9828   // of the arithmetic instruction and use a reduced bit-width instruction.
9829   bool NeedTruncation = false;
9830   SDValue ArithOp = Op;
9831   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9832     SDValue Arith = Op->getOperand(0);
9833     // Both the trunc and the arithmetic op need to have one user each.
9834     if (Arith->hasOneUse())
9835       switch (Arith.getOpcode()) {
9836         default: break;
9837         case ISD::ADD:
9838         case ISD::SUB:
9839         case ISD::AND:
9840         case ISD::OR:
9841         case ISD::XOR: {
9842           NeedTruncation = true;
9843           ArithOp = Arith;
9844         }
9845       }
9846   }
9847
9848   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9849   // which may be the result of a CAST.  We use the variable 'Op', which is the
9850   // non-casted variable when we check for possible users.
9851   switch (ArithOp.getOpcode()) {
9852   case ISD::ADD:
9853     // Due to an isel shortcoming, be conservative if this add is likely to be
9854     // selected as part of a load-modify-store instruction. When the root node
9855     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9856     // uses of other nodes in the match, such as the ADD in this case. This
9857     // leads to the ADD being left around and reselected, with the result being
9858     // two adds in the output.  Alas, even if none our users are stores, that
9859     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9860     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9861     // climbing the DAG back to the root, and it doesn't seem to be worth the
9862     // effort.
9863     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9864          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9865       if (UI->getOpcode() != ISD::CopyToReg &&
9866           UI->getOpcode() != ISD::SETCC &&
9867           UI->getOpcode() != ISD::STORE)
9868         goto default_case;
9869
9870     if (ConstantSDNode *C =
9871         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9872       // An add of one will be selected as an INC.
9873       if (C->getAPIntValue() == 1) {
9874         Opcode = X86ISD::INC;
9875         NumOperands = 1;
9876         break;
9877       }
9878
9879       // An add of negative one (subtract of one) will be selected as a DEC.
9880       if (C->getAPIntValue().isAllOnesValue()) {
9881         Opcode = X86ISD::DEC;
9882         NumOperands = 1;
9883         break;
9884       }
9885     }
9886
9887     // Otherwise use a regular EFLAGS-setting add.
9888     Opcode = X86ISD::ADD;
9889     NumOperands = 2;
9890     break;
9891   case ISD::SHL:
9892   case ISD::SRL:
9893     // If we have a constant logical shift that's only used in a comparison
9894     // against zero turn it into an equivalent AND. This allows turning it into
9895     // a TEST instruction later.
9896     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9897         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9898       EVT VT = Op.getValueType();
9899       unsigned BitWidth = VT.getSizeInBits();
9900       unsigned ShAmt = Op->getConstantOperandVal(1);
9901       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9902         break;
9903       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9904                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9905                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9906       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9907         break;
9908       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9909                                 DAG.getConstant(Mask, VT));
9910       DAG.ReplaceAllUsesWith(Op, New);
9911       Op = New;
9912     }
9913     break;
9914
9915   case ISD::AND:
9916     // If the primary and result isn't used, don't bother using X86ISD::AND,
9917     // because a TEST instruction will be better.
9918     if (!hasNonFlagsUse(Op))
9919       break;
9920     // FALL THROUGH
9921   case ISD::SUB:
9922   case ISD::OR:
9923   case ISD::XOR:
9924     // Due to the ISEL shortcoming noted above, be conservative if this op is
9925     // likely to be selected as part of a load-modify-store instruction.
9926     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9927            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9928       if (UI->getOpcode() == ISD::STORE)
9929         goto default_case;
9930
9931     // Otherwise use a regular EFLAGS-setting instruction.
9932     switch (ArithOp.getOpcode()) {
9933     default: llvm_unreachable("unexpected operator!");
9934     case ISD::SUB: Opcode = X86ISD::SUB; break;
9935     case ISD::XOR: Opcode = X86ISD::XOR; break;
9936     case ISD::AND: Opcode = X86ISD::AND; break;
9937     case ISD::OR: {
9938       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9939         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9940         if (EFLAGS.getNode())
9941           return EFLAGS;
9942       }
9943       Opcode = X86ISD::OR;
9944       break;
9945     }
9946     }
9947
9948     NumOperands = 2;
9949     break;
9950   case X86ISD::ADD:
9951   case X86ISD::SUB:
9952   case X86ISD::INC:
9953   case X86ISD::DEC:
9954   case X86ISD::OR:
9955   case X86ISD::XOR:
9956   case X86ISD::AND:
9957     return SDValue(Op.getNode(), 1);
9958   default:
9959   default_case:
9960     break;
9961   }
9962
9963   // If we found that truncation is beneficial, perform the truncation and
9964   // update 'Op'.
9965   if (NeedTruncation) {
9966     EVT VT = Op.getValueType();
9967     SDValue WideVal = Op->getOperand(0);
9968     EVT WideVT = WideVal.getValueType();
9969     unsigned ConvertedOp = 0;
9970     // Use a target machine opcode to prevent further DAGCombine
9971     // optimizations that may separate the arithmetic operations
9972     // from the setcc node.
9973     switch (WideVal.getOpcode()) {
9974       default: break;
9975       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9976       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9977       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9978       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9979       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9980     }
9981
9982     if (ConvertedOp) {
9983       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9984       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9985         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9986         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9987         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9988       }
9989     }
9990   }
9991
9992   if (Opcode == 0)
9993     // Emit a CMP with 0, which is the TEST pattern.
9994     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9995                        DAG.getConstant(0, Op.getValueType()));
9996
9997   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9998   SmallVector<SDValue, 4> Ops;
9999   for (unsigned i = 0; i != NumOperands; ++i)
10000     Ops.push_back(Op.getOperand(i));
10001
10002   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10003   DAG.ReplaceAllUsesWith(Op, New);
10004   return SDValue(New.getNode(), 1);
10005 }
10006
10007 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10008 /// equivalent.
10009 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10010                                    SDLoc dl, SelectionDAG &DAG) const {
10011   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10012     if (C->getAPIntValue() == 0)
10013       return EmitTest(Op0, X86CC, dl, DAG);
10014
10015      if (Op0.getValueType() == MVT::i1)
10016        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10017   }
10018  
10019   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10020        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10021     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10022     // This avoids subregister aliasing issues. Keep the smaller reference 
10023     // if we're optimizing for size, however, as that'll allow better folding 
10024     // of memory operations.
10025     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10026         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10027              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10028         !Subtarget->isAtom()) {
10029       unsigned ExtendOp =
10030           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10031       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10032       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10033     }
10034     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10035     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10036     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10037                               Op0, Op1);
10038     return SDValue(Sub.getNode(), 1);
10039   }
10040   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10041 }
10042
10043 /// Convert a comparison if required by the subtarget.
10044 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10045                                                  SelectionDAG &DAG) const {
10046   // If the subtarget does not support the FUCOMI instruction, floating-point
10047   // comparisons have to be converted.
10048   if (Subtarget->hasCMov() ||
10049       Cmp.getOpcode() != X86ISD::CMP ||
10050       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10051       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10052     return Cmp;
10053
10054   // The instruction selector will select an FUCOM instruction instead of
10055   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10056   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10057   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10058   SDLoc dl(Cmp);
10059   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10060   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10061   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10062                             DAG.getConstant(8, MVT::i8));
10063   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10064   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10065 }
10066
10067 static bool isAllOnes(SDValue V) {
10068   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10069   return C && C->isAllOnesValue();
10070 }
10071
10072 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10073 /// if it's possible.
10074 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10075                                      SDLoc dl, SelectionDAG &DAG) const {
10076   SDValue Op0 = And.getOperand(0);
10077   SDValue Op1 = And.getOperand(1);
10078   if (Op0.getOpcode() == ISD::TRUNCATE)
10079     Op0 = Op0.getOperand(0);
10080   if (Op1.getOpcode() == ISD::TRUNCATE)
10081     Op1 = Op1.getOperand(0);
10082
10083   SDValue LHS, RHS;
10084   if (Op1.getOpcode() == ISD::SHL)
10085     std::swap(Op0, Op1);
10086   if (Op0.getOpcode() == ISD::SHL) {
10087     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10088       if (And00C->getZExtValue() == 1) {
10089         // If we looked past a truncate, check that it's only truncating away
10090         // known zeros.
10091         unsigned BitWidth = Op0.getValueSizeInBits();
10092         unsigned AndBitWidth = And.getValueSizeInBits();
10093         if (BitWidth > AndBitWidth) {
10094           APInt Zeros, Ones;
10095           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10096           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10097             return SDValue();
10098         }
10099         LHS = Op1;
10100         RHS = Op0.getOperand(1);
10101       }
10102   } else if (Op1.getOpcode() == ISD::Constant) {
10103     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10104     uint64_t AndRHSVal = AndRHS->getZExtValue();
10105     SDValue AndLHS = Op0;
10106
10107     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10108       LHS = AndLHS.getOperand(0);
10109       RHS = AndLHS.getOperand(1);
10110     }
10111
10112     // Use BT if the immediate can't be encoded in a TEST instruction.
10113     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10114       LHS = AndLHS;
10115       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10116     }
10117   }
10118
10119   if (LHS.getNode()) {
10120     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10121     // instruction.  Since the shift amount is in-range-or-undefined, we know
10122     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10123     // the encoding for the i16 version is larger than the i32 version.
10124     // Also promote i16 to i32 for performance / code size reason.
10125     if (LHS.getValueType() == MVT::i8 ||
10126         LHS.getValueType() == MVT::i16)
10127       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10128
10129     // If the operand types disagree, extend the shift amount to match.  Since
10130     // BT ignores high bits (like shifts) we can use anyextend.
10131     if (LHS.getValueType() != RHS.getValueType())
10132       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10133
10134     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10135     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10136     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10137                        DAG.getConstant(Cond, MVT::i8), BT);
10138   }
10139
10140   return SDValue();
10141 }
10142
10143 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10144 /// mask CMPs.
10145 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10146                               SDValue &Op1) {
10147   unsigned SSECC;
10148   bool Swap = false;
10149
10150   // SSE Condition code mapping:
10151   //  0 - EQ
10152   //  1 - LT
10153   //  2 - LE
10154   //  3 - UNORD
10155   //  4 - NEQ
10156   //  5 - NLT
10157   //  6 - NLE
10158   //  7 - ORD
10159   switch (SetCCOpcode) {
10160   default: llvm_unreachable("Unexpected SETCC condition");
10161   case ISD::SETOEQ:
10162   case ISD::SETEQ:  SSECC = 0; break;
10163   case ISD::SETOGT:
10164   case ISD::SETGT:  Swap = true; // Fallthrough
10165   case ISD::SETLT:
10166   case ISD::SETOLT: SSECC = 1; break;
10167   case ISD::SETOGE:
10168   case ISD::SETGE:  Swap = true; // Fallthrough
10169   case ISD::SETLE:
10170   case ISD::SETOLE: SSECC = 2; break;
10171   case ISD::SETUO:  SSECC = 3; break;
10172   case ISD::SETUNE:
10173   case ISD::SETNE:  SSECC = 4; break;
10174   case ISD::SETULE: Swap = true; // Fallthrough
10175   case ISD::SETUGE: SSECC = 5; break;
10176   case ISD::SETULT: Swap = true; // Fallthrough
10177   case ISD::SETUGT: SSECC = 6; break;
10178   case ISD::SETO:   SSECC = 7; break;
10179   case ISD::SETUEQ:
10180   case ISD::SETONE: SSECC = 8; break;
10181   }
10182   if (Swap)
10183     std::swap(Op0, Op1);
10184
10185   return SSECC;
10186 }
10187
10188 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10189 // ones, and then concatenate the result back.
10190 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10191   MVT VT = Op.getSimpleValueType();
10192
10193   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10194          "Unsupported value type for operation");
10195
10196   unsigned NumElems = VT.getVectorNumElements();
10197   SDLoc dl(Op);
10198   SDValue CC = Op.getOperand(2);
10199
10200   // Extract the LHS vectors
10201   SDValue LHS = Op.getOperand(0);
10202   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10203   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10204
10205   // Extract the RHS vectors
10206   SDValue RHS = Op.getOperand(1);
10207   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10208   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10209
10210   // Issue the operation on the smaller types and concatenate the result back
10211   MVT EltVT = VT.getVectorElementType();
10212   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10213   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10214                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10215                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10216 }
10217
10218 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10219                                      const X86Subtarget *Subtarget) {
10220   SDValue Op0 = Op.getOperand(0);
10221   SDValue Op1 = Op.getOperand(1);
10222   SDValue CC = Op.getOperand(2);
10223   MVT VT = Op.getSimpleValueType();
10224   SDLoc dl(Op);
10225
10226   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10227          Op.getValueType().getScalarType() == MVT::i1 &&
10228          "Cannot set masked compare for this operation");
10229
10230   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10231   unsigned  Opc = 0;
10232   bool Unsigned = false;
10233   bool Swap = false;
10234   unsigned SSECC;
10235   switch (SetCCOpcode) {
10236   default: llvm_unreachable("Unexpected SETCC condition");
10237   case ISD::SETNE:  SSECC = 4; break;
10238   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10239   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10240   case ISD::SETLT:  Swap = true; //fall-through
10241   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10242   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10243   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10244   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10245   case ISD::SETULE: Unsigned = true; //fall-through
10246   case ISD::SETLE:  SSECC = 2; break;
10247   }
10248
10249   if (Swap)
10250     std::swap(Op0, Op1);
10251   if (Opc)
10252     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10253   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10254   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10255                      DAG.getConstant(SSECC, MVT::i8));
10256 }
10257
10258 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10259 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10260 /// return an empty value.
10261 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10262 {
10263   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10264   if (!BV)
10265     return SDValue();
10266
10267   MVT VT = Op1.getSimpleValueType();
10268   MVT EVT = VT.getVectorElementType();
10269   unsigned n = VT.getVectorNumElements();
10270   SmallVector<SDValue, 8> ULTOp1;
10271
10272   for (unsigned i = 0; i < n; ++i) {
10273     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10274     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10275       return SDValue();
10276
10277     // Avoid underflow.
10278     APInt Val = Elt->getAPIntValue();
10279     if (Val == 0)
10280       return SDValue();
10281
10282     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10283   }
10284
10285   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10286 }
10287
10288 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10289                            SelectionDAG &DAG) {
10290   SDValue Op0 = Op.getOperand(0);
10291   SDValue Op1 = Op.getOperand(1);
10292   SDValue CC = Op.getOperand(2);
10293   MVT VT = Op.getSimpleValueType();
10294   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10295   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10296   SDLoc dl(Op);
10297
10298   if (isFP) {
10299 #ifndef NDEBUG
10300     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10301     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10302 #endif
10303
10304     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10305     unsigned Opc = X86ISD::CMPP;
10306     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10307       assert(VT.getVectorNumElements() <= 16);
10308       Opc = X86ISD::CMPM;
10309     }
10310     // In the two special cases we can't handle, emit two comparisons.
10311     if (SSECC == 8) {
10312       unsigned CC0, CC1;
10313       unsigned CombineOpc;
10314       if (SetCCOpcode == ISD::SETUEQ) {
10315         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10316       } else {
10317         assert(SetCCOpcode == ISD::SETONE);
10318         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10319       }
10320
10321       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10322                                  DAG.getConstant(CC0, MVT::i8));
10323       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10324                                  DAG.getConstant(CC1, MVT::i8));
10325       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10326     }
10327     // Handle all other FP comparisons here.
10328     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10329                        DAG.getConstant(SSECC, MVT::i8));
10330   }
10331
10332   // Break 256-bit integer vector compare into smaller ones.
10333   if (VT.is256BitVector() && !Subtarget->hasInt256())
10334     return Lower256IntVSETCC(Op, DAG);
10335
10336   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10337   EVT OpVT = Op1.getValueType();
10338   if (Subtarget->hasAVX512()) {
10339     if (Op1.getValueType().is512BitVector() ||
10340         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10341       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10342
10343     // In AVX-512 architecture setcc returns mask with i1 elements,
10344     // But there is no compare instruction for i8 and i16 elements.
10345     // We are not talking about 512-bit operands in this case, these
10346     // types are illegal.
10347     if (MaskResult &&
10348         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10349          OpVT.getVectorElementType().getSizeInBits() >= 8))
10350       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10351                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10352   }
10353
10354   // We are handling one of the integer comparisons here.  Since SSE only has
10355   // GT and EQ comparisons for integer, swapping operands and multiple
10356   // operations may be required for some comparisons.
10357   unsigned Opc;
10358   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10359   bool Subus = false;
10360
10361   switch (SetCCOpcode) {
10362   default: llvm_unreachable("Unexpected SETCC condition");
10363   case ISD::SETNE:  Invert = true;
10364   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10365   case ISD::SETLT:  Swap = true;
10366   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10367   case ISD::SETGE:  Swap = true;
10368   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10369                     Invert = true; break;
10370   case ISD::SETULT: Swap = true;
10371   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10372                     FlipSigns = true; break;
10373   case ISD::SETUGE: Swap = true;
10374   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10375                     FlipSigns = true; Invert = true; break;
10376   }
10377
10378   // Special case: Use min/max operations for SETULE/SETUGE
10379   MVT VET = VT.getVectorElementType();
10380   bool hasMinMax =
10381        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10382     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10383
10384   if (hasMinMax) {
10385     switch (SetCCOpcode) {
10386     default: break;
10387     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10388     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10389     }
10390
10391     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10392   }
10393
10394   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10395   if (!MinMax && hasSubus) {
10396     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10397     // Op0 u<= Op1:
10398     //   t = psubus Op0, Op1
10399     //   pcmpeq t, <0..0>
10400     switch (SetCCOpcode) {
10401     default: break;
10402     case ISD::SETULT: {
10403       // If the comparison is against a constant we can turn this into a
10404       // setule.  With psubus, setule does not require a swap.  This is
10405       // beneficial because the constant in the register is no longer
10406       // destructed as the destination so it can be hoisted out of a loop.
10407       // Only do this pre-AVX since vpcmp* is no longer destructive.
10408       if (Subtarget->hasAVX())
10409         break;
10410       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10411       if (ULEOp1.getNode()) {
10412         Op1 = ULEOp1;
10413         Subus = true; Invert = false; Swap = false;
10414       }
10415       break;
10416     }
10417     // Psubus is better than flip-sign because it requires no inversion.
10418     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10419     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10420     }
10421
10422     if (Subus) {
10423       Opc = X86ISD::SUBUS;
10424       FlipSigns = false;
10425     }
10426   }
10427
10428   if (Swap)
10429     std::swap(Op0, Op1);
10430
10431   // Check that the operation in question is available (most are plain SSE2,
10432   // but PCMPGTQ and PCMPEQQ have different requirements).
10433   if (VT == MVT::v2i64) {
10434     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10435       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10436
10437       // First cast everything to the right type.
10438       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10439       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10440
10441       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10442       // bits of the inputs before performing those operations. The lower
10443       // compare is always unsigned.
10444       SDValue SB;
10445       if (FlipSigns) {
10446         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10447       } else {
10448         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10449         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10450         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10451                          Sign, Zero, Sign, Zero);
10452       }
10453       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10454       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10455
10456       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10457       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10458       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10459
10460       // Create masks for only the low parts/high parts of the 64 bit integers.
10461       static const int MaskHi[] = { 1, 1, 3, 3 };
10462       static const int MaskLo[] = { 0, 0, 2, 2 };
10463       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10464       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10465       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10466
10467       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10468       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10469
10470       if (Invert)
10471         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10472
10473       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10474     }
10475
10476     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10477       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10478       // pcmpeqd + pshufd + pand.
10479       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10480
10481       // First cast everything to the right type.
10482       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10483       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10484
10485       // Do the compare.
10486       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10487
10488       // Make sure the lower and upper halves are both all-ones.
10489       static const int Mask[] = { 1, 0, 3, 2 };
10490       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10491       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10492
10493       if (Invert)
10494         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10495
10496       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10497     }
10498   }
10499
10500   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10501   // bits of the inputs before performing those operations.
10502   if (FlipSigns) {
10503     EVT EltVT = VT.getVectorElementType();
10504     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10505     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10506     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10507   }
10508
10509   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10510
10511   // If the logical-not of the result is required, perform that now.
10512   if (Invert)
10513     Result = DAG.getNOT(dl, Result, VT);
10514
10515   if (MinMax)
10516     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10517
10518   if (Subus)
10519     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10520                          getZeroVector(VT, Subtarget, DAG, dl));
10521
10522   return Result;
10523 }
10524
10525 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10526
10527   MVT VT = Op.getSimpleValueType();
10528
10529   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10530
10531   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10532          && "SetCC type must be 8-bit or 1-bit integer");
10533   SDValue Op0 = Op.getOperand(0);
10534   SDValue Op1 = Op.getOperand(1);
10535   SDLoc dl(Op);
10536   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10537
10538   // Optimize to BT if possible.
10539   // Lower (X & (1 << N)) == 0 to BT(X, N).
10540   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10541   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10542   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10543       Op1.getOpcode() == ISD::Constant &&
10544       cast<ConstantSDNode>(Op1)->isNullValue() &&
10545       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10546     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10547     if (NewSetCC.getNode())
10548       return NewSetCC;
10549   }
10550
10551   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10552   // these.
10553   if (Op1.getOpcode() == ISD::Constant &&
10554       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10555        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10556       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10557
10558     // If the input is a setcc, then reuse the input setcc or use a new one with
10559     // the inverted condition.
10560     if (Op0.getOpcode() == X86ISD::SETCC) {
10561       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10562       bool Invert = (CC == ISD::SETNE) ^
10563         cast<ConstantSDNode>(Op1)->isNullValue();
10564       if (!Invert)
10565         return Op0;
10566
10567       CCode = X86::GetOppositeBranchCondition(CCode);
10568       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10569                                   DAG.getConstant(CCode, MVT::i8),
10570                                   Op0.getOperand(1));
10571       if (VT == MVT::i1)
10572         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10573       return SetCC;
10574     }
10575   }
10576   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10577       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10578       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10579
10580     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10581     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10582   }
10583
10584   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10585   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10586   if (X86CC == X86::COND_INVALID)
10587     return SDValue();
10588
10589   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10590   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10591   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10592                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10593   if (VT == MVT::i1)
10594     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10595   return SetCC;
10596 }
10597
10598 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10599 static bool isX86LogicalCmp(SDValue Op) {
10600   unsigned Opc = Op.getNode()->getOpcode();
10601   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10602       Opc == X86ISD::SAHF)
10603     return true;
10604   if (Op.getResNo() == 1 &&
10605       (Opc == X86ISD::ADD ||
10606        Opc == X86ISD::SUB ||
10607        Opc == X86ISD::ADC ||
10608        Opc == X86ISD::SBB ||
10609        Opc == X86ISD::SMUL ||
10610        Opc == X86ISD::UMUL ||
10611        Opc == X86ISD::INC ||
10612        Opc == X86ISD::DEC ||
10613        Opc == X86ISD::OR ||
10614        Opc == X86ISD::XOR ||
10615        Opc == X86ISD::AND))
10616     return true;
10617
10618   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10619     return true;
10620
10621   return false;
10622 }
10623
10624 static bool isZero(SDValue V) {
10625   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10626   return C && C->isNullValue();
10627 }
10628
10629 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10630   if (V.getOpcode() != ISD::TRUNCATE)
10631     return false;
10632
10633   SDValue VOp0 = V.getOperand(0);
10634   unsigned InBits = VOp0.getValueSizeInBits();
10635   unsigned Bits = V.getValueSizeInBits();
10636   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10637 }
10638
10639 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10640   bool addTest = true;
10641   SDValue Cond  = Op.getOperand(0);
10642   SDValue Op1 = Op.getOperand(1);
10643   SDValue Op2 = Op.getOperand(2);
10644   SDLoc DL(Op);
10645   EVT VT = Op1.getValueType();
10646   SDValue CC;
10647
10648   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10649   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10650   // sequence later on.
10651   if (Cond.getOpcode() == ISD::SETCC &&
10652       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10653        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10654       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10655     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10656     int SSECC = translateX86FSETCC(
10657         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10658
10659     if (SSECC != 8) {
10660       if (Subtarget->hasAVX512()) {
10661         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10662                                   DAG.getConstant(SSECC, MVT::i8));
10663         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10664       }
10665       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10666                                 DAG.getConstant(SSECC, MVT::i8));
10667       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10668       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10669       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10670     }
10671   }
10672
10673   if (Cond.getOpcode() == ISD::SETCC) {
10674     SDValue NewCond = LowerSETCC(Cond, DAG);
10675     if (NewCond.getNode())
10676       Cond = NewCond;
10677   }
10678
10679   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10680   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10681   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10682   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10683   if (Cond.getOpcode() == X86ISD::SETCC &&
10684       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10685       isZero(Cond.getOperand(1).getOperand(1))) {
10686     SDValue Cmp = Cond.getOperand(1);
10687
10688     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10689
10690     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10691         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10692       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10693
10694       SDValue CmpOp0 = Cmp.getOperand(0);
10695       // Apply further optimizations for special cases
10696       // (select (x != 0), -1, 0) -> neg & sbb
10697       // (select (x == 0), 0, -1) -> neg & sbb
10698       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10699         if (YC->isNullValue() &&
10700             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10701           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10702           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10703                                     DAG.getConstant(0, CmpOp0.getValueType()),
10704                                     CmpOp0);
10705           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10706                                     DAG.getConstant(X86::COND_B, MVT::i8),
10707                                     SDValue(Neg.getNode(), 1));
10708           return Res;
10709         }
10710
10711       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10712                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10713       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10714
10715       SDValue Res =   // Res = 0 or -1.
10716         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10717                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10718
10719       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10720         Res = DAG.getNOT(DL, Res, Res.getValueType());
10721
10722       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10723       if (!N2C || !N2C->isNullValue())
10724         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10725       return Res;
10726     }
10727   }
10728
10729   // Look past (and (setcc_carry (cmp ...)), 1).
10730   if (Cond.getOpcode() == ISD::AND &&
10731       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10732     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10733     if (C && C->getAPIntValue() == 1)
10734       Cond = Cond.getOperand(0);
10735   }
10736
10737   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10738   // setting operand in place of the X86ISD::SETCC.
10739   unsigned CondOpcode = Cond.getOpcode();
10740   if (CondOpcode == X86ISD::SETCC ||
10741       CondOpcode == X86ISD::SETCC_CARRY) {
10742     CC = Cond.getOperand(0);
10743
10744     SDValue Cmp = Cond.getOperand(1);
10745     unsigned Opc = Cmp.getOpcode();
10746     MVT VT = Op.getSimpleValueType();
10747
10748     bool IllegalFPCMov = false;
10749     if (VT.isFloatingPoint() && !VT.isVector() &&
10750         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10751       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10752
10753     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10754         Opc == X86ISD::BT) { // FIXME
10755       Cond = Cmp;
10756       addTest = false;
10757     }
10758   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10759              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10760              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10761               Cond.getOperand(0).getValueType() != MVT::i8)) {
10762     SDValue LHS = Cond.getOperand(0);
10763     SDValue RHS = Cond.getOperand(1);
10764     unsigned X86Opcode;
10765     unsigned X86Cond;
10766     SDVTList VTs;
10767     switch (CondOpcode) {
10768     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10769     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10770     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10771     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10772     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10773     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10774     default: llvm_unreachable("unexpected overflowing operator");
10775     }
10776     if (CondOpcode == ISD::UMULO)
10777       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10778                           MVT::i32);
10779     else
10780       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10781
10782     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10783
10784     if (CondOpcode == ISD::UMULO)
10785       Cond = X86Op.getValue(2);
10786     else
10787       Cond = X86Op.getValue(1);
10788
10789     CC = DAG.getConstant(X86Cond, MVT::i8);
10790     addTest = false;
10791   }
10792
10793   if (addTest) {
10794     // Look pass the truncate if the high bits are known zero.
10795     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10796         Cond = Cond.getOperand(0);
10797
10798     // We know the result of AND is compared against zero. Try to match
10799     // it to BT.
10800     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10801       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10802       if (NewSetCC.getNode()) {
10803         CC = NewSetCC.getOperand(0);
10804         Cond = NewSetCC.getOperand(1);
10805         addTest = false;
10806       }
10807     }
10808   }
10809
10810   if (addTest) {
10811     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10812     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10813   }
10814
10815   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10816   // a <  b ?  0 : -1 -> RES = setcc_carry
10817   // a >= b ? -1 :  0 -> RES = setcc_carry
10818   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10819   if (Cond.getOpcode() == X86ISD::SUB) {
10820     Cond = ConvertCmpIfNecessary(Cond, DAG);
10821     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10822
10823     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10824         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10825       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10826                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10827       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10828         return DAG.getNOT(DL, Res, Res.getValueType());
10829       return Res;
10830     }
10831   }
10832
10833   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10834   // widen the cmov and push the truncate through. This avoids introducing a new
10835   // branch during isel and doesn't add any extensions.
10836   if (Op.getValueType() == MVT::i8 &&
10837       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10838     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10839     if (T1.getValueType() == T2.getValueType() &&
10840         // Blacklist CopyFromReg to avoid partial register stalls.
10841         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10842       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10843       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10844       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10845     }
10846   }
10847
10848   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10849   // condition is true.
10850   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10851   SDValue Ops[] = { Op2, Op1, CC, Cond };
10852   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10853 }
10854
10855 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10856   MVT VT = Op->getSimpleValueType(0);
10857   SDValue In = Op->getOperand(0);
10858   MVT InVT = In.getSimpleValueType();
10859   SDLoc dl(Op);
10860
10861   unsigned int NumElts = VT.getVectorNumElements();
10862   if (NumElts != 8 && NumElts != 16)
10863     return SDValue();
10864
10865   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10866     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10867
10868   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10869   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10870
10871   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10872   Constant *C = ConstantInt::get(*DAG.getContext(),
10873     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10874
10875   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10876   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10877   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10878                           MachinePointerInfo::getConstantPool(),
10879                           false, false, false, Alignment);
10880   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10881   if (VT.is512BitVector())
10882     return Brcst;
10883   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10884 }
10885
10886 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10887                                 SelectionDAG &DAG) {
10888   MVT VT = Op->getSimpleValueType(0);
10889   SDValue In = Op->getOperand(0);
10890   MVT InVT = In.getSimpleValueType();
10891   SDLoc dl(Op);
10892
10893   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10894     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10895
10896   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10897       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10898       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10899     return SDValue();
10900
10901   if (Subtarget->hasInt256())
10902     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10903
10904   // Optimize vectors in AVX mode
10905   // Sign extend  v8i16 to v8i32 and
10906   //              v4i32 to v4i64
10907   //
10908   // Divide input vector into two parts
10909   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10910   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10911   // concat the vectors to original VT
10912
10913   unsigned NumElems = InVT.getVectorNumElements();
10914   SDValue Undef = DAG.getUNDEF(InVT);
10915
10916   SmallVector<int,8> ShufMask1(NumElems, -1);
10917   for (unsigned i = 0; i != NumElems/2; ++i)
10918     ShufMask1[i] = i;
10919
10920   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10921
10922   SmallVector<int,8> ShufMask2(NumElems, -1);
10923   for (unsigned i = 0; i != NumElems/2; ++i)
10924     ShufMask2[i] = i + NumElems/2;
10925
10926   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10927
10928   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10929                                 VT.getVectorNumElements()/2);
10930
10931   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10932   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10933
10934   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10935 }
10936
10937 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10938 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10939 // from the AND / OR.
10940 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10941   Opc = Op.getOpcode();
10942   if (Opc != ISD::OR && Opc != ISD::AND)
10943     return false;
10944   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10945           Op.getOperand(0).hasOneUse() &&
10946           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10947           Op.getOperand(1).hasOneUse());
10948 }
10949
10950 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10951 // 1 and that the SETCC node has a single use.
10952 static bool isXor1OfSetCC(SDValue Op) {
10953   if (Op.getOpcode() != ISD::XOR)
10954     return false;
10955   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10956   if (N1C && N1C->getAPIntValue() == 1) {
10957     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10958       Op.getOperand(0).hasOneUse();
10959   }
10960   return false;
10961 }
10962
10963 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10964   bool addTest = true;
10965   SDValue Chain = Op.getOperand(0);
10966   SDValue Cond  = Op.getOperand(1);
10967   SDValue Dest  = Op.getOperand(2);
10968   SDLoc dl(Op);
10969   SDValue CC;
10970   bool Inverted = false;
10971
10972   if (Cond.getOpcode() == ISD::SETCC) {
10973     // Check for setcc([su]{add,sub,mul}o == 0).
10974     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10975         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10976         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10977         Cond.getOperand(0).getResNo() == 1 &&
10978         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10979          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10980          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10981          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10982          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10983          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10984       Inverted = true;
10985       Cond = Cond.getOperand(0);
10986     } else {
10987       SDValue NewCond = LowerSETCC(Cond, DAG);
10988       if (NewCond.getNode())
10989         Cond = NewCond;
10990     }
10991   }
10992 #if 0
10993   // FIXME: LowerXALUO doesn't handle these!!
10994   else if (Cond.getOpcode() == X86ISD::ADD  ||
10995            Cond.getOpcode() == X86ISD::SUB  ||
10996            Cond.getOpcode() == X86ISD::SMUL ||
10997            Cond.getOpcode() == X86ISD::UMUL)
10998     Cond = LowerXALUO(Cond, DAG);
10999 #endif
11000
11001   // Look pass (and (setcc_carry (cmp ...)), 1).
11002   if (Cond.getOpcode() == ISD::AND &&
11003       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11004     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11005     if (C && C->getAPIntValue() == 1)
11006       Cond = Cond.getOperand(0);
11007   }
11008
11009   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11010   // setting operand in place of the X86ISD::SETCC.
11011   unsigned CondOpcode = Cond.getOpcode();
11012   if (CondOpcode == X86ISD::SETCC ||
11013       CondOpcode == X86ISD::SETCC_CARRY) {
11014     CC = Cond.getOperand(0);
11015
11016     SDValue Cmp = Cond.getOperand(1);
11017     unsigned Opc = Cmp.getOpcode();
11018     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11019     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11020       Cond = Cmp;
11021       addTest = false;
11022     } else {
11023       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11024       default: break;
11025       case X86::COND_O:
11026       case X86::COND_B:
11027         // These can only come from an arithmetic instruction with overflow,
11028         // e.g. SADDO, UADDO.
11029         Cond = Cond.getNode()->getOperand(1);
11030         addTest = false;
11031         break;
11032       }
11033     }
11034   }
11035   CondOpcode = Cond.getOpcode();
11036   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11037       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11038       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11039        Cond.getOperand(0).getValueType() != MVT::i8)) {
11040     SDValue LHS = Cond.getOperand(0);
11041     SDValue RHS = Cond.getOperand(1);
11042     unsigned X86Opcode;
11043     unsigned X86Cond;
11044     SDVTList VTs;
11045     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11046     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11047     // X86ISD::INC).
11048     switch (CondOpcode) {
11049     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11050     case ISD::SADDO:
11051       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11052         if (C->isOne()) {
11053           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11054           break;
11055         }
11056       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11057     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11058     case ISD::SSUBO:
11059       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11060         if (C->isOne()) {
11061           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11062           break;
11063         }
11064       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11065     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11066     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11067     default: llvm_unreachable("unexpected overflowing operator");
11068     }
11069     if (Inverted)
11070       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11071     if (CondOpcode == ISD::UMULO)
11072       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11073                           MVT::i32);
11074     else
11075       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11076
11077     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11078
11079     if (CondOpcode == ISD::UMULO)
11080       Cond = X86Op.getValue(2);
11081     else
11082       Cond = X86Op.getValue(1);
11083
11084     CC = DAG.getConstant(X86Cond, MVT::i8);
11085     addTest = false;
11086   } else {
11087     unsigned CondOpc;
11088     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11089       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11090       if (CondOpc == ISD::OR) {
11091         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11092         // two branches instead of an explicit OR instruction with a
11093         // separate test.
11094         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11095             isX86LogicalCmp(Cmp)) {
11096           CC = Cond.getOperand(0).getOperand(0);
11097           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11098                               Chain, Dest, CC, Cmp);
11099           CC = Cond.getOperand(1).getOperand(0);
11100           Cond = Cmp;
11101           addTest = false;
11102         }
11103       } else { // ISD::AND
11104         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11105         // two branches instead of an explicit AND instruction with a
11106         // separate test. However, we only do this if this block doesn't
11107         // have a fall-through edge, because this requires an explicit
11108         // jmp when the condition is false.
11109         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11110             isX86LogicalCmp(Cmp) &&
11111             Op.getNode()->hasOneUse()) {
11112           X86::CondCode CCode =
11113             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11114           CCode = X86::GetOppositeBranchCondition(CCode);
11115           CC = DAG.getConstant(CCode, MVT::i8);
11116           SDNode *User = *Op.getNode()->use_begin();
11117           // Look for an unconditional branch following this conditional branch.
11118           // We need this because we need to reverse the successors in order
11119           // to implement FCMP_OEQ.
11120           if (User->getOpcode() == ISD::BR) {
11121             SDValue FalseBB = User->getOperand(1);
11122             SDNode *NewBR =
11123               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11124             assert(NewBR == User);
11125             (void)NewBR;
11126             Dest = FalseBB;
11127
11128             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11129                                 Chain, Dest, CC, Cmp);
11130             X86::CondCode CCode =
11131               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11132             CCode = X86::GetOppositeBranchCondition(CCode);
11133             CC = DAG.getConstant(CCode, MVT::i8);
11134             Cond = Cmp;
11135             addTest = false;
11136           }
11137         }
11138       }
11139     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11140       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11141       // It should be transformed during dag combiner except when the condition
11142       // is set by a arithmetics with overflow node.
11143       X86::CondCode CCode =
11144         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11145       CCode = X86::GetOppositeBranchCondition(CCode);
11146       CC = DAG.getConstant(CCode, MVT::i8);
11147       Cond = Cond.getOperand(0).getOperand(1);
11148       addTest = false;
11149     } else if (Cond.getOpcode() == ISD::SETCC &&
11150                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11151       // For FCMP_OEQ, we can emit
11152       // two branches instead of an explicit AND instruction with a
11153       // separate test. However, we only do this if this block doesn't
11154       // have a fall-through edge, because this requires an explicit
11155       // jmp when the condition is false.
11156       if (Op.getNode()->hasOneUse()) {
11157         SDNode *User = *Op.getNode()->use_begin();
11158         // Look for an unconditional branch following this conditional branch.
11159         // We need this because we need to reverse the successors in order
11160         // to implement FCMP_OEQ.
11161         if (User->getOpcode() == ISD::BR) {
11162           SDValue FalseBB = User->getOperand(1);
11163           SDNode *NewBR =
11164             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11165           assert(NewBR == User);
11166           (void)NewBR;
11167           Dest = FalseBB;
11168
11169           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11170                                     Cond.getOperand(0), Cond.getOperand(1));
11171           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11172           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11173           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11174                               Chain, Dest, CC, Cmp);
11175           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11176           Cond = Cmp;
11177           addTest = false;
11178         }
11179       }
11180     } else if (Cond.getOpcode() == ISD::SETCC &&
11181                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11182       // For FCMP_UNE, we can emit
11183       // two branches instead of an explicit AND instruction with a
11184       // separate test. However, we only do this if this block doesn't
11185       // have a fall-through edge, because this requires an explicit
11186       // jmp when the condition is false.
11187       if (Op.getNode()->hasOneUse()) {
11188         SDNode *User = *Op.getNode()->use_begin();
11189         // Look for an unconditional branch following this conditional branch.
11190         // We need this because we need to reverse the successors in order
11191         // to implement FCMP_UNE.
11192         if (User->getOpcode() == ISD::BR) {
11193           SDValue FalseBB = User->getOperand(1);
11194           SDNode *NewBR =
11195             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11196           assert(NewBR == User);
11197           (void)NewBR;
11198
11199           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11200                                     Cond.getOperand(0), Cond.getOperand(1));
11201           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11202           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11203           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11204                               Chain, Dest, CC, Cmp);
11205           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11206           Cond = Cmp;
11207           addTest = false;
11208           Dest = FalseBB;
11209         }
11210       }
11211     }
11212   }
11213
11214   if (addTest) {
11215     // Look pass the truncate if the high bits are known zero.
11216     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11217         Cond = Cond.getOperand(0);
11218
11219     // We know the result of AND is compared against zero. Try to match
11220     // it to BT.
11221     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11222       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11223       if (NewSetCC.getNode()) {
11224         CC = NewSetCC.getOperand(0);
11225         Cond = NewSetCC.getOperand(1);
11226         addTest = false;
11227       }
11228     }
11229   }
11230
11231   if (addTest) {
11232     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11233     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11234   }
11235   Cond = ConvertCmpIfNecessary(Cond, DAG);
11236   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11237                      Chain, Dest, CC, Cond);
11238 }
11239
11240 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11241 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11242 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11243 // that the guard pages used by the OS virtual memory manager are allocated in
11244 // correct sequence.
11245 SDValue
11246 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11247                                            SelectionDAG &DAG) const {
11248   MachineFunction &MF = DAG.getMachineFunction();
11249   bool SplitStack = MF.shouldSplitStack();
11250   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11251                SplitStack;
11252   SDLoc dl(Op);
11253
11254   if (!Lower) {
11255     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11256     SDNode* Node = Op.getNode();
11257
11258     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11259     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11260         " not tell us which reg is the stack pointer!");
11261     EVT VT = Node->getValueType(0);
11262     SDValue Tmp1 = SDValue(Node, 0);
11263     SDValue Tmp2 = SDValue(Node, 1);
11264     SDValue Tmp3 = Node->getOperand(2);
11265     SDValue Chain = Tmp1.getOperand(0);
11266
11267     // Chain the dynamic stack allocation so that it doesn't modify the stack
11268     // pointer when other instructions are using the stack.
11269     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11270         SDLoc(Node));
11271
11272     SDValue Size = Tmp2.getOperand(1);
11273     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11274     Chain = SP.getValue(1);
11275     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11276     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11277     unsigned StackAlign = TFI.getStackAlignment();
11278     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11279     if (Align > StackAlign)
11280       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11281           DAG.getConstant(-(uint64_t)Align, VT));
11282     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11283
11284     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11285         DAG.getIntPtrConstant(0, true), SDValue(),
11286         SDLoc(Node));
11287
11288     SDValue Ops[2] = { Tmp1, Tmp2 };
11289     return DAG.getMergeValues(Ops, 2, dl);
11290   }
11291
11292   // Get the inputs.
11293   SDValue Chain = Op.getOperand(0);
11294   SDValue Size  = Op.getOperand(1);
11295   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11296   EVT VT = Op.getNode()->getValueType(0);
11297
11298   bool Is64Bit = Subtarget->is64Bit();
11299   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11300
11301   if (SplitStack) {
11302     MachineRegisterInfo &MRI = MF.getRegInfo();
11303
11304     if (Is64Bit) {
11305       // The 64 bit implementation of segmented stacks needs to clobber both r10
11306       // r11. This makes it impossible to use it along with nested parameters.
11307       const Function *F = MF.getFunction();
11308
11309       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11310            I != E; ++I)
11311         if (I->hasNestAttr())
11312           report_fatal_error("Cannot use segmented stacks with functions that "
11313                              "have nested arguments.");
11314     }
11315
11316     const TargetRegisterClass *AddrRegClass =
11317       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11318     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11319     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11320     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11321                                 DAG.getRegister(Vreg, SPTy));
11322     SDValue Ops1[2] = { Value, Chain };
11323     return DAG.getMergeValues(Ops1, 2, dl);
11324   } else {
11325     SDValue Flag;
11326     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11327
11328     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11329     Flag = Chain.getValue(1);
11330     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11331
11332     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11333
11334     const X86RegisterInfo *RegInfo =
11335       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11336     unsigned SPReg = RegInfo->getStackRegister();
11337     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11338     Chain = SP.getValue(1);
11339
11340     if (Align) {
11341       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11342                        DAG.getConstant(-(uint64_t)Align, VT));
11343       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11344     }
11345
11346     SDValue Ops1[2] = { SP, Chain };
11347     return DAG.getMergeValues(Ops1, 2, dl);
11348   }
11349 }
11350
11351 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11352   MachineFunction &MF = DAG.getMachineFunction();
11353   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11354
11355   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11356   SDLoc DL(Op);
11357
11358   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11359     // vastart just stores the address of the VarArgsFrameIndex slot into the
11360     // memory location argument.
11361     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11362                                    getPointerTy());
11363     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11364                         MachinePointerInfo(SV), false, false, 0);
11365   }
11366
11367   // __va_list_tag:
11368   //   gp_offset         (0 - 6 * 8)
11369   //   fp_offset         (48 - 48 + 8 * 16)
11370   //   overflow_arg_area (point to parameters coming in memory).
11371   //   reg_save_area
11372   SmallVector<SDValue, 8> MemOps;
11373   SDValue FIN = Op.getOperand(1);
11374   // Store gp_offset
11375   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11376                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11377                                                MVT::i32),
11378                                FIN, MachinePointerInfo(SV), false, false, 0);
11379   MemOps.push_back(Store);
11380
11381   // Store fp_offset
11382   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11383                     FIN, DAG.getIntPtrConstant(4));
11384   Store = DAG.getStore(Op.getOperand(0), DL,
11385                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11386                                        MVT::i32),
11387                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11388   MemOps.push_back(Store);
11389
11390   // Store ptr to overflow_arg_area
11391   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11392                     FIN, DAG.getIntPtrConstant(4));
11393   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11394                                     getPointerTy());
11395   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11396                        MachinePointerInfo(SV, 8),
11397                        false, false, 0);
11398   MemOps.push_back(Store);
11399
11400   // Store ptr to reg_save_area.
11401   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11402                     FIN, DAG.getIntPtrConstant(8));
11403   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11404                                     getPointerTy());
11405   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11406                        MachinePointerInfo(SV, 16), false, false, 0);
11407   MemOps.push_back(Store);
11408   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11409 }
11410
11411 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11412   assert(Subtarget->is64Bit() &&
11413          "LowerVAARG only handles 64-bit va_arg!");
11414   assert((Subtarget->isTargetLinux() ||
11415           Subtarget->isTargetDarwin()) &&
11416           "Unhandled target in LowerVAARG");
11417   assert(Op.getNode()->getNumOperands() == 4);
11418   SDValue Chain = Op.getOperand(0);
11419   SDValue SrcPtr = Op.getOperand(1);
11420   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11421   unsigned Align = Op.getConstantOperandVal(3);
11422   SDLoc dl(Op);
11423
11424   EVT ArgVT = Op.getNode()->getValueType(0);
11425   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11426   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11427   uint8_t ArgMode;
11428
11429   // Decide which area this value should be read from.
11430   // TODO: Implement the AMD64 ABI in its entirety. This simple
11431   // selection mechanism works only for the basic types.
11432   if (ArgVT == MVT::f80) {
11433     llvm_unreachable("va_arg for f80 not yet implemented");
11434   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11435     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11436   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11437     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11438   } else {
11439     llvm_unreachable("Unhandled argument type in LowerVAARG");
11440   }
11441
11442   if (ArgMode == 2) {
11443     // Sanity Check: Make sure using fp_offset makes sense.
11444     assert(!getTargetMachine().Options.UseSoftFloat &&
11445            !(DAG.getMachineFunction()
11446                 .getFunction()->getAttributes()
11447                 .hasAttribute(AttributeSet::FunctionIndex,
11448                               Attribute::NoImplicitFloat)) &&
11449            Subtarget->hasSSE1());
11450   }
11451
11452   // Insert VAARG_64 node into the DAG
11453   // VAARG_64 returns two values: Variable Argument Address, Chain
11454   SmallVector<SDValue, 11> InstOps;
11455   InstOps.push_back(Chain);
11456   InstOps.push_back(SrcPtr);
11457   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11458   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11459   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11460   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11461   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11462                                           VTs, &InstOps[0], InstOps.size(),
11463                                           MVT::i64,
11464                                           MachinePointerInfo(SV),
11465                                           /*Align=*/0,
11466                                           /*Volatile=*/false,
11467                                           /*ReadMem=*/true,
11468                                           /*WriteMem=*/true);
11469   Chain = VAARG.getValue(1);
11470
11471   // Load the next argument and return it
11472   return DAG.getLoad(ArgVT, dl,
11473                      Chain,
11474                      VAARG,
11475                      MachinePointerInfo(),
11476                      false, false, false, 0);
11477 }
11478
11479 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11480                            SelectionDAG &DAG) {
11481   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11482   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11483   SDValue Chain = Op.getOperand(0);
11484   SDValue DstPtr = Op.getOperand(1);
11485   SDValue SrcPtr = Op.getOperand(2);
11486   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11487   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11488   SDLoc DL(Op);
11489
11490   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11491                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11492                        false,
11493                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11494 }
11495
11496 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11497 // amount is a constant. Takes immediate version of shift as input.
11498 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11499                                           SDValue SrcOp, uint64_t ShiftAmt,
11500                                           SelectionDAG &DAG) {
11501   MVT ElementType = VT.getVectorElementType();
11502
11503   // Check for ShiftAmt >= element width
11504   if (ShiftAmt >= ElementType.getSizeInBits()) {
11505     if (Opc == X86ISD::VSRAI)
11506       ShiftAmt = ElementType.getSizeInBits() - 1;
11507     else
11508       return DAG.getConstant(0, VT);
11509   }
11510
11511   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11512          && "Unknown target vector shift-by-constant node");
11513
11514   // Fold this packed vector shift into a build vector if SrcOp is a
11515   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11516   if (VT == SrcOp.getSimpleValueType() &&
11517       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11518     SmallVector<SDValue, 8> Elts;
11519     unsigned NumElts = SrcOp->getNumOperands();
11520     ConstantSDNode *ND;
11521
11522     switch(Opc) {
11523     default: llvm_unreachable(0);
11524     case X86ISD::VSHLI:
11525       for (unsigned i=0; i!=NumElts; ++i) {
11526         SDValue CurrentOp = SrcOp->getOperand(i);
11527         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11528           Elts.push_back(CurrentOp);
11529           continue;
11530         }
11531         ND = cast<ConstantSDNode>(CurrentOp);
11532         const APInt &C = ND->getAPIntValue();
11533         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11534       }
11535       break;
11536     case X86ISD::VSRLI:
11537       for (unsigned i=0; i!=NumElts; ++i) {
11538         SDValue CurrentOp = SrcOp->getOperand(i);
11539         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11540           Elts.push_back(CurrentOp);
11541           continue;
11542         }
11543         ND = cast<ConstantSDNode>(CurrentOp);
11544         const APInt &C = ND->getAPIntValue();
11545         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11546       }
11547       break;
11548     case X86ISD::VSRAI:
11549       for (unsigned i=0; i!=NumElts; ++i) {
11550         SDValue CurrentOp = SrcOp->getOperand(i);
11551         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11552           Elts.push_back(CurrentOp);
11553           continue;
11554         }
11555         ND = cast<ConstantSDNode>(CurrentOp);
11556         const APInt &C = ND->getAPIntValue();
11557         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11558       }
11559       break;
11560     }
11561
11562     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11563   }
11564
11565   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11566 }
11567
11568 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11569 // may or may not be a constant. Takes immediate version of shift as input.
11570 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11571                                    SDValue SrcOp, SDValue ShAmt,
11572                                    SelectionDAG &DAG) {
11573   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11574
11575   // Catch shift-by-constant.
11576   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11577     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11578                                       CShAmt->getZExtValue(), DAG);
11579
11580   // Change opcode to non-immediate version
11581   switch (Opc) {
11582     default: llvm_unreachable("Unknown target vector shift node");
11583     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11584     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11585     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11586   }
11587
11588   // Need to build a vector containing shift amount
11589   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11590   SDValue ShOps[4];
11591   ShOps[0] = ShAmt;
11592   ShOps[1] = DAG.getConstant(0, MVT::i32);
11593   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11594   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11595
11596   // The return type has to be a 128-bit type with the same element
11597   // type as the input type.
11598   MVT EltVT = VT.getVectorElementType();
11599   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11600
11601   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11602   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11603 }
11604
11605 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11606   SDLoc dl(Op);
11607   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11608   switch (IntNo) {
11609   default: return SDValue();    // Don't custom lower most intrinsics.
11610   // Comparison intrinsics.
11611   case Intrinsic::x86_sse_comieq_ss:
11612   case Intrinsic::x86_sse_comilt_ss:
11613   case Intrinsic::x86_sse_comile_ss:
11614   case Intrinsic::x86_sse_comigt_ss:
11615   case Intrinsic::x86_sse_comige_ss:
11616   case Intrinsic::x86_sse_comineq_ss:
11617   case Intrinsic::x86_sse_ucomieq_ss:
11618   case Intrinsic::x86_sse_ucomilt_ss:
11619   case Intrinsic::x86_sse_ucomile_ss:
11620   case Intrinsic::x86_sse_ucomigt_ss:
11621   case Intrinsic::x86_sse_ucomige_ss:
11622   case Intrinsic::x86_sse_ucomineq_ss:
11623   case Intrinsic::x86_sse2_comieq_sd:
11624   case Intrinsic::x86_sse2_comilt_sd:
11625   case Intrinsic::x86_sse2_comile_sd:
11626   case Intrinsic::x86_sse2_comigt_sd:
11627   case Intrinsic::x86_sse2_comige_sd:
11628   case Intrinsic::x86_sse2_comineq_sd:
11629   case Intrinsic::x86_sse2_ucomieq_sd:
11630   case Intrinsic::x86_sse2_ucomilt_sd:
11631   case Intrinsic::x86_sse2_ucomile_sd:
11632   case Intrinsic::x86_sse2_ucomigt_sd:
11633   case Intrinsic::x86_sse2_ucomige_sd:
11634   case Intrinsic::x86_sse2_ucomineq_sd: {
11635     unsigned Opc;
11636     ISD::CondCode CC;
11637     switch (IntNo) {
11638     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11639     case Intrinsic::x86_sse_comieq_ss:
11640     case Intrinsic::x86_sse2_comieq_sd:
11641       Opc = X86ISD::COMI;
11642       CC = ISD::SETEQ;
11643       break;
11644     case Intrinsic::x86_sse_comilt_ss:
11645     case Intrinsic::x86_sse2_comilt_sd:
11646       Opc = X86ISD::COMI;
11647       CC = ISD::SETLT;
11648       break;
11649     case Intrinsic::x86_sse_comile_ss:
11650     case Intrinsic::x86_sse2_comile_sd:
11651       Opc = X86ISD::COMI;
11652       CC = ISD::SETLE;
11653       break;
11654     case Intrinsic::x86_sse_comigt_ss:
11655     case Intrinsic::x86_sse2_comigt_sd:
11656       Opc = X86ISD::COMI;
11657       CC = ISD::SETGT;
11658       break;
11659     case Intrinsic::x86_sse_comige_ss:
11660     case Intrinsic::x86_sse2_comige_sd:
11661       Opc = X86ISD::COMI;
11662       CC = ISD::SETGE;
11663       break;
11664     case Intrinsic::x86_sse_comineq_ss:
11665     case Intrinsic::x86_sse2_comineq_sd:
11666       Opc = X86ISD::COMI;
11667       CC = ISD::SETNE;
11668       break;
11669     case Intrinsic::x86_sse_ucomieq_ss:
11670     case Intrinsic::x86_sse2_ucomieq_sd:
11671       Opc = X86ISD::UCOMI;
11672       CC = ISD::SETEQ;
11673       break;
11674     case Intrinsic::x86_sse_ucomilt_ss:
11675     case Intrinsic::x86_sse2_ucomilt_sd:
11676       Opc = X86ISD::UCOMI;
11677       CC = ISD::SETLT;
11678       break;
11679     case Intrinsic::x86_sse_ucomile_ss:
11680     case Intrinsic::x86_sse2_ucomile_sd:
11681       Opc = X86ISD::UCOMI;
11682       CC = ISD::SETLE;
11683       break;
11684     case Intrinsic::x86_sse_ucomigt_ss:
11685     case Intrinsic::x86_sse2_ucomigt_sd:
11686       Opc = X86ISD::UCOMI;
11687       CC = ISD::SETGT;
11688       break;
11689     case Intrinsic::x86_sse_ucomige_ss:
11690     case Intrinsic::x86_sse2_ucomige_sd:
11691       Opc = X86ISD::UCOMI;
11692       CC = ISD::SETGE;
11693       break;
11694     case Intrinsic::x86_sse_ucomineq_ss:
11695     case Intrinsic::x86_sse2_ucomineq_sd:
11696       Opc = X86ISD::UCOMI;
11697       CC = ISD::SETNE;
11698       break;
11699     }
11700
11701     SDValue LHS = Op.getOperand(1);
11702     SDValue RHS = Op.getOperand(2);
11703     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11704     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11705     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11706     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11707                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11708     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11709   }
11710
11711   // Arithmetic intrinsics.
11712   case Intrinsic::x86_sse2_pmulu_dq:
11713   case Intrinsic::x86_avx2_pmulu_dq:
11714     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11715                        Op.getOperand(1), Op.getOperand(2));
11716
11717   case Intrinsic::x86_sse41_pmuldq:
11718   case Intrinsic::x86_avx2_pmul_dq:
11719     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11720                        Op.getOperand(1), Op.getOperand(2));
11721
11722   case Intrinsic::x86_sse2_pmulhu_w:
11723   case Intrinsic::x86_avx2_pmulhu_w:
11724     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11725                        Op.getOperand(1), Op.getOperand(2));
11726
11727   case Intrinsic::x86_sse2_pmulh_w:
11728   case Intrinsic::x86_avx2_pmulh_w:
11729     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11730                        Op.getOperand(1), Op.getOperand(2));
11731
11732   // SSE2/AVX2 sub with unsigned saturation intrinsics
11733   case Intrinsic::x86_sse2_psubus_b:
11734   case Intrinsic::x86_sse2_psubus_w:
11735   case Intrinsic::x86_avx2_psubus_b:
11736   case Intrinsic::x86_avx2_psubus_w:
11737     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11738                        Op.getOperand(1), Op.getOperand(2));
11739
11740   // SSE3/AVX horizontal add/sub intrinsics
11741   case Intrinsic::x86_sse3_hadd_ps:
11742   case Intrinsic::x86_sse3_hadd_pd:
11743   case Intrinsic::x86_avx_hadd_ps_256:
11744   case Intrinsic::x86_avx_hadd_pd_256:
11745   case Intrinsic::x86_sse3_hsub_ps:
11746   case Intrinsic::x86_sse3_hsub_pd:
11747   case Intrinsic::x86_avx_hsub_ps_256:
11748   case Intrinsic::x86_avx_hsub_pd_256:
11749   case Intrinsic::x86_ssse3_phadd_w_128:
11750   case Intrinsic::x86_ssse3_phadd_d_128:
11751   case Intrinsic::x86_avx2_phadd_w:
11752   case Intrinsic::x86_avx2_phadd_d:
11753   case Intrinsic::x86_ssse3_phsub_w_128:
11754   case Intrinsic::x86_ssse3_phsub_d_128:
11755   case Intrinsic::x86_avx2_phsub_w:
11756   case Intrinsic::x86_avx2_phsub_d: {
11757     unsigned Opcode;
11758     switch (IntNo) {
11759     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11760     case Intrinsic::x86_sse3_hadd_ps:
11761     case Intrinsic::x86_sse3_hadd_pd:
11762     case Intrinsic::x86_avx_hadd_ps_256:
11763     case Intrinsic::x86_avx_hadd_pd_256:
11764       Opcode = X86ISD::FHADD;
11765       break;
11766     case Intrinsic::x86_sse3_hsub_ps:
11767     case Intrinsic::x86_sse3_hsub_pd:
11768     case Intrinsic::x86_avx_hsub_ps_256:
11769     case Intrinsic::x86_avx_hsub_pd_256:
11770       Opcode = X86ISD::FHSUB;
11771       break;
11772     case Intrinsic::x86_ssse3_phadd_w_128:
11773     case Intrinsic::x86_ssse3_phadd_d_128:
11774     case Intrinsic::x86_avx2_phadd_w:
11775     case Intrinsic::x86_avx2_phadd_d:
11776       Opcode = X86ISD::HADD;
11777       break;
11778     case Intrinsic::x86_ssse3_phsub_w_128:
11779     case Intrinsic::x86_ssse3_phsub_d_128:
11780     case Intrinsic::x86_avx2_phsub_w:
11781     case Intrinsic::x86_avx2_phsub_d:
11782       Opcode = X86ISD::HSUB;
11783       break;
11784     }
11785     return DAG.getNode(Opcode, dl, Op.getValueType(),
11786                        Op.getOperand(1), Op.getOperand(2));
11787   }
11788
11789   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11790   case Intrinsic::x86_sse2_pmaxu_b:
11791   case Intrinsic::x86_sse41_pmaxuw:
11792   case Intrinsic::x86_sse41_pmaxud:
11793   case Intrinsic::x86_avx2_pmaxu_b:
11794   case Intrinsic::x86_avx2_pmaxu_w:
11795   case Intrinsic::x86_avx2_pmaxu_d:
11796   case Intrinsic::x86_sse2_pminu_b:
11797   case Intrinsic::x86_sse41_pminuw:
11798   case Intrinsic::x86_sse41_pminud:
11799   case Intrinsic::x86_avx2_pminu_b:
11800   case Intrinsic::x86_avx2_pminu_w:
11801   case Intrinsic::x86_avx2_pminu_d:
11802   case Intrinsic::x86_sse41_pmaxsb:
11803   case Intrinsic::x86_sse2_pmaxs_w:
11804   case Intrinsic::x86_sse41_pmaxsd:
11805   case Intrinsic::x86_avx2_pmaxs_b:
11806   case Intrinsic::x86_avx2_pmaxs_w:
11807   case Intrinsic::x86_avx2_pmaxs_d:
11808   case Intrinsic::x86_sse41_pminsb:
11809   case Intrinsic::x86_sse2_pmins_w:
11810   case Intrinsic::x86_sse41_pminsd:
11811   case Intrinsic::x86_avx2_pmins_b:
11812   case Intrinsic::x86_avx2_pmins_w:
11813   case Intrinsic::x86_avx2_pmins_d: {
11814     unsigned Opcode;
11815     switch (IntNo) {
11816     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11817     case Intrinsic::x86_sse2_pmaxu_b:
11818     case Intrinsic::x86_sse41_pmaxuw:
11819     case Intrinsic::x86_sse41_pmaxud:
11820     case Intrinsic::x86_avx2_pmaxu_b:
11821     case Intrinsic::x86_avx2_pmaxu_w:
11822     case Intrinsic::x86_avx2_pmaxu_d:
11823       Opcode = X86ISD::UMAX;
11824       break;
11825     case Intrinsic::x86_sse2_pminu_b:
11826     case Intrinsic::x86_sse41_pminuw:
11827     case Intrinsic::x86_sse41_pminud:
11828     case Intrinsic::x86_avx2_pminu_b:
11829     case Intrinsic::x86_avx2_pminu_w:
11830     case Intrinsic::x86_avx2_pminu_d:
11831       Opcode = X86ISD::UMIN;
11832       break;
11833     case Intrinsic::x86_sse41_pmaxsb:
11834     case Intrinsic::x86_sse2_pmaxs_w:
11835     case Intrinsic::x86_sse41_pmaxsd:
11836     case Intrinsic::x86_avx2_pmaxs_b:
11837     case Intrinsic::x86_avx2_pmaxs_w:
11838     case Intrinsic::x86_avx2_pmaxs_d:
11839       Opcode = X86ISD::SMAX;
11840       break;
11841     case Intrinsic::x86_sse41_pminsb:
11842     case Intrinsic::x86_sse2_pmins_w:
11843     case Intrinsic::x86_sse41_pminsd:
11844     case Intrinsic::x86_avx2_pmins_b:
11845     case Intrinsic::x86_avx2_pmins_w:
11846     case Intrinsic::x86_avx2_pmins_d:
11847       Opcode = X86ISD::SMIN;
11848       break;
11849     }
11850     return DAG.getNode(Opcode, dl, Op.getValueType(),
11851                        Op.getOperand(1), Op.getOperand(2));
11852   }
11853
11854   // SSE/SSE2/AVX floating point max/min intrinsics.
11855   case Intrinsic::x86_sse_max_ps:
11856   case Intrinsic::x86_sse2_max_pd:
11857   case Intrinsic::x86_avx_max_ps_256:
11858   case Intrinsic::x86_avx_max_pd_256:
11859   case Intrinsic::x86_sse_min_ps:
11860   case Intrinsic::x86_sse2_min_pd:
11861   case Intrinsic::x86_avx_min_ps_256:
11862   case Intrinsic::x86_avx_min_pd_256: {
11863     unsigned Opcode;
11864     switch (IntNo) {
11865     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11866     case Intrinsic::x86_sse_max_ps:
11867     case Intrinsic::x86_sse2_max_pd:
11868     case Intrinsic::x86_avx_max_ps_256:
11869     case Intrinsic::x86_avx_max_pd_256:
11870       Opcode = X86ISD::FMAX;
11871       break;
11872     case Intrinsic::x86_sse_min_ps:
11873     case Intrinsic::x86_sse2_min_pd:
11874     case Intrinsic::x86_avx_min_ps_256:
11875     case Intrinsic::x86_avx_min_pd_256:
11876       Opcode = X86ISD::FMIN;
11877       break;
11878     }
11879     return DAG.getNode(Opcode, dl, Op.getValueType(),
11880                        Op.getOperand(1), Op.getOperand(2));
11881   }
11882
11883   // AVX2 variable shift intrinsics
11884   case Intrinsic::x86_avx2_psllv_d:
11885   case Intrinsic::x86_avx2_psllv_q:
11886   case Intrinsic::x86_avx2_psllv_d_256:
11887   case Intrinsic::x86_avx2_psllv_q_256:
11888   case Intrinsic::x86_avx2_psrlv_d:
11889   case Intrinsic::x86_avx2_psrlv_q:
11890   case Intrinsic::x86_avx2_psrlv_d_256:
11891   case Intrinsic::x86_avx2_psrlv_q_256:
11892   case Intrinsic::x86_avx2_psrav_d:
11893   case Intrinsic::x86_avx2_psrav_d_256: {
11894     unsigned Opcode;
11895     switch (IntNo) {
11896     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11897     case Intrinsic::x86_avx2_psllv_d:
11898     case Intrinsic::x86_avx2_psllv_q:
11899     case Intrinsic::x86_avx2_psllv_d_256:
11900     case Intrinsic::x86_avx2_psllv_q_256:
11901       Opcode = ISD::SHL;
11902       break;
11903     case Intrinsic::x86_avx2_psrlv_d:
11904     case Intrinsic::x86_avx2_psrlv_q:
11905     case Intrinsic::x86_avx2_psrlv_d_256:
11906     case Intrinsic::x86_avx2_psrlv_q_256:
11907       Opcode = ISD::SRL;
11908       break;
11909     case Intrinsic::x86_avx2_psrav_d:
11910     case Intrinsic::x86_avx2_psrav_d_256:
11911       Opcode = ISD::SRA;
11912       break;
11913     }
11914     return DAG.getNode(Opcode, dl, Op.getValueType(),
11915                        Op.getOperand(1), Op.getOperand(2));
11916   }
11917
11918   case Intrinsic::x86_ssse3_pshuf_b_128:
11919   case Intrinsic::x86_avx2_pshuf_b:
11920     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11921                        Op.getOperand(1), Op.getOperand(2));
11922
11923   case Intrinsic::x86_ssse3_psign_b_128:
11924   case Intrinsic::x86_ssse3_psign_w_128:
11925   case Intrinsic::x86_ssse3_psign_d_128:
11926   case Intrinsic::x86_avx2_psign_b:
11927   case Intrinsic::x86_avx2_psign_w:
11928   case Intrinsic::x86_avx2_psign_d:
11929     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11930                        Op.getOperand(1), Op.getOperand(2));
11931
11932   case Intrinsic::x86_sse41_insertps:
11933     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11934                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11935
11936   case Intrinsic::x86_avx_vperm2f128_ps_256:
11937   case Intrinsic::x86_avx_vperm2f128_pd_256:
11938   case Intrinsic::x86_avx_vperm2f128_si_256:
11939   case Intrinsic::x86_avx2_vperm2i128:
11940     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11941                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11942
11943   case Intrinsic::x86_avx2_permd:
11944   case Intrinsic::x86_avx2_permps:
11945     // Operands intentionally swapped. Mask is last operand to intrinsic,
11946     // but second operand for node/instruction.
11947     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11948                        Op.getOperand(2), Op.getOperand(1));
11949
11950   case Intrinsic::x86_sse_sqrt_ps:
11951   case Intrinsic::x86_sse2_sqrt_pd:
11952   case Intrinsic::x86_avx_sqrt_ps_256:
11953   case Intrinsic::x86_avx_sqrt_pd_256:
11954     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11955
11956   // ptest and testp intrinsics. The intrinsic these come from are designed to
11957   // return an integer value, not just an instruction so lower it to the ptest
11958   // or testp pattern and a setcc for the result.
11959   case Intrinsic::x86_sse41_ptestz:
11960   case Intrinsic::x86_sse41_ptestc:
11961   case Intrinsic::x86_sse41_ptestnzc:
11962   case Intrinsic::x86_avx_ptestz_256:
11963   case Intrinsic::x86_avx_ptestc_256:
11964   case Intrinsic::x86_avx_ptestnzc_256:
11965   case Intrinsic::x86_avx_vtestz_ps:
11966   case Intrinsic::x86_avx_vtestc_ps:
11967   case Intrinsic::x86_avx_vtestnzc_ps:
11968   case Intrinsic::x86_avx_vtestz_pd:
11969   case Intrinsic::x86_avx_vtestc_pd:
11970   case Intrinsic::x86_avx_vtestnzc_pd:
11971   case Intrinsic::x86_avx_vtestz_ps_256:
11972   case Intrinsic::x86_avx_vtestc_ps_256:
11973   case Intrinsic::x86_avx_vtestnzc_ps_256:
11974   case Intrinsic::x86_avx_vtestz_pd_256:
11975   case Intrinsic::x86_avx_vtestc_pd_256:
11976   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11977     bool IsTestPacked = false;
11978     unsigned X86CC;
11979     switch (IntNo) {
11980     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11981     case Intrinsic::x86_avx_vtestz_ps:
11982     case Intrinsic::x86_avx_vtestz_pd:
11983     case Intrinsic::x86_avx_vtestz_ps_256:
11984     case Intrinsic::x86_avx_vtestz_pd_256:
11985       IsTestPacked = true; // Fallthrough
11986     case Intrinsic::x86_sse41_ptestz:
11987     case Intrinsic::x86_avx_ptestz_256:
11988       // ZF = 1
11989       X86CC = X86::COND_E;
11990       break;
11991     case Intrinsic::x86_avx_vtestc_ps:
11992     case Intrinsic::x86_avx_vtestc_pd:
11993     case Intrinsic::x86_avx_vtestc_ps_256:
11994     case Intrinsic::x86_avx_vtestc_pd_256:
11995       IsTestPacked = true; // Fallthrough
11996     case Intrinsic::x86_sse41_ptestc:
11997     case Intrinsic::x86_avx_ptestc_256:
11998       // CF = 1
11999       X86CC = X86::COND_B;
12000       break;
12001     case Intrinsic::x86_avx_vtestnzc_ps:
12002     case Intrinsic::x86_avx_vtestnzc_pd:
12003     case Intrinsic::x86_avx_vtestnzc_ps_256:
12004     case Intrinsic::x86_avx_vtestnzc_pd_256:
12005       IsTestPacked = true; // Fallthrough
12006     case Intrinsic::x86_sse41_ptestnzc:
12007     case Intrinsic::x86_avx_ptestnzc_256:
12008       // ZF and CF = 0
12009       X86CC = X86::COND_A;
12010       break;
12011     }
12012
12013     SDValue LHS = Op.getOperand(1);
12014     SDValue RHS = Op.getOperand(2);
12015     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12016     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12017     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12018     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12019     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12020   }
12021   case Intrinsic::x86_avx512_kortestz_w:
12022   case Intrinsic::x86_avx512_kortestc_w: {
12023     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12024     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12025     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12026     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12027     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12028     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12029     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12030   }
12031
12032   // SSE/AVX shift intrinsics
12033   case Intrinsic::x86_sse2_psll_w:
12034   case Intrinsic::x86_sse2_psll_d:
12035   case Intrinsic::x86_sse2_psll_q:
12036   case Intrinsic::x86_avx2_psll_w:
12037   case Intrinsic::x86_avx2_psll_d:
12038   case Intrinsic::x86_avx2_psll_q:
12039   case Intrinsic::x86_sse2_psrl_w:
12040   case Intrinsic::x86_sse2_psrl_d:
12041   case Intrinsic::x86_sse2_psrl_q:
12042   case Intrinsic::x86_avx2_psrl_w:
12043   case Intrinsic::x86_avx2_psrl_d:
12044   case Intrinsic::x86_avx2_psrl_q:
12045   case Intrinsic::x86_sse2_psra_w:
12046   case Intrinsic::x86_sse2_psra_d:
12047   case Intrinsic::x86_avx2_psra_w:
12048   case Intrinsic::x86_avx2_psra_d: {
12049     unsigned Opcode;
12050     switch (IntNo) {
12051     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12052     case Intrinsic::x86_sse2_psll_w:
12053     case Intrinsic::x86_sse2_psll_d:
12054     case Intrinsic::x86_sse2_psll_q:
12055     case Intrinsic::x86_avx2_psll_w:
12056     case Intrinsic::x86_avx2_psll_d:
12057     case Intrinsic::x86_avx2_psll_q:
12058       Opcode = X86ISD::VSHL;
12059       break;
12060     case Intrinsic::x86_sse2_psrl_w:
12061     case Intrinsic::x86_sse2_psrl_d:
12062     case Intrinsic::x86_sse2_psrl_q:
12063     case Intrinsic::x86_avx2_psrl_w:
12064     case Intrinsic::x86_avx2_psrl_d:
12065     case Intrinsic::x86_avx2_psrl_q:
12066       Opcode = X86ISD::VSRL;
12067       break;
12068     case Intrinsic::x86_sse2_psra_w:
12069     case Intrinsic::x86_sse2_psra_d:
12070     case Intrinsic::x86_avx2_psra_w:
12071     case Intrinsic::x86_avx2_psra_d:
12072       Opcode = X86ISD::VSRA;
12073       break;
12074     }
12075     return DAG.getNode(Opcode, dl, Op.getValueType(),
12076                        Op.getOperand(1), Op.getOperand(2));
12077   }
12078
12079   // SSE/AVX immediate shift intrinsics
12080   case Intrinsic::x86_sse2_pslli_w:
12081   case Intrinsic::x86_sse2_pslli_d:
12082   case Intrinsic::x86_sse2_pslli_q:
12083   case Intrinsic::x86_avx2_pslli_w:
12084   case Intrinsic::x86_avx2_pslli_d:
12085   case Intrinsic::x86_avx2_pslli_q:
12086   case Intrinsic::x86_sse2_psrli_w:
12087   case Intrinsic::x86_sse2_psrli_d:
12088   case Intrinsic::x86_sse2_psrli_q:
12089   case Intrinsic::x86_avx2_psrli_w:
12090   case Intrinsic::x86_avx2_psrli_d:
12091   case Intrinsic::x86_avx2_psrli_q:
12092   case Intrinsic::x86_sse2_psrai_w:
12093   case Intrinsic::x86_sse2_psrai_d:
12094   case Intrinsic::x86_avx2_psrai_w:
12095   case Intrinsic::x86_avx2_psrai_d: {
12096     unsigned Opcode;
12097     switch (IntNo) {
12098     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12099     case Intrinsic::x86_sse2_pslli_w:
12100     case Intrinsic::x86_sse2_pslli_d:
12101     case Intrinsic::x86_sse2_pslli_q:
12102     case Intrinsic::x86_avx2_pslli_w:
12103     case Intrinsic::x86_avx2_pslli_d:
12104     case Intrinsic::x86_avx2_pslli_q:
12105       Opcode = X86ISD::VSHLI;
12106       break;
12107     case Intrinsic::x86_sse2_psrli_w:
12108     case Intrinsic::x86_sse2_psrli_d:
12109     case Intrinsic::x86_sse2_psrli_q:
12110     case Intrinsic::x86_avx2_psrli_w:
12111     case Intrinsic::x86_avx2_psrli_d:
12112     case Intrinsic::x86_avx2_psrli_q:
12113       Opcode = X86ISD::VSRLI;
12114       break;
12115     case Intrinsic::x86_sse2_psrai_w:
12116     case Intrinsic::x86_sse2_psrai_d:
12117     case Intrinsic::x86_avx2_psrai_w:
12118     case Intrinsic::x86_avx2_psrai_d:
12119       Opcode = X86ISD::VSRAI;
12120       break;
12121     }
12122     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12123                                Op.getOperand(1), Op.getOperand(2), DAG);
12124   }
12125
12126   case Intrinsic::x86_sse42_pcmpistria128:
12127   case Intrinsic::x86_sse42_pcmpestria128:
12128   case Intrinsic::x86_sse42_pcmpistric128:
12129   case Intrinsic::x86_sse42_pcmpestric128:
12130   case Intrinsic::x86_sse42_pcmpistrio128:
12131   case Intrinsic::x86_sse42_pcmpestrio128:
12132   case Intrinsic::x86_sse42_pcmpistris128:
12133   case Intrinsic::x86_sse42_pcmpestris128:
12134   case Intrinsic::x86_sse42_pcmpistriz128:
12135   case Intrinsic::x86_sse42_pcmpestriz128: {
12136     unsigned Opcode;
12137     unsigned X86CC;
12138     switch (IntNo) {
12139     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12140     case Intrinsic::x86_sse42_pcmpistria128:
12141       Opcode = X86ISD::PCMPISTRI;
12142       X86CC = X86::COND_A;
12143       break;
12144     case Intrinsic::x86_sse42_pcmpestria128:
12145       Opcode = X86ISD::PCMPESTRI;
12146       X86CC = X86::COND_A;
12147       break;
12148     case Intrinsic::x86_sse42_pcmpistric128:
12149       Opcode = X86ISD::PCMPISTRI;
12150       X86CC = X86::COND_B;
12151       break;
12152     case Intrinsic::x86_sse42_pcmpestric128:
12153       Opcode = X86ISD::PCMPESTRI;
12154       X86CC = X86::COND_B;
12155       break;
12156     case Intrinsic::x86_sse42_pcmpistrio128:
12157       Opcode = X86ISD::PCMPISTRI;
12158       X86CC = X86::COND_O;
12159       break;
12160     case Intrinsic::x86_sse42_pcmpestrio128:
12161       Opcode = X86ISD::PCMPESTRI;
12162       X86CC = X86::COND_O;
12163       break;
12164     case Intrinsic::x86_sse42_pcmpistris128:
12165       Opcode = X86ISD::PCMPISTRI;
12166       X86CC = X86::COND_S;
12167       break;
12168     case Intrinsic::x86_sse42_pcmpestris128:
12169       Opcode = X86ISD::PCMPESTRI;
12170       X86CC = X86::COND_S;
12171       break;
12172     case Intrinsic::x86_sse42_pcmpistriz128:
12173       Opcode = X86ISD::PCMPISTRI;
12174       X86CC = X86::COND_E;
12175       break;
12176     case Intrinsic::x86_sse42_pcmpestriz128:
12177       Opcode = X86ISD::PCMPESTRI;
12178       X86CC = X86::COND_E;
12179       break;
12180     }
12181     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12182     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12183     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12184     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12185                                 DAG.getConstant(X86CC, MVT::i8),
12186                                 SDValue(PCMP.getNode(), 1));
12187     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12188   }
12189
12190   case Intrinsic::x86_sse42_pcmpistri128:
12191   case Intrinsic::x86_sse42_pcmpestri128: {
12192     unsigned Opcode;
12193     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12194       Opcode = X86ISD::PCMPISTRI;
12195     else
12196       Opcode = X86ISD::PCMPESTRI;
12197
12198     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12199     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12200     return DAG.getNode(Opcode, dl, VTs, NewOps);
12201   }
12202   case Intrinsic::x86_fma_vfmadd_ps:
12203   case Intrinsic::x86_fma_vfmadd_pd:
12204   case Intrinsic::x86_fma_vfmsub_ps:
12205   case Intrinsic::x86_fma_vfmsub_pd:
12206   case Intrinsic::x86_fma_vfnmadd_ps:
12207   case Intrinsic::x86_fma_vfnmadd_pd:
12208   case Intrinsic::x86_fma_vfnmsub_ps:
12209   case Intrinsic::x86_fma_vfnmsub_pd:
12210   case Intrinsic::x86_fma_vfmaddsub_ps:
12211   case Intrinsic::x86_fma_vfmaddsub_pd:
12212   case Intrinsic::x86_fma_vfmsubadd_ps:
12213   case Intrinsic::x86_fma_vfmsubadd_pd:
12214   case Intrinsic::x86_fma_vfmadd_ps_256:
12215   case Intrinsic::x86_fma_vfmadd_pd_256:
12216   case Intrinsic::x86_fma_vfmsub_ps_256:
12217   case Intrinsic::x86_fma_vfmsub_pd_256:
12218   case Intrinsic::x86_fma_vfnmadd_ps_256:
12219   case Intrinsic::x86_fma_vfnmadd_pd_256:
12220   case Intrinsic::x86_fma_vfnmsub_ps_256:
12221   case Intrinsic::x86_fma_vfnmsub_pd_256:
12222   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12223   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12224   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12225   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12226   case Intrinsic::x86_fma_vfmadd_ps_512:
12227   case Intrinsic::x86_fma_vfmadd_pd_512:
12228   case Intrinsic::x86_fma_vfmsub_ps_512:
12229   case Intrinsic::x86_fma_vfmsub_pd_512:
12230   case Intrinsic::x86_fma_vfnmadd_ps_512:
12231   case Intrinsic::x86_fma_vfnmadd_pd_512:
12232   case Intrinsic::x86_fma_vfnmsub_ps_512:
12233   case Intrinsic::x86_fma_vfnmsub_pd_512:
12234   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12235   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12236   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12237   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12238     unsigned Opc;
12239     switch (IntNo) {
12240     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12241     case Intrinsic::x86_fma_vfmadd_ps:
12242     case Intrinsic::x86_fma_vfmadd_pd:
12243     case Intrinsic::x86_fma_vfmadd_ps_256:
12244     case Intrinsic::x86_fma_vfmadd_pd_256:
12245     case Intrinsic::x86_fma_vfmadd_ps_512:
12246     case Intrinsic::x86_fma_vfmadd_pd_512:
12247       Opc = X86ISD::FMADD;
12248       break;
12249     case Intrinsic::x86_fma_vfmsub_ps:
12250     case Intrinsic::x86_fma_vfmsub_pd:
12251     case Intrinsic::x86_fma_vfmsub_ps_256:
12252     case Intrinsic::x86_fma_vfmsub_pd_256:
12253     case Intrinsic::x86_fma_vfmsub_ps_512:
12254     case Intrinsic::x86_fma_vfmsub_pd_512:
12255       Opc = X86ISD::FMSUB;
12256       break;
12257     case Intrinsic::x86_fma_vfnmadd_ps:
12258     case Intrinsic::x86_fma_vfnmadd_pd:
12259     case Intrinsic::x86_fma_vfnmadd_ps_256:
12260     case Intrinsic::x86_fma_vfnmadd_pd_256:
12261     case Intrinsic::x86_fma_vfnmadd_ps_512:
12262     case Intrinsic::x86_fma_vfnmadd_pd_512:
12263       Opc = X86ISD::FNMADD;
12264       break;
12265     case Intrinsic::x86_fma_vfnmsub_ps:
12266     case Intrinsic::x86_fma_vfnmsub_pd:
12267     case Intrinsic::x86_fma_vfnmsub_ps_256:
12268     case Intrinsic::x86_fma_vfnmsub_pd_256:
12269     case Intrinsic::x86_fma_vfnmsub_ps_512:
12270     case Intrinsic::x86_fma_vfnmsub_pd_512:
12271       Opc = X86ISD::FNMSUB;
12272       break;
12273     case Intrinsic::x86_fma_vfmaddsub_ps:
12274     case Intrinsic::x86_fma_vfmaddsub_pd:
12275     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12276     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12277     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12278     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12279       Opc = X86ISD::FMADDSUB;
12280       break;
12281     case Intrinsic::x86_fma_vfmsubadd_ps:
12282     case Intrinsic::x86_fma_vfmsubadd_pd:
12283     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12284     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12285     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12286     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12287       Opc = X86ISD::FMSUBADD;
12288       break;
12289     }
12290
12291     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12292                        Op.getOperand(2), Op.getOperand(3));
12293   }
12294   }
12295 }
12296
12297 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12298                              SDValue Base, SDValue Index,
12299                              SDValue ScaleOp, SDValue Chain,
12300                              const X86Subtarget * Subtarget) {
12301   SDLoc dl(Op);
12302   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12303   assert(C && "Invalid scale type");
12304   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12305   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12306   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12307                              Index.getSimpleValueType().getVectorNumElements());
12308   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12309   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12310   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12311   SDValue Segment = DAG.getRegister(0, MVT::i32);
12312   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12313   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12314   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12315   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12316 }
12317
12318 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12319                               SDValue Src, SDValue Mask, SDValue Base,
12320                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12321                               const X86Subtarget * Subtarget) {
12322   SDLoc dl(Op);
12323   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12324   assert(C && "Invalid scale type");
12325   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12326   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12327                              Index.getSimpleValueType().getVectorNumElements());
12328   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12329   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12330   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12331   SDValue Segment = DAG.getRegister(0, MVT::i32);
12332   if (Src.getOpcode() == ISD::UNDEF)
12333     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12334   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12335   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12336   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12337   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12338 }
12339
12340 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12341                               SDValue Src, SDValue Base, SDValue Index,
12342                               SDValue ScaleOp, SDValue Chain) {
12343   SDLoc dl(Op);
12344   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12345   assert(C && "Invalid scale type");
12346   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12347   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12348   SDValue Segment = DAG.getRegister(0, MVT::i32);
12349   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12350                              Index.getSimpleValueType().getVectorNumElements());
12351   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12352   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12353   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12354   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12355   return SDValue(Res, 1);
12356 }
12357
12358 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12359                                SDValue Src, SDValue Mask, SDValue Base,
12360                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12361   SDLoc dl(Op);
12362   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12363   assert(C && "Invalid scale type");
12364   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12365   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12366   SDValue Segment = DAG.getRegister(0, MVT::i32);
12367   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12368                              Index.getSimpleValueType().getVectorNumElements());
12369   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12370   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12371   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12372   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12373   return SDValue(Res, 1);
12374 }
12375
12376 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12377 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12378 // also used to custom lower READCYCLECOUNTER nodes.
12379 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12380                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12381                               SmallVectorImpl<SDValue> &Results) {
12382   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12383   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12384   SDValue LO, HI;
12385
12386   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12387   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12388   // and the EAX register is loaded with the low-order 32 bits.
12389   if (Subtarget->is64Bit()) {
12390     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12391     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12392                             LO.getValue(2));
12393   } else {
12394     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12395     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12396                             LO.getValue(2));
12397   }
12398   SDValue Chain = HI.getValue(1);
12399
12400   if (Opcode == X86ISD::RDTSCP_DAG) {
12401     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12402
12403     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12404     // the ECX register. Add 'ecx' explicitly to the chain.
12405     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12406                                      HI.getValue(2));
12407     // Explicitly store the content of ECX at the location passed in input
12408     // to the 'rdtscp' intrinsic.
12409     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12410                          MachinePointerInfo(), false, false, 0);
12411   }
12412
12413   if (Subtarget->is64Bit()) {
12414     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12415     // the EAX register is loaded with the low-order 32 bits.
12416     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12417                               DAG.getConstant(32, MVT::i8));
12418     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12419     Results.push_back(Chain);
12420     return;
12421   }
12422
12423   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12424   SDValue Ops[] = { LO, HI };
12425   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12426   Results.push_back(Pair);
12427   Results.push_back(Chain);
12428 }
12429
12430 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12431                                      SelectionDAG &DAG) {
12432   SmallVector<SDValue, 2> Results;
12433   SDLoc DL(Op);
12434   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12435                           Results);
12436   return DAG.getMergeValues(&Results[0], Results.size(), DL);
12437 }
12438
12439 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12440                                       SelectionDAG &DAG) {
12441   SDLoc dl(Op);
12442   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12443   switch (IntNo) {
12444   default: return SDValue();    // Don't custom lower most intrinsics.
12445
12446   // RDRAND/RDSEED intrinsics.
12447   case Intrinsic::x86_rdrand_16:
12448   case Intrinsic::x86_rdrand_32:
12449   case Intrinsic::x86_rdrand_64:
12450   case Intrinsic::x86_rdseed_16:
12451   case Intrinsic::x86_rdseed_32:
12452   case Intrinsic::x86_rdseed_64: {
12453     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12454                        IntNo == Intrinsic::x86_rdseed_32 ||
12455                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12456                                                             X86ISD::RDRAND;
12457     // Emit the node with the right value type.
12458     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12459     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12460
12461     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12462     // Otherwise return the value from Rand, which is always 0, casted to i32.
12463     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12464                       DAG.getConstant(1, Op->getValueType(1)),
12465                       DAG.getConstant(X86::COND_B, MVT::i32),
12466                       SDValue(Result.getNode(), 1) };
12467     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12468                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12469                                   Ops);
12470
12471     // Return { result, isValid, chain }.
12472     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12473                        SDValue(Result.getNode(), 2));
12474   }
12475   //int_gather(index, base, scale);
12476   case Intrinsic::x86_avx512_gather_qpd_512:
12477   case Intrinsic::x86_avx512_gather_qps_512:
12478   case Intrinsic::x86_avx512_gather_dpd_512:
12479   case Intrinsic::x86_avx512_gather_qpi_512:
12480   case Intrinsic::x86_avx512_gather_qpq_512:
12481   case Intrinsic::x86_avx512_gather_dpq_512:
12482   case Intrinsic::x86_avx512_gather_dps_512:
12483   case Intrinsic::x86_avx512_gather_dpi_512: {
12484     unsigned Opc;
12485     switch (IntNo) {
12486     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12487     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12488     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12489     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12490     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12491     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12492     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12493     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12494     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12495     }
12496     SDValue Chain = Op.getOperand(0);
12497     SDValue Index = Op.getOperand(2);
12498     SDValue Base  = Op.getOperand(3);
12499     SDValue Scale = Op.getOperand(4);
12500     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12501   }
12502   //int_gather_mask(v1, mask, index, base, scale);
12503   case Intrinsic::x86_avx512_gather_qps_mask_512:
12504   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12505   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12506   case Intrinsic::x86_avx512_gather_dps_mask_512:
12507   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12508   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12509   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12510   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12511     unsigned Opc;
12512     switch (IntNo) {
12513     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12514     case Intrinsic::x86_avx512_gather_qps_mask_512:
12515       Opc = X86::VGATHERQPSZrm; break;
12516     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12517       Opc = X86::VGATHERQPDZrm; break;
12518     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12519       Opc = X86::VGATHERDPDZrm; break;
12520     case Intrinsic::x86_avx512_gather_dps_mask_512:
12521       Opc = X86::VGATHERDPSZrm; break;
12522     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12523       Opc = X86::VPGATHERQDZrm; break;
12524     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12525       Opc = X86::VPGATHERQQZrm; break;
12526     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12527       Opc = X86::VPGATHERDDZrm; break;
12528     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12529       Opc = X86::VPGATHERDQZrm; break;
12530     }
12531     SDValue Chain = Op.getOperand(0);
12532     SDValue Src   = Op.getOperand(2);
12533     SDValue Mask  = Op.getOperand(3);
12534     SDValue Index = Op.getOperand(4);
12535     SDValue Base  = Op.getOperand(5);
12536     SDValue Scale = Op.getOperand(6);
12537     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12538                           Subtarget);
12539   }
12540   //int_scatter(base, index, v1, scale);
12541   case Intrinsic::x86_avx512_scatter_qpd_512:
12542   case Intrinsic::x86_avx512_scatter_qps_512:
12543   case Intrinsic::x86_avx512_scatter_dpd_512:
12544   case Intrinsic::x86_avx512_scatter_qpi_512:
12545   case Intrinsic::x86_avx512_scatter_qpq_512:
12546   case Intrinsic::x86_avx512_scatter_dpq_512:
12547   case Intrinsic::x86_avx512_scatter_dps_512:
12548   case Intrinsic::x86_avx512_scatter_dpi_512: {
12549     unsigned Opc;
12550     switch (IntNo) {
12551     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12552     case Intrinsic::x86_avx512_scatter_qpd_512:
12553       Opc = X86::VSCATTERQPDZmr; break;
12554     case Intrinsic::x86_avx512_scatter_qps_512:
12555       Opc = X86::VSCATTERQPSZmr; break;
12556     case Intrinsic::x86_avx512_scatter_dpd_512:
12557       Opc = X86::VSCATTERDPDZmr; break;
12558     case Intrinsic::x86_avx512_scatter_dps_512:
12559       Opc = X86::VSCATTERDPSZmr; break;
12560     case Intrinsic::x86_avx512_scatter_qpi_512:
12561       Opc = X86::VPSCATTERQDZmr; break;
12562     case Intrinsic::x86_avx512_scatter_qpq_512:
12563       Opc = X86::VPSCATTERQQZmr; break;
12564     case Intrinsic::x86_avx512_scatter_dpq_512:
12565       Opc = X86::VPSCATTERDQZmr; break;
12566     case Intrinsic::x86_avx512_scatter_dpi_512:
12567       Opc = X86::VPSCATTERDDZmr; break;
12568     }
12569     SDValue Chain = Op.getOperand(0);
12570     SDValue Base  = Op.getOperand(2);
12571     SDValue Index = Op.getOperand(3);
12572     SDValue Src   = Op.getOperand(4);
12573     SDValue Scale = Op.getOperand(5);
12574     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12575   }
12576   //int_scatter_mask(base, mask, index, v1, scale);
12577   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12578   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12579   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12580   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12581   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12582   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12583   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12584   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12585     unsigned Opc;
12586     switch (IntNo) {
12587     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12588     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12589       Opc = X86::VSCATTERQPDZmr; break;
12590     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12591       Opc = X86::VSCATTERQPSZmr; break;
12592     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12593       Opc = X86::VSCATTERDPDZmr; break;
12594     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12595       Opc = X86::VSCATTERDPSZmr; break;
12596     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12597       Opc = X86::VPSCATTERQDZmr; break;
12598     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12599       Opc = X86::VPSCATTERQQZmr; break;
12600     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12601       Opc = X86::VPSCATTERDQZmr; break;
12602     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12603       Opc = X86::VPSCATTERDDZmr; break;
12604     }
12605     SDValue Chain = Op.getOperand(0);
12606     SDValue Base  = Op.getOperand(2);
12607     SDValue Mask  = Op.getOperand(3);
12608     SDValue Index = Op.getOperand(4);
12609     SDValue Src   = Op.getOperand(5);
12610     SDValue Scale = Op.getOperand(6);
12611     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12612   }
12613   // Read Time Stamp Counter (RDTSC).
12614   case Intrinsic::x86_rdtsc:
12615   // Read Time Stamp Counter and Processor ID (RDTSCP).
12616   case Intrinsic::x86_rdtscp: {
12617     unsigned Opc;
12618     switch (IntNo) {
12619     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12620     case Intrinsic::x86_rdtsc:
12621       Opc = X86ISD::RDTSC_DAG; break;
12622     case Intrinsic::x86_rdtscp:
12623       Opc = X86ISD::RDTSCP_DAG; break;
12624     }
12625     SmallVector<SDValue, 2> Results;
12626     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12627     return DAG.getMergeValues(&Results[0], Results.size(), dl);
12628   }
12629   // XTEST intrinsics.
12630   case Intrinsic::x86_xtest: {
12631     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12632     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12633     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12634                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12635                                 InTrans);
12636     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12637     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12638                        Ret, SDValue(InTrans.getNode(), 1));
12639   }
12640   }
12641 }
12642
12643 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12644                                            SelectionDAG &DAG) const {
12645   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12646   MFI->setReturnAddressIsTaken(true);
12647
12648   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12649     return SDValue();
12650
12651   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12652   SDLoc dl(Op);
12653   EVT PtrVT = getPointerTy();
12654
12655   if (Depth > 0) {
12656     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12657     const X86RegisterInfo *RegInfo =
12658       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12659     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12660     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12661                        DAG.getNode(ISD::ADD, dl, PtrVT,
12662                                    FrameAddr, Offset),
12663                        MachinePointerInfo(), false, false, false, 0);
12664   }
12665
12666   // Just load the return address.
12667   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12668   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12669                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12670 }
12671
12672 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12673   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12674   MFI->setFrameAddressIsTaken(true);
12675
12676   EVT VT = Op.getValueType();
12677   SDLoc dl(Op);  // FIXME probably not meaningful
12678   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12679   const X86RegisterInfo *RegInfo =
12680     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12681   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12682   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12683           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12684          "Invalid Frame Register!");
12685   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12686   while (Depth--)
12687     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12688                             MachinePointerInfo(),
12689                             false, false, false, 0);
12690   return FrameAddr;
12691 }
12692
12693 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12694                                                      SelectionDAG &DAG) const {
12695   const X86RegisterInfo *RegInfo =
12696     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12697   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12698 }
12699
12700 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12701   SDValue Chain     = Op.getOperand(0);
12702   SDValue Offset    = Op.getOperand(1);
12703   SDValue Handler   = Op.getOperand(2);
12704   SDLoc dl      (Op);
12705
12706   EVT PtrVT = getPointerTy();
12707   const X86RegisterInfo *RegInfo =
12708     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12709   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12710   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12711           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12712          "Invalid Frame Register!");
12713   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12714   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12715
12716   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12717                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12718   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12719   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12720                        false, false, 0);
12721   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12722
12723   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12724                      DAG.getRegister(StoreAddrReg, PtrVT));
12725 }
12726
12727 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12728                                                SelectionDAG &DAG) const {
12729   SDLoc DL(Op);
12730   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12731                      DAG.getVTList(MVT::i32, MVT::Other),
12732                      Op.getOperand(0), Op.getOperand(1));
12733 }
12734
12735 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12736                                                 SelectionDAG &DAG) const {
12737   SDLoc DL(Op);
12738   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12739                      Op.getOperand(0), Op.getOperand(1));
12740 }
12741
12742 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12743   return Op.getOperand(0);
12744 }
12745
12746 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12747                                                 SelectionDAG &DAG) const {
12748   SDValue Root = Op.getOperand(0);
12749   SDValue Trmp = Op.getOperand(1); // trampoline
12750   SDValue FPtr = Op.getOperand(2); // nested function
12751   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12752   SDLoc dl (Op);
12753
12754   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12755   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12756
12757   if (Subtarget->is64Bit()) {
12758     SDValue OutChains[6];
12759
12760     // Large code-model.
12761     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12762     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12763
12764     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12765     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12766
12767     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12768
12769     // Load the pointer to the nested function into R11.
12770     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12771     SDValue Addr = Trmp;
12772     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12773                                 Addr, MachinePointerInfo(TrmpAddr),
12774                                 false, false, 0);
12775
12776     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12777                        DAG.getConstant(2, MVT::i64));
12778     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12779                                 MachinePointerInfo(TrmpAddr, 2),
12780                                 false, false, 2);
12781
12782     // Load the 'nest' parameter value into R10.
12783     // R10 is specified in X86CallingConv.td
12784     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12785     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12786                        DAG.getConstant(10, MVT::i64));
12787     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12788                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12789                                 false, false, 0);
12790
12791     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12792                        DAG.getConstant(12, MVT::i64));
12793     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12794                                 MachinePointerInfo(TrmpAddr, 12),
12795                                 false, false, 2);
12796
12797     // Jump to the nested function.
12798     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12799     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12800                        DAG.getConstant(20, MVT::i64));
12801     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12802                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12803                                 false, false, 0);
12804
12805     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12806     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12807                        DAG.getConstant(22, MVT::i64));
12808     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12809                                 MachinePointerInfo(TrmpAddr, 22),
12810                                 false, false, 0);
12811
12812     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12813   } else {
12814     const Function *Func =
12815       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12816     CallingConv::ID CC = Func->getCallingConv();
12817     unsigned NestReg;
12818
12819     switch (CC) {
12820     default:
12821       llvm_unreachable("Unsupported calling convention");
12822     case CallingConv::C:
12823     case CallingConv::X86_StdCall: {
12824       // Pass 'nest' parameter in ECX.
12825       // Must be kept in sync with X86CallingConv.td
12826       NestReg = X86::ECX;
12827
12828       // Check that ECX wasn't needed by an 'inreg' parameter.
12829       FunctionType *FTy = Func->getFunctionType();
12830       const AttributeSet &Attrs = Func->getAttributes();
12831
12832       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12833         unsigned InRegCount = 0;
12834         unsigned Idx = 1;
12835
12836         for (FunctionType::param_iterator I = FTy->param_begin(),
12837              E = FTy->param_end(); I != E; ++I, ++Idx)
12838           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12839             // FIXME: should only count parameters that are lowered to integers.
12840             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12841
12842         if (InRegCount > 2) {
12843           report_fatal_error("Nest register in use - reduce number of inreg"
12844                              " parameters!");
12845         }
12846       }
12847       break;
12848     }
12849     case CallingConv::X86_FastCall:
12850     case CallingConv::X86_ThisCall:
12851     case CallingConv::Fast:
12852       // Pass 'nest' parameter in EAX.
12853       // Must be kept in sync with X86CallingConv.td
12854       NestReg = X86::EAX;
12855       break;
12856     }
12857
12858     SDValue OutChains[4];
12859     SDValue Addr, Disp;
12860
12861     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12862                        DAG.getConstant(10, MVT::i32));
12863     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12864
12865     // This is storing the opcode for MOV32ri.
12866     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12867     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12868     OutChains[0] = DAG.getStore(Root, dl,
12869                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12870                                 Trmp, MachinePointerInfo(TrmpAddr),
12871                                 false, false, 0);
12872
12873     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12874                        DAG.getConstant(1, MVT::i32));
12875     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12876                                 MachinePointerInfo(TrmpAddr, 1),
12877                                 false, false, 1);
12878
12879     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12880     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12881                        DAG.getConstant(5, MVT::i32));
12882     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12883                                 MachinePointerInfo(TrmpAddr, 5),
12884                                 false, false, 1);
12885
12886     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12887                        DAG.getConstant(6, MVT::i32));
12888     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12889                                 MachinePointerInfo(TrmpAddr, 6),
12890                                 false, false, 1);
12891
12892     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12893   }
12894 }
12895
12896 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12897                                             SelectionDAG &DAG) const {
12898   /*
12899    The rounding mode is in bits 11:10 of FPSR, and has the following
12900    settings:
12901      00 Round to nearest
12902      01 Round to -inf
12903      10 Round to +inf
12904      11 Round to 0
12905
12906   FLT_ROUNDS, on the other hand, expects the following:
12907     -1 Undefined
12908      0 Round to 0
12909      1 Round to nearest
12910      2 Round to +inf
12911      3 Round to -inf
12912
12913   To perform the conversion, we do:
12914     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12915   */
12916
12917   MachineFunction &MF = DAG.getMachineFunction();
12918   const TargetMachine &TM = MF.getTarget();
12919   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12920   unsigned StackAlignment = TFI.getStackAlignment();
12921   MVT VT = Op.getSimpleValueType();
12922   SDLoc DL(Op);
12923
12924   // Save FP Control Word to stack slot
12925   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12926   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12927
12928   MachineMemOperand *MMO =
12929    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12930                            MachineMemOperand::MOStore, 2, 2);
12931
12932   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12933   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12934                                           DAG.getVTList(MVT::Other),
12935                                           Ops, array_lengthof(Ops), MVT::i16,
12936                                           MMO);
12937
12938   // Load FP Control Word from stack slot
12939   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12940                             MachinePointerInfo(), false, false, false, 0);
12941
12942   // Transform as necessary
12943   SDValue CWD1 =
12944     DAG.getNode(ISD::SRL, DL, MVT::i16,
12945                 DAG.getNode(ISD::AND, DL, MVT::i16,
12946                             CWD, DAG.getConstant(0x800, MVT::i16)),
12947                 DAG.getConstant(11, MVT::i8));
12948   SDValue CWD2 =
12949     DAG.getNode(ISD::SRL, DL, MVT::i16,
12950                 DAG.getNode(ISD::AND, DL, MVT::i16,
12951                             CWD, DAG.getConstant(0x400, MVT::i16)),
12952                 DAG.getConstant(9, MVT::i8));
12953
12954   SDValue RetVal =
12955     DAG.getNode(ISD::AND, DL, MVT::i16,
12956                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12957                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12958                             DAG.getConstant(1, MVT::i16)),
12959                 DAG.getConstant(3, MVT::i16));
12960
12961   return DAG.getNode((VT.getSizeInBits() < 16 ?
12962                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12963 }
12964
12965 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12966   MVT VT = Op.getSimpleValueType();
12967   EVT OpVT = VT;
12968   unsigned NumBits = VT.getSizeInBits();
12969   SDLoc dl(Op);
12970
12971   Op = Op.getOperand(0);
12972   if (VT == MVT::i8) {
12973     // Zero extend to i32 since there is not an i8 bsr.
12974     OpVT = MVT::i32;
12975     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12976   }
12977
12978   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12979   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12980   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12981
12982   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12983   SDValue Ops[] = {
12984     Op,
12985     DAG.getConstant(NumBits+NumBits-1, OpVT),
12986     DAG.getConstant(X86::COND_E, MVT::i8),
12987     Op.getValue(1)
12988   };
12989   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
12990
12991   // Finally xor with NumBits-1.
12992   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12993
12994   if (VT == MVT::i8)
12995     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12996   return Op;
12997 }
12998
12999 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13000   MVT VT = Op.getSimpleValueType();
13001   EVT OpVT = VT;
13002   unsigned NumBits = VT.getSizeInBits();
13003   SDLoc dl(Op);
13004
13005   Op = Op.getOperand(0);
13006   if (VT == MVT::i8) {
13007     // Zero extend to i32 since there is not an i8 bsr.
13008     OpVT = MVT::i32;
13009     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13010   }
13011
13012   // Issue a bsr (scan bits in reverse).
13013   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13014   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13015
13016   // And xor with NumBits-1.
13017   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13018
13019   if (VT == MVT::i8)
13020     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13021   return Op;
13022 }
13023
13024 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13025   MVT VT = Op.getSimpleValueType();
13026   unsigned NumBits = VT.getSizeInBits();
13027   SDLoc dl(Op);
13028   Op = Op.getOperand(0);
13029
13030   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13031   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13032   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13033
13034   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13035   SDValue Ops[] = {
13036     Op,
13037     DAG.getConstant(NumBits, VT),
13038     DAG.getConstant(X86::COND_E, MVT::i8),
13039     Op.getValue(1)
13040   };
13041   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13042 }
13043
13044 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13045 // ones, and then concatenate the result back.
13046 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13047   MVT VT = Op.getSimpleValueType();
13048
13049   assert(VT.is256BitVector() && VT.isInteger() &&
13050          "Unsupported value type for operation");
13051
13052   unsigned NumElems = VT.getVectorNumElements();
13053   SDLoc dl(Op);
13054
13055   // Extract the LHS vectors
13056   SDValue LHS = Op.getOperand(0);
13057   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13058   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13059
13060   // Extract the RHS vectors
13061   SDValue RHS = Op.getOperand(1);
13062   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13063   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13064
13065   MVT EltVT = VT.getVectorElementType();
13066   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13067
13068   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13069                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13070                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13071 }
13072
13073 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13074   assert(Op.getSimpleValueType().is256BitVector() &&
13075          Op.getSimpleValueType().isInteger() &&
13076          "Only handle AVX 256-bit vector integer operation");
13077   return Lower256IntArith(Op, DAG);
13078 }
13079
13080 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13081   assert(Op.getSimpleValueType().is256BitVector() &&
13082          Op.getSimpleValueType().isInteger() &&
13083          "Only handle AVX 256-bit vector integer operation");
13084   return Lower256IntArith(Op, DAG);
13085 }
13086
13087 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13088                         SelectionDAG &DAG) {
13089   SDLoc dl(Op);
13090   MVT VT = Op.getSimpleValueType();
13091
13092   // Decompose 256-bit ops into smaller 128-bit ops.
13093   if (VT.is256BitVector() && !Subtarget->hasInt256())
13094     return Lower256IntArith(Op, DAG);
13095
13096   SDValue A = Op.getOperand(0);
13097   SDValue B = Op.getOperand(1);
13098
13099   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13100   if (VT == MVT::v4i32) {
13101     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13102            "Should not custom lower when pmuldq is available!");
13103
13104     // Extract the odd parts.
13105     static const int UnpackMask[] = { 1, -1, 3, -1 };
13106     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13107     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13108
13109     // Multiply the even parts.
13110     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13111     // Now multiply odd parts.
13112     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13113
13114     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13115     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13116
13117     // Merge the two vectors back together with a shuffle. This expands into 2
13118     // shuffles.
13119     static const int ShufMask[] = { 0, 4, 2, 6 };
13120     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13121   }
13122
13123   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13124          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13125
13126   //  Ahi = psrlqi(a, 32);
13127   //  Bhi = psrlqi(b, 32);
13128   //
13129   //  AloBlo = pmuludq(a, b);
13130   //  AloBhi = pmuludq(a, Bhi);
13131   //  AhiBlo = pmuludq(Ahi, b);
13132
13133   //  AloBhi = psllqi(AloBhi, 32);
13134   //  AhiBlo = psllqi(AhiBlo, 32);
13135   //  return AloBlo + AloBhi + AhiBlo;
13136
13137   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13138   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13139
13140   // Bit cast to 32-bit vectors for MULUDQ
13141   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13142                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13143   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13144   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13145   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13146   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13147
13148   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13149   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13150   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13151
13152   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13153   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13154
13155   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13156   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13157 }
13158
13159 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13160                              SelectionDAG &DAG) {
13161   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13162   EVT VT = Op0.getValueType();
13163   SDLoc dl(Op);
13164
13165   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13166          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13167
13168   // Get the high parts.
13169   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13170   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13171   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13172
13173   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13174   // ints.
13175   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13176   unsigned Opcode =
13177       Op->getOpcode() == ISD::UMUL_LOHI ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13178   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13179                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13180   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13181                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13182
13183   // Shuffle it back into the right order.
13184   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13185   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13186   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13187   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13188
13189   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13190 }
13191
13192 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13193                                          const X86Subtarget *Subtarget) {
13194   MVT VT = Op.getSimpleValueType();
13195   SDLoc dl(Op);
13196   SDValue R = Op.getOperand(0);
13197   SDValue Amt = Op.getOperand(1);
13198
13199   // Optimize shl/srl/sra with constant shift amount.
13200   if (isSplatVector(Amt.getNode())) {
13201     SDValue SclrAmt = Amt->getOperand(0);
13202     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13203       uint64_t ShiftAmt = C->getZExtValue();
13204
13205       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13206           (Subtarget->hasInt256() &&
13207            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13208           (Subtarget->hasAVX512() &&
13209            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13210         if (Op.getOpcode() == ISD::SHL)
13211           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13212                                             DAG);
13213         if (Op.getOpcode() == ISD::SRL)
13214           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13215                                             DAG);
13216         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13217           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13218                                             DAG);
13219       }
13220
13221       if (VT == MVT::v16i8) {
13222         if (Op.getOpcode() == ISD::SHL) {
13223           // Make a large shift.
13224           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13225                                                    MVT::v8i16, R, ShiftAmt,
13226                                                    DAG);
13227           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13228           // Zero out the rightmost bits.
13229           SmallVector<SDValue, 16> V(16,
13230                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13231                                                      MVT::i8));
13232           return DAG.getNode(ISD::AND, dl, VT, SHL,
13233                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13234         }
13235         if (Op.getOpcode() == ISD::SRL) {
13236           // Make a large shift.
13237           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13238                                                    MVT::v8i16, R, ShiftAmt,
13239                                                    DAG);
13240           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13241           // Zero out the leftmost bits.
13242           SmallVector<SDValue, 16> V(16,
13243                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13244                                                      MVT::i8));
13245           return DAG.getNode(ISD::AND, dl, VT, SRL,
13246                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13247         }
13248         if (Op.getOpcode() == ISD::SRA) {
13249           if (ShiftAmt == 7) {
13250             // R s>> 7  ===  R s< 0
13251             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13252             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13253           }
13254
13255           // R s>> a === ((R u>> a) ^ m) - m
13256           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13257           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13258                                                          MVT::i8));
13259           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13260           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13261           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13262           return Res;
13263         }
13264         llvm_unreachable("Unknown shift opcode.");
13265       }
13266
13267       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13268         if (Op.getOpcode() == ISD::SHL) {
13269           // Make a large shift.
13270           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13271                                                    MVT::v16i16, R, ShiftAmt,
13272                                                    DAG);
13273           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13274           // Zero out the rightmost bits.
13275           SmallVector<SDValue, 32> V(32,
13276                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13277                                                      MVT::i8));
13278           return DAG.getNode(ISD::AND, dl, VT, SHL,
13279                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13280         }
13281         if (Op.getOpcode() == ISD::SRL) {
13282           // Make a large shift.
13283           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13284                                                    MVT::v16i16, R, ShiftAmt,
13285                                                    DAG);
13286           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13287           // Zero out the leftmost bits.
13288           SmallVector<SDValue, 32> V(32,
13289                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13290                                                      MVT::i8));
13291           return DAG.getNode(ISD::AND, dl, VT, SRL,
13292                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13293         }
13294         if (Op.getOpcode() == ISD::SRA) {
13295           if (ShiftAmt == 7) {
13296             // R s>> 7  ===  R s< 0
13297             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13298             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13299           }
13300
13301           // R s>> a === ((R u>> a) ^ m) - m
13302           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13303           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13304                                                          MVT::i8));
13305           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13306           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13307           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13308           return Res;
13309         }
13310         llvm_unreachable("Unknown shift opcode.");
13311       }
13312     }
13313   }
13314
13315   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13316   if (!Subtarget->is64Bit() &&
13317       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13318       Amt.getOpcode() == ISD::BITCAST &&
13319       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13320     Amt = Amt.getOperand(0);
13321     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13322                      VT.getVectorNumElements();
13323     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13324     uint64_t ShiftAmt = 0;
13325     for (unsigned i = 0; i != Ratio; ++i) {
13326       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13327       if (!C)
13328         return SDValue();
13329       // 6 == Log2(64)
13330       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13331     }
13332     // Check remaining shift amounts.
13333     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13334       uint64_t ShAmt = 0;
13335       for (unsigned j = 0; j != Ratio; ++j) {
13336         ConstantSDNode *C =
13337           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13338         if (!C)
13339           return SDValue();
13340         // 6 == Log2(64)
13341         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13342       }
13343       if (ShAmt != ShiftAmt)
13344         return SDValue();
13345     }
13346     switch (Op.getOpcode()) {
13347     default:
13348       llvm_unreachable("Unknown shift opcode!");
13349     case ISD::SHL:
13350       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13351                                         DAG);
13352     case ISD::SRL:
13353       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13354                                         DAG);
13355     case ISD::SRA:
13356       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13357                                         DAG);
13358     }
13359   }
13360
13361   return SDValue();
13362 }
13363
13364 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13365                                         const X86Subtarget* Subtarget) {
13366   MVT VT = Op.getSimpleValueType();
13367   SDLoc dl(Op);
13368   SDValue R = Op.getOperand(0);
13369   SDValue Amt = Op.getOperand(1);
13370
13371   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13372       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13373       (Subtarget->hasInt256() &&
13374        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13375         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13376        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13377     SDValue BaseShAmt;
13378     EVT EltVT = VT.getVectorElementType();
13379
13380     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13381       unsigned NumElts = VT.getVectorNumElements();
13382       unsigned i, j;
13383       for (i = 0; i != NumElts; ++i) {
13384         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13385           continue;
13386         break;
13387       }
13388       for (j = i; j != NumElts; ++j) {
13389         SDValue Arg = Amt.getOperand(j);
13390         if (Arg.getOpcode() == ISD::UNDEF) continue;
13391         if (Arg != Amt.getOperand(i))
13392           break;
13393       }
13394       if (i != NumElts && j == NumElts)
13395         BaseShAmt = Amt.getOperand(i);
13396     } else {
13397       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13398         Amt = Amt.getOperand(0);
13399       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13400                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13401         SDValue InVec = Amt.getOperand(0);
13402         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13403           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13404           unsigned i = 0;
13405           for (; i != NumElts; ++i) {
13406             SDValue Arg = InVec.getOperand(i);
13407             if (Arg.getOpcode() == ISD::UNDEF) continue;
13408             BaseShAmt = Arg;
13409             break;
13410           }
13411         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13412            if (ConstantSDNode *C =
13413                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13414              unsigned SplatIdx =
13415                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13416              if (C->getZExtValue() == SplatIdx)
13417                BaseShAmt = InVec.getOperand(1);
13418            }
13419         }
13420         if (!BaseShAmt.getNode())
13421           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13422                                   DAG.getIntPtrConstant(0));
13423       }
13424     }
13425
13426     if (BaseShAmt.getNode()) {
13427       if (EltVT.bitsGT(MVT::i32))
13428         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13429       else if (EltVT.bitsLT(MVT::i32))
13430         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13431
13432       switch (Op.getOpcode()) {
13433       default:
13434         llvm_unreachable("Unknown shift opcode!");
13435       case ISD::SHL:
13436         switch (VT.SimpleTy) {
13437         default: return SDValue();
13438         case MVT::v2i64:
13439         case MVT::v4i32:
13440         case MVT::v8i16:
13441         case MVT::v4i64:
13442         case MVT::v8i32:
13443         case MVT::v16i16:
13444         case MVT::v16i32:
13445         case MVT::v8i64:
13446           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13447         }
13448       case ISD::SRA:
13449         switch (VT.SimpleTy) {
13450         default: return SDValue();
13451         case MVT::v4i32:
13452         case MVT::v8i16:
13453         case MVT::v8i32:
13454         case MVT::v16i16:
13455         case MVT::v16i32:
13456         case MVT::v8i64:
13457           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13458         }
13459       case ISD::SRL:
13460         switch (VT.SimpleTy) {
13461         default: return SDValue();
13462         case MVT::v2i64:
13463         case MVT::v4i32:
13464         case MVT::v8i16:
13465         case MVT::v4i64:
13466         case MVT::v8i32:
13467         case MVT::v16i16:
13468         case MVT::v16i32:
13469         case MVT::v8i64:
13470           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13471         }
13472       }
13473     }
13474   }
13475
13476   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13477   if (!Subtarget->is64Bit() &&
13478       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13479       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13480       Amt.getOpcode() == ISD::BITCAST &&
13481       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13482     Amt = Amt.getOperand(0);
13483     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13484                      VT.getVectorNumElements();
13485     std::vector<SDValue> Vals(Ratio);
13486     for (unsigned i = 0; i != Ratio; ++i)
13487       Vals[i] = Amt.getOperand(i);
13488     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13489       for (unsigned j = 0; j != Ratio; ++j)
13490         if (Vals[j] != Amt.getOperand(i + j))
13491           return SDValue();
13492     }
13493     switch (Op.getOpcode()) {
13494     default:
13495       llvm_unreachable("Unknown shift opcode!");
13496     case ISD::SHL:
13497       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13498     case ISD::SRL:
13499       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13500     case ISD::SRA:
13501       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13502     }
13503   }
13504
13505   return SDValue();
13506 }
13507
13508 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13509                           SelectionDAG &DAG) {
13510
13511   MVT VT = Op.getSimpleValueType();
13512   SDLoc dl(Op);
13513   SDValue R = Op.getOperand(0);
13514   SDValue Amt = Op.getOperand(1);
13515   SDValue V;
13516
13517   if (!Subtarget->hasSSE2())
13518     return SDValue();
13519
13520   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13521   if (V.getNode())
13522     return V;
13523
13524   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13525   if (V.getNode())
13526       return V;
13527
13528   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13529     return Op;
13530   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13531   if (Subtarget->hasInt256()) {
13532     if (Op.getOpcode() == ISD::SRL &&
13533         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13534          VT == MVT::v4i64 || VT == MVT::v8i32))
13535       return Op;
13536     if (Op.getOpcode() == ISD::SHL &&
13537         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13538          VT == MVT::v4i64 || VT == MVT::v8i32))
13539       return Op;
13540     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13541       return Op;
13542   }
13543
13544   // If possible, lower this packed shift into a vector multiply instead of
13545   // expanding it into a sequence of scalar shifts.
13546   // Do this only if the vector shift count is a constant build_vector.
13547   if (Op.getOpcode() == ISD::SHL && 
13548       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13549        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13550       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13551     SmallVector<SDValue, 8> Elts;
13552     EVT SVT = VT.getScalarType();
13553     unsigned SVTBits = SVT.getSizeInBits();
13554     const APInt &One = APInt(SVTBits, 1);
13555     unsigned NumElems = VT.getVectorNumElements();
13556
13557     for (unsigned i=0; i !=NumElems; ++i) {
13558       SDValue Op = Amt->getOperand(i);
13559       if (Op->getOpcode() == ISD::UNDEF) {
13560         Elts.push_back(Op);
13561         continue;
13562       }
13563
13564       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13565       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13566       uint64_t ShAmt = C.getZExtValue();
13567       if (ShAmt >= SVTBits) {
13568         Elts.push_back(DAG.getUNDEF(SVT));
13569         continue;
13570       }
13571       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13572     }
13573     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13574     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13575   }
13576
13577   // Lower SHL with variable shift amount.
13578   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13579     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13580
13581     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13582     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13583     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13584     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13585   }
13586
13587   // If possible, lower this shift as a sequence of two shifts by
13588   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13589   // Example:
13590   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13591   //
13592   // Could be rewritten as:
13593   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13594   //
13595   // The advantage is that the two shifts from the example would be
13596   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13597   // the vector shift into four scalar shifts plus four pairs of vector
13598   // insert/extract.
13599   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13600       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13601     unsigned TargetOpcode = X86ISD::MOVSS;
13602     bool CanBeSimplified;
13603     // The splat value for the first packed shift (the 'X' from the example).
13604     SDValue Amt1 = Amt->getOperand(0);
13605     // The splat value for the second packed shift (the 'Y' from the example).
13606     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13607                                         Amt->getOperand(2);
13608
13609     // See if it is possible to replace this node with a sequence of
13610     // two shifts followed by a MOVSS/MOVSD
13611     if (VT == MVT::v4i32) {
13612       // Check if it is legal to use a MOVSS.
13613       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13614                         Amt2 == Amt->getOperand(3);
13615       if (!CanBeSimplified) {
13616         // Otherwise, check if we can still simplify this node using a MOVSD.
13617         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13618                           Amt->getOperand(2) == Amt->getOperand(3);
13619         TargetOpcode = X86ISD::MOVSD;
13620         Amt2 = Amt->getOperand(2);
13621       }
13622     } else {
13623       // Do similar checks for the case where the machine value type
13624       // is MVT::v8i16.
13625       CanBeSimplified = Amt1 == Amt->getOperand(1);
13626       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13627         CanBeSimplified = Amt2 == Amt->getOperand(i);
13628
13629       if (!CanBeSimplified) {
13630         TargetOpcode = X86ISD::MOVSD;
13631         CanBeSimplified = true;
13632         Amt2 = Amt->getOperand(4);
13633         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13634           CanBeSimplified = Amt1 == Amt->getOperand(i);
13635         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13636           CanBeSimplified = Amt2 == Amt->getOperand(j);
13637       }
13638     }
13639     
13640     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13641         isa<ConstantSDNode>(Amt2)) {
13642       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13643       EVT CastVT = MVT::v4i32;
13644       SDValue Splat1 = 
13645         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13646       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13647       SDValue Splat2 = 
13648         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13649       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13650       if (TargetOpcode == X86ISD::MOVSD)
13651         CastVT = MVT::v2i64;
13652       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13653       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13654       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13655                                             BitCast1, DAG);
13656       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13657     }
13658   }
13659
13660   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13661     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13662
13663     // a = a << 5;
13664     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13665     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13666
13667     // Turn 'a' into a mask suitable for VSELECT
13668     SDValue VSelM = DAG.getConstant(0x80, VT);
13669     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13670     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13671
13672     SDValue CM1 = DAG.getConstant(0x0f, VT);
13673     SDValue CM2 = DAG.getConstant(0x3f, VT);
13674
13675     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13676     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13677     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13678     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13679     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13680
13681     // a += a
13682     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13683     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13684     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13685
13686     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13687     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13688     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13689     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13690     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13691
13692     // a += a
13693     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13694     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13695     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13696
13697     // return VSELECT(r, r+r, a);
13698     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13699                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13700     return R;
13701   }
13702
13703   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13704   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13705   // solution better.
13706   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13707     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13708     unsigned ExtOpc =
13709         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13710     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13711     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13712     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13713                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13714     }
13715
13716   // Decompose 256-bit shifts into smaller 128-bit shifts.
13717   if (VT.is256BitVector()) {
13718     unsigned NumElems = VT.getVectorNumElements();
13719     MVT EltVT = VT.getVectorElementType();
13720     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13721
13722     // Extract the two vectors
13723     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13724     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13725
13726     // Recreate the shift amount vectors
13727     SDValue Amt1, Amt2;
13728     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13729       // Constant shift amount
13730       SmallVector<SDValue, 4> Amt1Csts;
13731       SmallVector<SDValue, 4> Amt2Csts;
13732       for (unsigned i = 0; i != NumElems/2; ++i)
13733         Amt1Csts.push_back(Amt->getOperand(i));
13734       for (unsigned i = NumElems/2; i != NumElems; ++i)
13735         Amt2Csts.push_back(Amt->getOperand(i));
13736
13737       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13738       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13739     } else {
13740       // Variable shift amount
13741       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13742       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13743     }
13744
13745     // Issue new vector shifts for the smaller types
13746     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13747     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13748
13749     // Concatenate the result back
13750     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13751   }
13752
13753   return SDValue();
13754 }
13755
13756 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13757   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13758   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13759   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13760   // has only one use.
13761   SDNode *N = Op.getNode();
13762   SDValue LHS = N->getOperand(0);
13763   SDValue RHS = N->getOperand(1);
13764   unsigned BaseOp = 0;
13765   unsigned Cond = 0;
13766   SDLoc DL(Op);
13767   switch (Op.getOpcode()) {
13768   default: llvm_unreachable("Unknown ovf instruction!");
13769   case ISD::SADDO:
13770     // A subtract of one will be selected as a INC. Note that INC doesn't
13771     // set CF, so we can't do this for UADDO.
13772     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13773       if (C->isOne()) {
13774         BaseOp = X86ISD::INC;
13775         Cond = X86::COND_O;
13776         break;
13777       }
13778     BaseOp = X86ISD::ADD;
13779     Cond = X86::COND_O;
13780     break;
13781   case ISD::UADDO:
13782     BaseOp = X86ISD::ADD;
13783     Cond = X86::COND_B;
13784     break;
13785   case ISD::SSUBO:
13786     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13787     // set CF, so we can't do this for USUBO.
13788     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13789       if (C->isOne()) {
13790         BaseOp = X86ISD::DEC;
13791         Cond = X86::COND_O;
13792         break;
13793       }
13794     BaseOp = X86ISD::SUB;
13795     Cond = X86::COND_O;
13796     break;
13797   case ISD::USUBO:
13798     BaseOp = X86ISD::SUB;
13799     Cond = X86::COND_B;
13800     break;
13801   case ISD::SMULO:
13802     BaseOp = X86ISD::SMUL;
13803     Cond = X86::COND_O;
13804     break;
13805   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13806     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13807                                  MVT::i32);
13808     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13809
13810     SDValue SetCC =
13811       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13812                   DAG.getConstant(X86::COND_O, MVT::i32),
13813                   SDValue(Sum.getNode(), 2));
13814
13815     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13816   }
13817   }
13818
13819   // Also sets EFLAGS.
13820   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13821   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13822
13823   SDValue SetCC =
13824     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13825                 DAG.getConstant(Cond, MVT::i32),
13826                 SDValue(Sum.getNode(), 1));
13827
13828   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13829 }
13830
13831 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13832                                                   SelectionDAG &DAG) const {
13833   SDLoc dl(Op);
13834   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13835   MVT VT = Op.getSimpleValueType();
13836
13837   if (!Subtarget->hasSSE2() || !VT.isVector())
13838     return SDValue();
13839
13840   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13841                       ExtraVT.getScalarType().getSizeInBits();
13842
13843   switch (VT.SimpleTy) {
13844     default: return SDValue();
13845     case MVT::v8i32:
13846     case MVT::v16i16:
13847       if (!Subtarget->hasFp256())
13848         return SDValue();
13849       if (!Subtarget->hasInt256()) {
13850         // needs to be split
13851         unsigned NumElems = VT.getVectorNumElements();
13852
13853         // Extract the LHS vectors
13854         SDValue LHS = Op.getOperand(0);
13855         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13856         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13857
13858         MVT EltVT = VT.getVectorElementType();
13859         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13860
13861         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13862         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13863         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13864                                    ExtraNumElems/2);
13865         SDValue Extra = DAG.getValueType(ExtraVT);
13866
13867         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13868         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13869
13870         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13871       }
13872       // fall through
13873     case MVT::v4i32:
13874     case MVT::v8i16: {
13875       SDValue Op0 = Op.getOperand(0);
13876       SDValue Op00 = Op0.getOperand(0);
13877       SDValue Tmp1;
13878       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13879       if (Op0.getOpcode() == ISD::BITCAST &&
13880           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13881         // (sext (vzext x)) -> (vsext x)
13882         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13883         if (Tmp1.getNode()) {
13884           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13885           // This folding is only valid when the in-reg type is a vector of i8,
13886           // i16, or i32.
13887           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13888               ExtraEltVT == MVT::i32) {
13889             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13890             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13891                    "This optimization is invalid without a VZEXT.");
13892             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13893           }
13894           Op0 = Tmp1;
13895         }
13896       }
13897
13898       // If the above didn't work, then just use Shift-Left + Shift-Right.
13899       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13900                                         DAG);
13901       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13902                                         DAG);
13903     }
13904   }
13905 }
13906
13907 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13908                                  SelectionDAG &DAG) {
13909   SDLoc dl(Op);
13910   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13911     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13912   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13913     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13914
13915   // The only fence that needs an instruction is a sequentially-consistent
13916   // cross-thread fence.
13917   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13918     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13919     // no-sse2). There isn't any reason to disable it if the target processor
13920     // supports it.
13921     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13922       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13923
13924     SDValue Chain = Op.getOperand(0);
13925     SDValue Zero = DAG.getConstant(0, MVT::i32);
13926     SDValue Ops[] = {
13927       DAG.getRegister(X86::ESP, MVT::i32), // Base
13928       DAG.getTargetConstant(1, MVT::i8),   // Scale
13929       DAG.getRegister(0, MVT::i32),        // Index
13930       DAG.getTargetConstant(0, MVT::i32),  // Disp
13931       DAG.getRegister(0, MVT::i32),        // Segment.
13932       Zero,
13933       Chain
13934     };
13935     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13936     return SDValue(Res, 0);
13937   }
13938
13939   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13940   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13941 }
13942
13943 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13944                              SelectionDAG &DAG) {
13945   MVT T = Op.getSimpleValueType();
13946   SDLoc DL(Op);
13947   unsigned Reg = 0;
13948   unsigned size = 0;
13949   switch(T.SimpleTy) {
13950   default: llvm_unreachable("Invalid value type!");
13951   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13952   case MVT::i16: Reg = X86::AX;  size = 2; break;
13953   case MVT::i32: Reg = X86::EAX; size = 4; break;
13954   case MVT::i64:
13955     assert(Subtarget->is64Bit() && "Node not type legal!");
13956     Reg = X86::RAX; size = 8;
13957     break;
13958   }
13959   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13960                                     Op.getOperand(2), SDValue());
13961   SDValue Ops[] = { cpIn.getValue(0),
13962                     Op.getOperand(1),
13963                     Op.getOperand(3),
13964                     DAG.getTargetConstant(size, MVT::i8),
13965                     cpIn.getValue(1) };
13966   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13967   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13968   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13969                                            Ops, array_lengthof(Ops), T, MMO);
13970   SDValue cpOut =
13971     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13972   return cpOut;
13973 }
13974
13975 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13976                             SelectionDAG &DAG) {
13977   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13978   MVT DstVT = Op.getSimpleValueType();
13979   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13980          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13981   assert((DstVT == MVT::i64 ||
13982           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13983          "Unexpected custom BITCAST");
13984   // i64 <=> MMX conversions are Legal.
13985   if (SrcVT==MVT::i64 && DstVT.isVector())
13986     return Op;
13987   if (DstVT==MVT::i64 && SrcVT.isVector())
13988     return Op;
13989   // MMX <=> MMX conversions are Legal.
13990   if (SrcVT.isVector() && DstVT.isVector())
13991     return Op;
13992   // All other conversions need to be expanded.
13993   return SDValue();
13994 }
13995
13996 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13997   SDNode *Node = Op.getNode();
13998   SDLoc dl(Node);
13999   EVT T = Node->getValueType(0);
14000   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14001                               DAG.getConstant(0, T), Node->getOperand(2));
14002   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14003                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14004                        Node->getOperand(0),
14005                        Node->getOperand(1), negOp,
14006                        cast<AtomicSDNode>(Node)->getMemOperand(),
14007                        cast<AtomicSDNode>(Node)->getOrdering(),
14008                        cast<AtomicSDNode>(Node)->getSynchScope());
14009 }
14010
14011 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14012   SDNode *Node = Op.getNode();
14013   SDLoc dl(Node);
14014   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14015
14016   // Convert seq_cst store -> xchg
14017   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14018   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14019   //        (The only way to get a 16-byte store is cmpxchg16b)
14020   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14021   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14022       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14023     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14024                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14025                                  Node->getOperand(0),
14026                                  Node->getOperand(1), Node->getOperand(2),
14027                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14028                                  cast<AtomicSDNode>(Node)->getOrdering(),
14029                                  cast<AtomicSDNode>(Node)->getSynchScope());
14030     return Swap.getValue(1);
14031   }
14032   // Other atomic stores have a simple pattern.
14033   return Op;
14034 }
14035
14036 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14037   EVT VT = Op.getNode()->getSimpleValueType(0);
14038
14039   // Let legalize expand this if it isn't a legal type yet.
14040   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14041     return SDValue();
14042
14043   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14044
14045   unsigned Opc;
14046   bool ExtraOp = false;
14047   switch (Op.getOpcode()) {
14048   default: llvm_unreachable("Invalid code");
14049   case ISD::ADDC: Opc = X86ISD::ADD; break;
14050   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14051   case ISD::SUBC: Opc = X86ISD::SUB; break;
14052   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14053   }
14054
14055   if (!ExtraOp)
14056     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14057                        Op.getOperand(1));
14058   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14059                      Op.getOperand(1), Op.getOperand(2));
14060 }
14061
14062 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14063                             SelectionDAG &DAG) {
14064   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14065
14066   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14067   // which returns the values as { float, float } (in XMM0) or
14068   // { double, double } (which is returned in XMM0, XMM1).
14069   SDLoc dl(Op);
14070   SDValue Arg = Op.getOperand(0);
14071   EVT ArgVT = Arg.getValueType();
14072   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14073
14074   TargetLowering::ArgListTy Args;
14075   TargetLowering::ArgListEntry Entry;
14076
14077   Entry.Node = Arg;
14078   Entry.Ty = ArgTy;
14079   Entry.isSExt = false;
14080   Entry.isZExt = false;
14081   Args.push_back(Entry);
14082
14083   bool isF64 = ArgVT == MVT::f64;
14084   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14085   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14086   // the results are returned via SRet in memory.
14087   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14088   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14089   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14090
14091   Type *RetTy = isF64
14092     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14093     : (Type*)VectorType::get(ArgTy, 4);
14094   TargetLowering::
14095     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14096                          false, false, false, false, 0,
14097                          CallingConv::C, /*isTaillCall=*/false,
14098                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14099                          Callee, Args, DAG, dl);
14100   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14101
14102   if (isF64)
14103     // Returned in xmm0 and xmm1.
14104     return CallResult.first;
14105
14106   // Returned in bits 0:31 and 32:64 xmm0.
14107   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14108                                CallResult.first, DAG.getIntPtrConstant(0));
14109   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14110                                CallResult.first, DAG.getIntPtrConstant(1));
14111   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14112   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14113 }
14114
14115 /// LowerOperation - Provide custom lowering hooks for some operations.
14116 ///
14117 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14118   switch (Op.getOpcode()) {
14119   default: llvm_unreachable("Should not custom lower this!");
14120   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14121   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14122   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14123   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14124   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14125   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14126   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14127   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14128   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14129   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14130   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14131   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14132   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14133   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14134   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14135   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14136   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14137   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14138   case ISD::SHL_PARTS:
14139   case ISD::SRA_PARTS:
14140   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14141   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14142   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14143   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14144   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14145   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14146   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14147   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14148   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14149   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14150   case ISD::FABS:               return LowerFABS(Op, DAG);
14151   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14152   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14153   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14154   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14155   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14156   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14157   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14158   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14159   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14160   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14161   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14162   case ISD::INTRINSIC_VOID:
14163   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14164   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14165   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14166   case ISD::FRAME_TO_ARGS_OFFSET:
14167                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14168   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14169   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14170   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14171   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14172   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14173   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14174   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14175   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14176   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14177   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14178   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14179   case ISD::UMUL_LOHI:
14180   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14181   case ISD::SRA:
14182   case ISD::SRL:
14183   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14184   case ISD::SADDO:
14185   case ISD::UADDO:
14186   case ISD::SSUBO:
14187   case ISD::USUBO:
14188   case ISD::SMULO:
14189   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14190   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14191   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14192   case ISD::ADDC:
14193   case ISD::ADDE:
14194   case ISD::SUBC:
14195   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14196   case ISD::ADD:                return LowerADD(Op, DAG);
14197   case ISD::SUB:                return LowerSUB(Op, DAG);
14198   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14199   }
14200 }
14201
14202 static void ReplaceATOMIC_LOAD(SDNode *Node,
14203                                   SmallVectorImpl<SDValue> &Results,
14204                                   SelectionDAG &DAG) {
14205   SDLoc dl(Node);
14206   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14207
14208   // Convert wide load -> cmpxchg8b/cmpxchg16b
14209   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14210   //        (The only way to get a 16-byte load is cmpxchg16b)
14211   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14212   SDValue Zero = DAG.getConstant(0, VT);
14213   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14214                                Node->getOperand(0),
14215                                Node->getOperand(1), Zero, Zero,
14216                                cast<AtomicSDNode>(Node)->getMemOperand(),
14217                                cast<AtomicSDNode>(Node)->getOrdering(),
14218                                cast<AtomicSDNode>(Node)->getOrdering(),
14219                                cast<AtomicSDNode>(Node)->getSynchScope());
14220   Results.push_back(Swap.getValue(0));
14221   Results.push_back(Swap.getValue(1));
14222 }
14223
14224 static void
14225 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14226                         SelectionDAG &DAG, unsigned NewOp) {
14227   SDLoc dl(Node);
14228   assert (Node->getValueType(0) == MVT::i64 &&
14229           "Only know how to expand i64 atomics");
14230
14231   SDValue Chain = Node->getOperand(0);
14232   SDValue In1 = Node->getOperand(1);
14233   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14234                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14235   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14236                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14237   SDValue Ops[] = { Chain, In1, In2L, In2H };
14238   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14239   SDValue Result =
14240     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
14241                             cast<MemSDNode>(Node)->getMemOperand());
14242   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14243   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14244   Results.push_back(Result.getValue(2));
14245 }
14246
14247 /// ReplaceNodeResults - Replace a node with an illegal result type
14248 /// with a new node built out of custom code.
14249 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14250                                            SmallVectorImpl<SDValue>&Results,
14251                                            SelectionDAG &DAG) const {
14252   SDLoc dl(N);
14253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14254   switch (N->getOpcode()) {
14255   default:
14256     llvm_unreachable("Do not know how to custom type legalize this operation!");
14257   case ISD::SIGN_EXTEND_INREG:
14258   case ISD::ADDC:
14259   case ISD::ADDE:
14260   case ISD::SUBC:
14261   case ISD::SUBE:
14262     // We don't want to expand or promote these.
14263     return;
14264   case ISD::FP_TO_SINT:
14265   case ISD::FP_TO_UINT: {
14266     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14267
14268     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14269       return;
14270
14271     std::pair<SDValue,SDValue> Vals =
14272         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14273     SDValue FIST = Vals.first, StackSlot = Vals.second;
14274     if (FIST.getNode()) {
14275       EVT VT = N->getValueType(0);
14276       // Return a load from the stack slot.
14277       if (StackSlot.getNode())
14278         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14279                                       MachinePointerInfo(),
14280                                       false, false, false, 0));
14281       else
14282         Results.push_back(FIST);
14283     }
14284     return;
14285   }
14286   case ISD::UINT_TO_FP: {
14287     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14288     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14289         N->getValueType(0) != MVT::v2f32)
14290       return;
14291     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14292                                  N->getOperand(0));
14293     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14294                                      MVT::f64);
14295     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14296     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14297                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14298     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14299     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14300     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14301     return;
14302   }
14303   case ISD::FP_ROUND: {
14304     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14305         return;
14306     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14307     Results.push_back(V);
14308     return;
14309   }
14310   case ISD::INTRINSIC_W_CHAIN: {
14311     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14312     switch (IntNo) {
14313     default : llvm_unreachable("Do not know how to custom type "
14314                                "legalize this intrinsic operation!");
14315     case Intrinsic::x86_rdtsc:
14316       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14317                                      Results);
14318     case Intrinsic::x86_rdtscp:
14319       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14320                                      Results);
14321     }
14322   }
14323   case ISD::READCYCLECOUNTER: {
14324     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14325                                    Results);
14326   }
14327   case ISD::ATOMIC_CMP_SWAP: {
14328     EVT T = N->getValueType(0);
14329     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14330     bool Regs64bit = T == MVT::i128;
14331     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14332     SDValue cpInL, cpInH;
14333     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14334                         DAG.getConstant(0, HalfT));
14335     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14336                         DAG.getConstant(1, HalfT));
14337     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14338                              Regs64bit ? X86::RAX : X86::EAX,
14339                              cpInL, SDValue());
14340     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14341                              Regs64bit ? X86::RDX : X86::EDX,
14342                              cpInH, cpInL.getValue(1));
14343     SDValue swapInL, swapInH;
14344     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14345                           DAG.getConstant(0, HalfT));
14346     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14347                           DAG.getConstant(1, HalfT));
14348     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14349                                Regs64bit ? X86::RBX : X86::EBX,
14350                                swapInL, cpInH.getValue(1));
14351     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14352                                Regs64bit ? X86::RCX : X86::ECX,
14353                                swapInH, swapInL.getValue(1));
14354     SDValue Ops[] = { swapInH.getValue(0),
14355                       N->getOperand(1),
14356                       swapInH.getValue(1) };
14357     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14358     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14359     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14360                                   X86ISD::LCMPXCHG8_DAG;
14361     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
14362                                              Ops, array_lengthof(Ops), T, MMO);
14363     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14364                                         Regs64bit ? X86::RAX : X86::EAX,
14365                                         HalfT, Result.getValue(1));
14366     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14367                                         Regs64bit ? X86::RDX : X86::EDX,
14368                                         HalfT, cpOutL.getValue(2));
14369     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14370     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14371     Results.push_back(cpOutH.getValue(1));
14372     return;
14373   }
14374   case ISD::ATOMIC_LOAD_ADD:
14375   case ISD::ATOMIC_LOAD_AND:
14376   case ISD::ATOMIC_LOAD_NAND:
14377   case ISD::ATOMIC_LOAD_OR:
14378   case ISD::ATOMIC_LOAD_SUB:
14379   case ISD::ATOMIC_LOAD_XOR:
14380   case ISD::ATOMIC_LOAD_MAX:
14381   case ISD::ATOMIC_LOAD_MIN:
14382   case ISD::ATOMIC_LOAD_UMAX:
14383   case ISD::ATOMIC_LOAD_UMIN:
14384   case ISD::ATOMIC_SWAP: {
14385     unsigned Opc;
14386     switch (N->getOpcode()) {
14387     default: llvm_unreachable("Unexpected opcode");
14388     case ISD::ATOMIC_LOAD_ADD:
14389       Opc = X86ISD::ATOMADD64_DAG;
14390       break;
14391     case ISD::ATOMIC_LOAD_AND:
14392       Opc = X86ISD::ATOMAND64_DAG;
14393       break;
14394     case ISD::ATOMIC_LOAD_NAND:
14395       Opc = X86ISD::ATOMNAND64_DAG;
14396       break;
14397     case ISD::ATOMIC_LOAD_OR:
14398       Opc = X86ISD::ATOMOR64_DAG;
14399       break;
14400     case ISD::ATOMIC_LOAD_SUB:
14401       Opc = X86ISD::ATOMSUB64_DAG;
14402       break;
14403     case ISD::ATOMIC_LOAD_XOR:
14404       Opc = X86ISD::ATOMXOR64_DAG;
14405       break;
14406     case ISD::ATOMIC_LOAD_MAX:
14407       Opc = X86ISD::ATOMMAX64_DAG;
14408       break;
14409     case ISD::ATOMIC_LOAD_MIN:
14410       Opc = X86ISD::ATOMMIN64_DAG;
14411       break;
14412     case ISD::ATOMIC_LOAD_UMAX:
14413       Opc = X86ISD::ATOMUMAX64_DAG;
14414       break;
14415     case ISD::ATOMIC_LOAD_UMIN:
14416       Opc = X86ISD::ATOMUMIN64_DAG;
14417       break;
14418     case ISD::ATOMIC_SWAP:
14419       Opc = X86ISD::ATOMSWAP64_DAG;
14420       break;
14421     }
14422     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14423     return;
14424   }
14425   case ISD::ATOMIC_LOAD:
14426     ReplaceATOMIC_LOAD(N, Results, DAG);
14427   }
14428 }
14429
14430 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14431   switch (Opcode) {
14432   default: return nullptr;
14433   case X86ISD::BSF:                return "X86ISD::BSF";
14434   case X86ISD::BSR:                return "X86ISD::BSR";
14435   case X86ISD::SHLD:               return "X86ISD::SHLD";
14436   case X86ISD::SHRD:               return "X86ISD::SHRD";
14437   case X86ISD::FAND:               return "X86ISD::FAND";
14438   case X86ISD::FANDN:              return "X86ISD::FANDN";
14439   case X86ISD::FOR:                return "X86ISD::FOR";
14440   case X86ISD::FXOR:               return "X86ISD::FXOR";
14441   case X86ISD::FSRL:               return "X86ISD::FSRL";
14442   case X86ISD::FILD:               return "X86ISD::FILD";
14443   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14444   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14445   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14446   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14447   case X86ISD::FLD:                return "X86ISD::FLD";
14448   case X86ISD::FST:                return "X86ISD::FST";
14449   case X86ISD::CALL:               return "X86ISD::CALL";
14450   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14451   case X86ISD::BT:                 return "X86ISD::BT";
14452   case X86ISD::CMP:                return "X86ISD::CMP";
14453   case X86ISD::COMI:               return "X86ISD::COMI";
14454   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14455   case X86ISD::CMPM:               return "X86ISD::CMPM";
14456   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14457   case X86ISD::SETCC:              return "X86ISD::SETCC";
14458   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14459   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14460   case X86ISD::CMOV:               return "X86ISD::CMOV";
14461   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14462   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14463   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14464   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14465   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14466   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14467   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14468   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14469   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14470   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14471   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14472   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14473   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14474   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14475   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14476   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14477   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14478   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14479   case X86ISD::HADD:               return "X86ISD::HADD";
14480   case X86ISD::HSUB:               return "X86ISD::HSUB";
14481   case X86ISD::FHADD:              return "X86ISD::FHADD";
14482   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14483   case X86ISD::UMAX:               return "X86ISD::UMAX";
14484   case X86ISD::UMIN:               return "X86ISD::UMIN";
14485   case X86ISD::SMAX:               return "X86ISD::SMAX";
14486   case X86ISD::SMIN:               return "X86ISD::SMIN";
14487   case X86ISD::FMAX:               return "X86ISD::FMAX";
14488   case X86ISD::FMIN:               return "X86ISD::FMIN";
14489   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14490   case X86ISD::FMINC:              return "X86ISD::FMINC";
14491   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14492   case X86ISD::FRCP:               return "X86ISD::FRCP";
14493   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14494   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14495   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14496   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14497   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14498   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14499   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14500   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14501   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14502   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14503   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14504   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14505   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14506   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14507   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14508   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14509   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14510   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14511   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14512   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14513   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14514   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14515   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14516   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14517   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14518   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14519   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14520   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14521   case X86ISD::VSHL:               return "X86ISD::VSHL";
14522   case X86ISD::VSRL:               return "X86ISD::VSRL";
14523   case X86ISD::VSRA:               return "X86ISD::VSRA";
14524   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14525   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14526   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14527   case X86ISD::CMPP:               return "X86ISD::CMPP";
14528   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14529   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14530   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14531   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14532   case X86ISD::ADD:                return "X86ISD::ADD";
14533   case X86ISD::SUB:                return "X86ISD::SUB";
14534   case X86ISD::ADC:                return "X86ISD::ADC";
14535   case X86ISD::SBB:                return "X86ISD::SBB";
14536   case X86ISD::SMUL:               return "X86ISD::SMUL";
14537   case X86ISD::UMUL:               return "X86ISD::UMUL";
14538   case X86ISD::INC:                return "X86ISD::INC";
14539   case X86ISD::DEC:                return "X86ISD::DEC";
14540   case X86ISD::OR:                 return "X86ISD::OR";
14541   case X86ISD::XOR:                return "X86ISD::XOR";
14542   case X86ISD::AND:                return "X86ISD::AND";
14543   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14544   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14545   case X86ISD::PTEST:              return "X86ISD::PTEST";
14546   case X86ISD::TESTP:              return "X86ISD::TESTP";
14547   case X86ISD::TESTM:              return "X86ISD::TESTM";
14548   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14549   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14550   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14551   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14552   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14553   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14554   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14555   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14556   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14557   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14558   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14559   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14560   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14561   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14562   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14563   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14564   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14565   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14566   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14567   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14568   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14569   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14570   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14571   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14572   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14573   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14574   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14575   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14576   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14577   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14578   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14579   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14580   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14581   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14582   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14583   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14584   case X86ISD::SAHF:               return "X86ISD::SAHF";
14585   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14586   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14587   case X86ISD::FMADD:              return "X86ISD::FMADD";
14588   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14589   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14590   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14591   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14592   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14593   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14594   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14595   case X86ISD::XTEST:              return "X86ISD::XTEST";
14596   }
14597 }
14598
14599 // isLegalAddressingMode - Return true if the addressing mode represented
14600 // by AM is legal for this target, for a load/store of the specified type.
14601 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14602                                               Type *Ty) const {
14603   // X86 supports extremely general addressing modes.
14604   CodeModel::Model M = getTargetMachine().getCodeModel();
14605   Reloc::Model R = getTargetMachine().getRelocationModel();
14606
14607   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14608   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14609     return false;
14610
14611   if (AM.BaseGV) {
14612     unsigned GVFlags =
14613       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14614
14615     // If a reference to this global requires an extra load, we can't fold it.
14616     if (isGlobalStubReference(GVFlags))
14617       return false;
14618
14619     // If BaseGV requires a register for the PIC base, we cannot also have a
14620     // BaseReg specified.
14621     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14622       return false;
14623
14624     // If lower 4G is not available, then we must use rip-relative addressing.
14625     if ((M != CodeModel::Small || R != Reloc::Static) &&
14626         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14627       return false;
14628   }
14629
14630   switch (AM.Scale) {
14631   case 0:
14632   case 1:
14633   case 2:
14634   case 4:
14635   case 8:
14636     // These scales always work.
14637     break;
14638   case 3:
14639   case 5:
14640   case 9:
14641     // These scales are formed with basereg+scalereg.  Only accept if there is
14642     // no basereg yet.
14643     if (AM.HasBaseReg)
14644       return false;
14645     break;
14646   default:  // Other stuff never works.
14647     return false;
14648   }
14649
14650   return true;
14651 }
14652
14653 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14654   unsigned Bits = Ty->getScalarSizeInBits();
14655
14656   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14657   // particularly cheaper than those without.
14658   if (Bits == 8)
14659     return false;
14660
14661   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14662   // variable shifts just as cheap as scalar ones.
14663   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14664     return false;
14665
14666   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14667   // fully general vector.
14668   return true;
14669 }
14670
14671 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14672   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14673     return false;
14674   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14675   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14676   return NumBits1 > NumBits2;
14677 }
14678
14679 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14680   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14681     return false;
14682
14683   if (!isTypeLegal(EVT::getEVT(Ty1)))
14684     return false;
14685
14686   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14687
14688   // Assuming the caller doesn't have a zeroext or signext return parameter,
14689   // truncation all the way down to i1 is valid.
14690   return true;
14691 }
14692
14693 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14694   return isInt<32>(Imm);
14695 }
14696
14697 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14698   // Can also use sub to handle negated immediates.
14699   return isInt<32>(Imm);
14700 }
14701
14702 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14703   if (!VT1.isInteger() || !VT2.isInteger())
14704     return false;
14705   unsigned NumBits1 = VT1.getSizeInBits();
14706   unsigned NumBits2 = VT2.getSizeInBits();
14707   return NumBits1 > NumBits2;
14708 }
14709
14710 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14711   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14712   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14713 }
14714
14715 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14716   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14717   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14718 }
14719
14720 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14721   EVT VT1 = Val.getValueType();
14722   if (isZExtFree(VT1, VT2))
14723     return true;
14724
14725   if (Val.getOpcode() != ISD::LOAD)
14726     return false;
14727
14728   if (!VT1.isSimple() || !VT1.isInteger() ||
14729       !VT2.isSimple() || !VT2.isInteger())
14730     return false;
14731
14732   switch (VT1.getSimpleVT().SimpleTy) {
14733   default: break;
14734   case MVT::i8:
14735   case MVT::i16:
14736   case MVT::i32:
14737     // X86 has 8, 16, and 32-bit zero-extending loads.
14738     return true;
14739   }
14740
14741   return false;
14742 }
14743
14744 bool
14745 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14746   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14747     return false;
14748
14749   VT = VT.getScalarType();
14750
14751   if (!VT.isSimple())
14752     return false;
14753
14754   switch (VT.getSimpleVT().SimpleTy) {
14755   case MVT::f32:
14756   case MVT::f64:
14757     return true;
14758   default:
14759     break;
14760   }
14761
14762   return false;
14763 }
14764
14765 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14766   // i16 instructions are longer (0x66 prefix) and potentially slower.
14767   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14768 }
14769
14770 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14771 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14772 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14773 /// are assumed to be legal.
14774 bool
14775 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14776                                       EVT VT) const {
14777   if (!VT.isSimple())
14778     return false;
14779
14780   MVT SVT = VT.getSimpleVT();
14781
14782   // Very little shuffling can be done for 64-bit vectors right now.
14783   if (VT.getSizeInBits() == 64)
14784     return false;
14785
14786   // FIXME: pshufb, blends, shifts.
14787   return (SVT.getVectorNumElements() == 2 ||
14788           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14789           isMOVLMask(M, SVT) ||
14790           isSHUFPMask(M, SVT) ||
14791           isPSHUFDMask(M, SVT) ||
14792           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14793           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14794           isPALIGNRMask(M, SVT, Subtarget) ||
14795           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14796           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14797           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14798           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14799 }
14800
14801 bool
14802 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14803                                           EVT VT) const {
14804   if (!VT.isSimple())
14805     return false;
14806
14807   MVT SVT = VT.getSimpleVT();
14808   unsigned NumElts = SVT.getVectorNumElements();
14809   // FIXME: This collection of masks seems suspect.
14810   if (NumElts == 2)
14811     return true;
14812   if (NumElts == 4 && SVT.is128BitVector()) {
14813     return (isMOVLMask(Mask, SVT)  ||
14814             isCommutedMOVLMask(Mask, SVT, true) ||
14815             isSHUFPMask(Mask, SVT) ||
14816             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14817   }
14818   return false;
14819 }
14820
14821 //===----------------------------------------------------------------------===//
14822 //                           X86 Scheduler Hooks
14823 //===----------------------------------------------------------------------===//
14824
14825 /// Utility function to emit xbegin specifying the start of an RTM region.
14826 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14827                                      const TargetInstrInfo *TII) {
14828   DebugLoc DL = MI->getDebugLoc();
14829
14830   const BasicBlock *BB = MBB->getBasicBlock();
14831   MachineFunction::iterator I = MBB;
14832   ++I;
14833
14834   // For the v = xbegin(), we generate
14835   //
14836   // thisMBB:
14837   //  xbegin sinkMBB
14838   //
14839   // mainMBB:
14840   //  eax = -1
14841   //
14842   // sinkMBB:
14843   //  v = eax
14844
14845   MachineBasicBlock *thisMBB = MBB;
14846   MachineFunction *MF = MBB->getParent();
14847   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14848   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14849   MF->insert(I, mainMBB);
14850   MF->insert(I, sinkMBB);
14851
14852   // Transfer the remainder of BB and its successor edges to sinkMBB.
14853   sinkMBB->splice(sinkMBB->begin(), MBB,
14854                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14855   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14856
14857   // thisMBB:
14858   //  xbegin sinkMBB
14859   //  # fallthrough to mainMBB
14860   //  # abortion to sinkMBB
14861   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14862   thisMBB->addSuccessor(mainMBB);
14863   thisMBB->addSuccessor(sinkMBB);
14864
14865   // mainMBB:
14866   //  EAX = -1
14867   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14868   mainMBB->addSuccessor(sinkMBB);
14869
14870   // sinkMBB:
14871   // EAX is live into the sinkMBB
14872   sinkMBB->addLiveIn(X86::EAX);
14873   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14874           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14875     .addReg(X86::EAX);
14876
14877   MI->eraseFromParent();
14878   return sinkMBB;
14879 }
14880
14881 // Get CMPXCHG opcode for the specified data type.
14882 static unsigned getCmpXChgOpcode(EVT VT) {
14883   switch (VT.getSimpleVT().SimpleTy) {
14884   case MVT::i8:  return X86::LCMPXCHG8;
14885   case MVT::i16: return X86::LCMPXCHG16;
14886   case MVT::i32: return X86::LCMPXCHG32;
14887   case MVT::i64: return X86::LCMPXCHG64;
14888   default:
14889     break;
14890   }
14891   llvm_unreachable("Invalid operand size!");
14892 }
14893
14894 // Get LOAD opcode for the specified data type.
14895 static unsigned getLoadOpcode(EVT VT) {
14896   switch (VT.getSimpleVT().SimpleTy) {
14897   case MVT::i8:  return X86::MOV8rm;
14898   case MVT::i16: return X86::MOV16rm;
14899   case MVT::i32: return X86::MOV32rm;
14900   case MVT::i64: return X86::MOV64rm;
14901   default:
14902     break;
14903   }
14904   llvm_unreachable("Invalid operand size!");
14905 }
14906
14907 // Get opcode of the non-atomic one from the specified atomic instruction.
14908 static unsigned getNonAtomicOpcode(unsigned Opc) {
14909   switch (Opc) {
14910   case X86::ATOMAND8:  return X86::AND8rr;
14911   case X86::ATOMAND16: return X86::AND16rr;
14912   case X86::ATOMAND32: return X86::AND32rr;
14913   case X86::ATOMAND64: return X86::AND64rr;
14914   case X86::ATOMOR8:   return X86::OR8rr;
14915   case X86::ATOMOR16:  return X86::OR16rr;
14916   case X86::ATOMOR32:  return X86::OR32rr;
14917   case X86::ATOMOR64:  return X86::OR64rr;
14918   case X86::ATOMXOR8:  return X86::XOR8rr;
14919   case X86::ATOMXOR16: return X86::XOR16rr;
14920   case X86::ATOMXOR32: return X86::XOR32rr;
14921   case X86::ATOMXOR64: return X86::XOR64rr;
14922   }
14923   llvm_unreachable("Unhandled atomic-load-op opcode!");
14924 }
14925
14926 // Get opcode of the non-atomic one from the specified atomic instruction with
14927 // extra opcode.
14928 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14929                                                unsigned &ExtraOpc) {
14930   switch (Opc) {
14931   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14932   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14933   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14934   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14935   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14936   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14937   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14938   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14939   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14940   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14941   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14942   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14943   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14944   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14945   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14946   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14947   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14948   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14949   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14950   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14951   }
14952   llvm_unreachable("Unhandled atomic-load-op opcode!");
14953 }
14954
14955 // Get opcode of the non-atomic one from the specified atomic instruction for
14956 // 64-bit data type on 32-bit target.
14957 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14958   switch (Opc) {
14959   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14960   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14961   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14962   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14963   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14964   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14965   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14966   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14967   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14968   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14969   }
14970   llvm_unreachable("Unhandled atomic-load-op opcode!");
14971 }
14972
14973 // Get opcode of the non-atomic one from the specified atomic instruction for
14974 // 64-bit data type on 32-bit target with extra opcode.
14975 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14976                                                    unsigned &HiOpc,
14977                                                    unsigned &ExtraOpc) {
14978   switch (Opc) {
14979   case X86::ATOMNAND6432:
14980     ExtraOpc = X86::NOT32r;
14981     HiOpc = X86::AND32rr;
14982     return X86::AND32rr;
14983   }
14984   llvm_unreachable("Unhandled atomic-load-op opcode!");
14985 }
14986
14987 // Get pseudo CMOV opcode from the specified data type.
14988 static unsigned getPseudoCMOVOpc(EVT VT) {
14989   switch (VT.getSimpleVT().SimpleTy) {
14990   case MVT::i8:  return X86::CMOV_GR8;
14991   case MVT::i16: return X86::CMOV_GR16;
14992   case MVT::i32: return X86::CMOV_GR32;
14993   default:
14994     break;
14995   }
14996   llvm_unreachable("Unknown CMOV opcode!");
14997 }
14998
14999 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15000 // They will be translated into a spin-loop or compare-exchange loop from
15001 //
15002 //    ...
15003 //    dst = atomic-fetch-op MI.addr, MI.val
15004 //    ...
15005 //
15006 // to
15007 //
15008 //    ...
15009 //    t1 = LOAD MI.addr
15010 // loop:
15011 //    t4 = phi(t1, t3 / loop)
15012 //    t2 = OP MI.val, t4
15013 //    EAX = t4
15014 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15015 //    t3 = EAX
15016 //    JNE loop
15017 // sink:
15018 //    dst = t3
15019 //    ...
15020 MachineBasicBlock *
15021 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15022                                        MachineBasicBlock *MBB) const {
15023   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15024   DebugLoc DL = MI->getDebugLoc();
15025
15026   MachineFunction *MF = MBB->getParent();
15027   MachineRegisterInfo &MRI = MF->getRegInfo();
15028
15029   const BasicBlock *BB = MBB->getBasicBlock();
15030   MachineFunction::iterator I = MBB;
15031   ++I;
15032
15033   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15034          "Unexpected number of operands");
15035
15036   assert(MI->hasOneMemOperand() &&
15037          "Expected atomic-load-op to have one memoperand");
15038
15039   // Memory Reference
15040   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15041   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15042
15043   unsigned DstReg, SrcReg;
15044   unsigned MemOpndSlot;
15045
15046   unsigned CurOp = 0;
15047
15048   DstReg = MI->getOperand(CurOp++).getReg();
15049   MemOpndSlot = CurOp;
15050   CurOp += X86::AddrNumOperands;
15051   SrcReg = MI->getOperand(CurOp++).getReg();
15052
15053   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15054   MVT::SimpleValueType VT = *RC->vt_begin();
15055   unsigned t1 = MRI.createVirtualRegister(RC);
15056   unsigned t2 = MRI.createVirtualRegister(RC);
15057   unsigned t3 = MRI.createVirtualRegister(RC);
15058   unsigned t4 = MRI.createVirtualRegister(RC);
15059   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15060
15061   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15062   unsigned LOADOpc = getLoadOpcode(VT);
15063
15064   // For the atomic load-arith operator, we generate
15065   //
15066   //  thisMBB:
15067   //    t1 = LOAD [MI.addr]
15068   //  mainMBB:
15069   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15070   //    t1 = OP MI.val, EAX
15071   //    EAX = t4
15072   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15073   //    t3 = EAX
15074   //    JNE mainMBB
15075   //  sinkMBB:
15076   //    dst = t3
15077
15078   MachineBasicBlock *thisMBB = MBB;
15079   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15080   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15081   MF->insert(I, mainMBB);
15082   MF->insert(I, sinkMBB);
15083
15084   MachineInstrBuilder MIB;
15085
15086   // Transfer the remainder of BB and its successor edges to sinkMBB.
15087   sinkMBB->splice(sinkMBB->begin(), MBB,
15088                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15089   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15090
15091   // thisMBB:
15092   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15093   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15094     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15095     if (NewMO.isReg())
15096       NewMO.setIsKill(false);
15097     MIB.addOperand(NewMO);
15098   }
15099   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15100     unsigned flags = (*MMOI)->getFlags();
15101     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15102     MachineMemOperand *MMO =
15103       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15104                                (*MMOI)->getSize(),
15105                                (*MMOI)->getBaseAlignment(),
15106                                (*MMOI)->getTBAAInfo(),
15107                                (*MMOI)->getRanges());
15108     MIB.addMemOperand(MMO);
15109   }
15110
15111   thisMBB->addSuccessor(mainMBB);
15112
15113   // mainMBB:
15114   MachineBasicBlock *origMainMBB = mainMBB;
15115
15116   // Add a PHI.
15117   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15118                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15119
15120   unsigned Opc = MI->getOpcode();
15121   switch (Opc) {
15122   default:
15123     llvm_unreachable("Unhandled atomic-load-op opcode!");
15124   case X86::ATOMAND8:
15125   case X86::ATOMAND16:
15126   case X86::ATOMAND32:
15127   case X86::ATOMAND64:
15128   case X86::ATOMOR8:
15129   case X86::ATOMOR16:
15130   case X86::ATOMOR32:
15131   case X86::ATOMOR64:
15132   case X86::ATOMXOR8:
15133   case X86::ATOMXOR16:
15134   case X86::ATOMXOR32:
15135   case X86::ATOMXOR64: {
15136     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15137     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15138       .addReg(t4);
15139     break;
15140   }
15141   case X86::ATOMNAND8:
15142   case X86::ATOMNAND16:
15143   case X86::ATOMNAND32:
15144   case X86::ATOMNAND64: {
15145     unsigned Tmp = MRI.createVirtualRegister(RC);
15146     unsigned NOTOpc;
15147     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15148     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15149       .addReg(t4);
15150     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15151     break;
15152   }
15153   case X86::ATOMMAX8:
15154   case X86::ATOMMAX16:
15155   case X86::ATOMMAX32:
15156   case X86::ATOMMAX64:
15157   case X86::ATOMMIN8:
15158   case X86::ATOMMIN16:
15159   case X86::ATOMMIN32:
15160   case X86::ATOMMIN64:
15161   case X86::ATOMUMAX8:
15162   case X86::ATOMUMAX16:
15163   case X86::ATOMUMAX32:
15164   case X86::ATOMUMAX64:
15165   case X86::ATOMUMIN8:
15166   case X86::ATOMUMIN16:
15167   case X86::ATOMUMIN32:
15168   case X86::ATOMUMIN64: {
15169     unsigned CMPOpc;
15170     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15171
15172     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15173       .addReg(SrcReg)
15174       .addReg(t4);
15175
15176     if (Subtarget->hasCMov()) {
15177       if (VT != MVT::i8) {
15178         // Native support
15179         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15180           .addReg(SrcReg)
15181           .addReg(t4);
15182       } else {
15183         // Promote i8 to i32 to use CMOV32
15184         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15185         const TargetRegisterClass *RC32 =
15186           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15187         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15188         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15189         unsigned Tmp = MRI.createVirtualRegister(RC32);
15190
15191         unsigned Undef = MRI.createVirtualRegister(RC32);
15192         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15193
15194         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15195           .addReg(Undef)
15196           .addReg(SrcReg)
15197           .addImm(X86::sub_8bit);
15198         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15199           .addReg(Undef)
15200           .addReg(t4)
15201           .addImm(X86::sub_8bit);
15202
15203         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15204           .addReg(SrcReg32)
15205           .addReg(AccReg32);
15206
15207         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15208           .addReg(Tmp, 0, X86::sub_8bit);
15209       }
15210     } else {
15211       // Use pseudo select and lower them.
15212       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15213              "Invalid atomic-load-op transformation!");
15214       unsigned SelOpc = getPseudoCMOVOpc(VT);
15215       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15216       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15217       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15218               .addReg(SrcReg).addReg(t4)
15219               .addImm(CC);
15220       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15221       // Replace the original PHI node as mainMBB is changed after CMOV
15222       // lowering.
15223       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15224         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15225       Phi->eraseFromParent();
15226     }
15227     break;
15228   }
15229   }
15230
15231   // Copy PhyReg back from virtual register.
15232   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15233     .addReg(t4);
15234
15235   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15236   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15237     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15238     if (NewMO.isReg())
15239       NewMO.setIsKill(false);
15240     MIB.addOperand(NewMO);
15241   }
15242   MIB.addReg(t2);
15243   MIB.setMemRefs(MMOBegin, MMOEnd);
15244
15245   // Copy PhyReg back to virtual register.
15246   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15247     .addReg(PhyReg);
15248
15249   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15250
15251   mainMBB->addSuccessor(origMainMBB);
15252   mainMBB->addSuccessor(sinkMBB);
15253
15254   // sinkMBB:
15255   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15256           TII->get(TargetOpcode::COPY), DstReg)
15257     .addReg(t3);
15258
15259   MI->eraseFromParent();
15260   return sinkMBB;
15261 }
15262
15263 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15264 // instructions. They will be translated into a spin-loop or compare-exchange
15265 // loop from
15266 //
15267 //    ...
15268 //    dst = atomic-fetch-op MI.addr, MI.val
15269 //    ...
15270 //
15271 // to
15272 //
15273 //    ...
15274 //    t1L = LOAD [MI.addr + 0]
15275 //    t1H = LOAD [MI.addr + 4]
15276 // loop:
15277 //    t4L = phi(t1L, t3L / loop)
15278 //    t4H = phi(t1H, t3H / loop)
15279 //    t2L = OP MI.val.lo, t4L
15280 //    t2H = OP MI.val.hi, t4H
15281 //    EAX = t4L
15282 //    EDX = t4H
15283 //    EBX = t2L
15284 //    ECX = t2H
15285 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15286 //    t3L = EAX
15287 //    t3H = EDX
15288 //    JNE loop
15289 // sink:
15290 //    dstL = t3L
15291 //    dstH = t3H
15292 //    ...
15293 MachineBasicBlock *
15294 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15295                                            MachineBasicBlock *MBB) const {
15296   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15297   DebugLoc DL = MI->getDebugLoc();
15298
15299   MachineFunction *MF = MBB->getParent();
15300   MachineRegisterInfo &MRI = MF->getRegInfo();
15301
15302   const BasicBlock *BB = MBB->getBasicBlock();
15303   MachineFunction::iterator I = MBB;
15304   ++I;
15305
15306   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15307          "Unexpected number of operands");
15308
15309   assert(MI->hasOneMemOperand() &&
15310          "Expected atomic-load-op32 to have one memoperand");
15311
15312   // Memory Reference
15313   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15314   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15315
15316   unsigned DstLoReg, DstHiReg;
15317   unsigned SrcLoReg, SrcHiReg;
15318   unsigned MemOpndSlot;
15319
15320   unsigned CurOp = 0;
15321
15322   DstLoReg = MI->getOperand(CurOp++).getReg();
15323   DstHiReg = MI->getOperand(CurOp++).getReg();
15324   MemOpndSlot = CurOp;
15325   CurOp += X86::AddrNumOperands;
15326   SrcLoReg = MI->getOperand(CurOp++).getReg();
15327   SrcHiReg = MI->getOperand(CurOp++).getReg();
15328
15329   const TargetRegisterClass *RC = &X86::GR32RegClass;
15330   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15331
15332   unsigned t1L = MRI.createVirtualRegister(RC);
15333   unsigned t1H = MRI.createVirtualRegister(RC);
15334   unsigned t2L = MRI.createVirtualRegister(RC);
15335   unsigned t2H = MRI.createVirtualRegister(RC);
15336   unsigned t3L = MRI.createVirtualRegister(RC);
15337   unsigned t3H = MRI.createVirtualRegister(RC);
15338   unsigned t4L = MRI.createVirtualRegister(RC);
15339   unsigned t4H = MRI.createVirtualRegister(RC);
15340
15341   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15342   unsigned LOADOpc = X86::MOV32rm;
15343
15344   // For the atomic load-arith operator, we generate
15345   //
15346   //  thisMBB:
15347   //    t1L = LOAD [MI.addr + 0]
15348   //    t1H = LOAD [MI.addr + 4]
15349   //  mainMBB:
15350   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15351   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15352   //    t2L = OP MI.val.lo, t4L
15353   //    t2H = OP MI.val.hi, t4H
15354   //    EBX = t2L
15355   //    ECX = t2H
15356   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15357   //    t3L = EAX
15358   //    t3H = EDX
15359   //    JNE loop
15360   //  sinkMBB:
15361   //    dstL = t3L
15362   //    dstH = t3H
15363
15364   MachineBasicBlock *thisMBB = MBB;
15365   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15366   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15367   MF->insert(I, mainMBB);
15368   MF->insert(I, sinkMBB);
15369
15370   MachineInstrBuilder MIB;
15371
15372   // Transfer the remainder of BB and its successor edges to sinkMBB.
15373   sinkMBB->splice(sinkMBB->begin(), MBB,
15374                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15375   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15376
15377   // thisMBB:
15378   // Lo
15379   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15380   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15381     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15382     if (NewMO.isReg())
15383       NewMO.setIsKill(false);
15384     MIB.addOperand(NewMO);
15385   }
15386   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15387     unsigned flags = (*MMOI)->getFlags();
15388     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15389     MachineMemOperand *MMO =
15390       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15391                                (*MMOI)->getSize(),
15392                                (*MMOI)->getBaseAlignment(),
15393                                (*MMOI)->getTBAAInfo(),
15394                                (*MMOI)->getRanges());
15395     MIB.addMemOperand(MMO);
15396   };
15397   MachineInstr *LowMI = MIB;
15398
15399   // Hi
15400   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15401   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15402     if (i == X86::AddrDisp) {
15403       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15404     } else {
15405       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15406       if (NewMO.isReg())
15407         NewMO.setIsKill(false);
15408       MIB.addOperand(NewMO);
15409     }
15410   }
15411   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15412
15413   thisMBB->addSuccessor(mainMBB);
15414
15415   // mainMBB:
15416   MachineBasicBlock *origMainMBB = mainMBB;
15417
15418   // Add PHIs.
15419   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15420                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15421   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15422                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15423
15424   unsigned Opc = MI->getOpcode();
15425   switch (Opc) {
15426   default:
15427     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15428   case X86::ATOMAND6432:
15429   case X86::ATOMOR6432:
15430   case X86::ATOMXOR6432:
15431   case X86::ATOMADD6432:
15432   case X86::ATOMSUB6432: {
15433     unsigned HiOpc;
15434     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15435     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15436       .addReg(SrcLoReg);
15437     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15438       .addReg(SrcHiReg);
15439     break;
15440   }
15441   case X86::ATOMNAND6432: {
15442     unsigned HiOpc, NOTOpc;
15443     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15444     unsigned TmpL = MRI.createVirtualRegister(RC);
15445     unsigned TmpH = MRI.createVirtualRegister(RC);
15446     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15447       .addReg(t4L);
15448     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15449       .addReg(t4H);
15450     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15451     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15452     break;
15453   }
15454   case X86::ATOMMAX6432:
15455   case X86::ATOMMIN6432:
15456   case X86::ATOMUMAX6432:
15457   case X86::ATOMUMIN6432: {
15458     unsigned HiOpc;
15459     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15460     unsigned cL = MRI.createVirtualRegister(RC8);
15461     unsigned cH = MRI.createVirtualRegister(RC8);
15462     unsigned cL32 = MRI.createVirtualRegister(RC);
15463     unsigned cH32 = MRI.createVirtualRegister(RC);
15464     unsigned cc = MRI.createVirtualRegister(RC);
15465     // cl := cmp src_lo, lo
15466     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15467       .addReg(SrcLoReg).addReg(t4L);
15468     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15469     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15470     // ch := cmp src_hi, hi
15471     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15472       .addReg(SrcHiReg).addReg(t4H);
15473     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15474     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15475     // cc := if (src_hi == hi) ? cl : ch;
15476     if (Subtarget->hasCMov()) {
15477       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15478         .addReg(cH32).addReg(cL32);
15479     } else {
15480       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15481               .addReg(cH32).addReg(cL32)
15482               .addImm(X86::COND_E);
15483       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15484     }
15485     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15486     if (Subtarget->hasCMov()) {
15487       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15488         .addReg(SrcLoReg).addReg(t4L);
15489       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15490         .addReg(SrcHiReg).addReg(t4H);
15491     } else {
15492       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15493               .addReg(SrcLoReg).addReg(t4L)
15494               .addImm(X86::COND_NE);
15495       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15496       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15497       // 2nd CMOV lowering.
15498       mainMBB->addLiveIn(X86::EFLAGS);
15499       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15500               .addReg(SrcHiReg).addReg(t4H)
15501               .addImm(X86::COND_NE);
15502       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15503       // Replace the original PHI node as mainMBB is changed after CMOV
15504       // lowering.
15505       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15506         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15507       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15508         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15509       PhiL->eraseFromParent();
15510       PhiH->eraseFromParent();
15511     }
15512     break;
15513   }
15514   case X86::ATOMSWAP6432: {
15515     unsigned HiOpc;
15516     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15517     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15518     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15519     break;
15520   }
15521   }
15522
15523   // Copy EDX:EAX back from HiReg:LoReg
15524   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15525   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15526   // Copy ECX:EBX from t1H:t1L
15527   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15528   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15529
15530   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15531   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15532     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15533     if (NewMO.isReg())
15534       NewMO.setIsKill(false);
15535     MIB.addOperand(NewMO);
15536   }
15537   MIB.setMemRefs(MMOBegin, MMOEnd);
15538
15539   // Copy EDX:EAX back to t3H:t3L
15540   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15541   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15542
15543   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15544
15545   mainMBB->addSuccessor(origMainMBB);
15546   mainMBB->addSuccessor(sinkMBB);
15547
15548   // sinkMBB:
15549   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15550           TII->get(TargetOpcode::COPY), DstLoReg)
15551     .addReg(t3L);
15552   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15553           TII->get(TargetOpcode::COPY), DstHiReg)
15554     .addReg(t3H);
15555
15556   MI->eraseFromParent();
15557   return sinkMBB;
15558 }
15559
15560 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15561 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15562 // in the .td file.
15563 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15564                                        const TargetInstrInfo *TII) {
15565   unsigned Opc;
15566   switch (MI->getOpcode()) {
15567   default: llvm_unreachable("illegal opcode!");
15568   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15569   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15570   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15571   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15572   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15573   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15574   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15575   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15576   }
15577
15578   DebugLoc dl = MI->getDebugLoc();
15579   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15580
15581   unsigned NumArgs = MI->getNumOperands();
15582   for (unsigned i = 1; i < NumArgs; ++i) {
15583     MachineOperand &Op = MI->getOperand(i);
15584     if (!(Op.isReg() && Op.isImplicit()))
15585       MIB.addOperand(Op);
15586   }
15587   if (MI->hasOneMemOperand())
15588     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15589
15590   BuildMI(*BB, MI, dl,
15591     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15592     .addReg(X86::XMM0);
15593
15594   MI->eraseFromParent();
15595   return BB;
15596 }
15597
15598 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15599 // defs in an instruction pattern
15600 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15601                                        const TargetInstrInfo *TII) {
15602   unsigned Opc;
15603   switch (MI->getOpcode()) {
15604   default: llvm_unreachable("illegal opcode!");
15605   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15606   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15607   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15608   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15609   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15610   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15611   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15612   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15613   }
15614
15615   DebugLoc dl = MI->getDebugLoc();
15616   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15617
15618   unsigned NumArgs = MI->getNumOperands(); // remove the results
15619   for (unsigned i = 1; i < NumArgs; ++i) {
15620     MachineOperand &Op = MI->getOperand(i);
15621     if (!(Op.isReg() && Op.isImplicit()))
15622       MIB.addOperand(Op);
15623   }
15624   if (MI->hasOneMemOperand())
15625     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15626
15627   BuildMI(*BB, MI, dl,
15628     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15629     .addReg(X86::ECX);
15630
15631   MI->eraseFromParent();
15632   return BB;
15633 }
15634
15635 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15636                                        const TargetInstrInfo *TII,
15637                                        const X86Subtarget* Subtarget) {
15638   DebugLoc dl = MI->getDebugLoc();
15639
15640   // Address into RAX/EAX, other two args into ECX, EDX.
15641   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15642   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15643   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15644   for (int i = 0; i < X86::AddrNumOperands; ++i)
15645     MIB.addOperand(MI->getOperand(i));
15646
15647   unsigned ValOps = X86::AddrNumOperands;
15648   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15649     .addReg(MI->getOperand(ValOps).getReg());
15650   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15651     .addReg(MI->getOperand(ValOps+1).getReg());
15652
15653   // The instruction doesn't actually take any operands though.
15654   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15655
15656   MI->eraseFromParent(); // The pseudo is gone now.
15657   return BB;
15658 }
15659
15660 MachineBasicBlock *
15661 X86TargetLowering::EmitVAARG64WithCustomInserter(
15662                    MachineInstr *MI,
15663                    MachineBasicBlock *MBB) const {
15664   // Emit va_arg instruction on X86-64.
15665
15666   // Operands to this pseudo-instruction:
15667   // 0  ) Output        : destination address (reg)
15668   // 1-5) Input         : va_list address (addr, i64mem)
15669   // 6  ) ArgSize       : Size (in bytes) of vararg type
15670   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15671   // 8  ) Align         : Alignment of type
15672   // 9  ) EFLAGS (implicit-def)
15673
15674   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15675   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15676
15677   unsigned DestReg = MI->getOperand(0).getReg();
15678   MachineOperand &Base = MI->getOperand(1);
15679   MachineOperand &Scale = MI->getOperand(2);
15680   MachineOperand &Index = MI->getOperand(3);
15681   MachineOperand &Disp = MI->getOperand(4);
15682   MachineOperand &Segment = MI->getOperand(5);
15683   unsigned ArgSize = MI->getOperand(6).getImm();
15684   unsigned ArgMode = MI->getOperand(7).getImm();
15685   unsigned Align = MI->getOperand(8).getImm();
15686
15687   // Memory Reference
15688   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15689   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15690   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15691
15692   // Machine Information
15693   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15694   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15695   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15696   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15697   DebugLoc DL = MI->getDebugLoc();
15698
15699   // struct va_list {
15700   //   i32   gp_offset
15701   //   i32   fp_offset
15702   //   i64   overflow_area (address)
15703   //   i64   reg_save_area (address)
15704   // }
15705   // sizeof(va_list) = 24
15706   // alignment(va_list) = 8
15707
15708   unsigned TotalNumIntRegs = 6;
15709   unsigned TotalNumXMMRegs = 8;
15710   bool UseGPOffset = (ArgMode == 1);
15711   bool UseFPOffset = (ArgMode == 2);
15712   unsigned MaxOffset = TotalNumIntRegs * 8 +
15713                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15714
15715   /* Align ArgSize to a multiple of 8 */
15716   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15717   bool NeedsAlign = (Align > 8);
15718
15719   MachineBasicBlock *thisMBB = MBB;
15720   MachineBasicBlock *overflowMBB;
15721   MachineBasicBlock *offsetMBB;
15722   MachineBasicBlock *endMBB;
15723
15724   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15725   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15726   unsigned OffsetReg = 0;
15727
15728   if (!UseGPOffset && !UseFPOffset) {
15729     // If we only pull from the overflow region, we don't create a branch.
15730     // We don't need to alter control flow.
15731     OffsetDestReg = 0; // unused
15732     OverflowDestReg = DestReg;
15733
15734     offsetMBB = nullptr;
15735     overflowMBB = thisMBB;
15736     endMBB = thisMBB;
15737   } else {
15738     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15739     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15740     // If not, pull from overflow_area. (branch to overflowMBB)
15741     //
15742     //       thisMBB
15743     //         |     .
15744     //         |        .
15745     //     offsetMBB   overflowMBB
15746     //         |        .
15747     //         |     .
15748     //        endMBB
15749
15750     // Registers for the PHI in endMBB
15751     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15752     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15753
15754     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15755     MachineFunction *MF = MBB->getParent();
15756     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15757     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15758     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15759
15760     MachineFunction::iterator MBBIter = MBB;
15761     ++MBBIter;
15762
15763     // Insert the new basic blocks
15764     MF->insert(MBBIter, offsetMBB);
15765     MF->insert(MBBIter, overflowMBB);
15766     MF->insert(MBBIter, endMBB);
15767
15768     // Transfer the remainder of MBB and its successor edges to endMBB.
15769     endMBB->splice(endMBB->begin(), thisMBB,
15770                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15771     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15772
15773     // Make offsetMBB and overflowMBB successors of thisMBB
15774     thisMBB->addSuccessor(offsetMBB);
15775     thisMBB->addSuccessor(overflowMBB);
15776
15777     // endMBB is a successor of both offsetMBB and overflowMBB
15778     offsetMBB->addSuccessor(endMBB);
15779     overflowMBB->addSuccessor(endMBB);
15780
15781     // Load the offset value into a register
15782     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15783     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15784       .addOperand(Base)
15785       .addOperand(Scale)
15786       .addOperand(Index)
15787       .addDisp(Disp, UseFPOffset ? 4 : 0)
15788       .addOperand(Segment)
15789       .setMemRefs(MMOBegin, MMOEnd);
15790
15791     // Check if there is enough room left to pull this argument.
15792     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15793       .addReg(OffsetReg)
15794       .addImm(MaxOffset + 8 - ArgSizeA8);
15795
15796     // Branch to "overflowMBB" if offset >= max
15797     // Fall through to "offsetMBB" otherwise
15798     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15799       .addMBB(overflowMBB);
15800   }
15801
15802   // In offsetMBB, emit code to use the reg_save_area.
15803   if (offsetMBB) {
15804     assert(OffsetReg != 0);
15805
15806     // Read the reg_save_area address.
15807     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15808     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15809       .addOperand(Base)
15810       .addOperand(Scale)
15811       .addOperand(Index)
15812       .addDisp(Disp, 16)
15813       .addOperand(Segment)
15814       .setMemRefs(MMOBegin, MMOEnd);
15815
15816     // Zero-extend the offset
15817     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15818       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15819         .addImm(0)
15820         .addReg(OffsetReg)
15821         .addImm(X86::sub_32bit);
15822
15823     // Add the offset to the reg_save_area to get the final address.
15824     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15825       .addReg(OffsetReg64)
15826       .addReg(RegSaveReg);
15827
15828     // Compute the offset for the next argument
15829     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15830     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15831       .addReg(OffsetReg)
15832       .addImm(UseFPOffset ? 16 : 8);
15833
15834     // Store it back into the va_list.
15835     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15836       .addOperand(Base)
15837       .addOperand(Scale)
15838       .addOperand(Index)
15839       .addDisp(Disp, UseFPOffset ? 4 : 0)
15840       .addOperand(Segment)
15841       .addReg(NextOffsetReg)
15842       .setMemRefs(MMOBegin, MMOEnd);
15843
15844     // Jump to endMBB
15845     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15846       .addMBB(endMBB);
15847   }
15848
15849   //
15850   // Emit code to use overflow area
15851   //
15852
15853   // Load the overflow_area address into a register.
15854   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15855   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15856     .addOperand(Base)
15857     .addOperand(Scale)
15858     .addOperand(Index)
15859     .addDisp(Disp, 8)
15860     .addOperand(Segment)
15861     .setMemRefs(MMOBegin, MMOEnd);
15862
15863   // If we need to align it, do so. Otherwise, just copy the address
15864   // to OverflowDestReg.
15865   if (NeedsAlign) {
15866     // Align the overflow address
15867     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15868     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15869
15870     // aligned_addr = (addr + (align-1)) & ~(align-1)
15871     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15872       .addReg(OverflowAddrReg)
15873       .addImm(Align-1);
15874
15875     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15876       .addReg(TmpReg)
15877       .addImm(~(uint64_t)(Align-1));
15878   } else {
15879     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15880       .addReg(OverflowAddrReg);
15881   }
15882
15883   // Compute the next overflow address after this argument.
15884   // (the overflow address should be kept 8-byte aligned)
15885   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15886   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15887     .addReg(OverflowDestReg)
15888     .addImm(ArgSizeA8);
15889
15890   // Store the new overflow address.
15891   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15892     .addOperand(Base)
15893     .addOperand(Scale)
15894     .addOperand(Index)
15895     .addDisp(Disp, 8)
15896     .addOperand(Segment)
15897     .addReg(NextAddrReg)
15898     .setMemRefs(MMOBegin, MMOEnd);
15899
15900   // If we branched, emit the PHI to the front of endMBB.
15901   if (offsetMBB) {
15902     BuildMI(*endMBB, endMBB->begin(), DL,
15903             TII->get(X86::PHI), DestReg)
15904       .addReg(OffsetDestReg).addMBB(offsetMBB)
15905       .addReg(OverflowDestReg).addMBB(overflowMBB);
15906   }
15907
15908   // Erase the pseudo instruction
15909   MI->eraseFromParent();
15910
15911   return endMBB;
15912 }
15913
15914 MachineBasicBlock *
15915 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15916                                                  MachineInstr *MI,
15917                                                  MachineBasicBlock *MBB) const {
15918   // Emit code to save XMM registers to the stack. The ABI says that the
15919   // number of registers to save is given in %al, so it's theoretically
15920   // possible to do an indirect jump trick to avoid saving all of them,
15921   // however this code takes a simpler approach and just executes all
15922   // of the stores if %al is non-zero. It's less code, and it's probably
15923   // easier on the hardware branch predictor, and stores aren't all that
15924   // expensive anyway.
15925
15926   // Create the new basic blocks. One block contains all the XMM stores,
15927   // and one block is the final destination regardless of whether any
15928   // stores were performed.
15929   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15930   MachineFunction *F = MBB->getParent();
15931   MachineFunction::iterator MBBIter = MBB;
15932   ++MBBIter;
15933   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15934   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15935   F->insert(MBBIter, XMMSaveMBB);
15936   F->insert(MBBIter, EndMBB);
15937
15938   // Transfer the remainder of MBB and its successor edges to EndMBB.
15939   EndMBB->splice(EndMBB->begin(), MBB,
15940                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15941   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15942
15943   // The original block will now fall through to the XMM save block.
15944   MBB->addSuccessor(XMMSaveMBB);
15945   // The XMMSaveMBB will fall through to the end block.
15946   XMMSaveMBB->addSuccessor(EndMBB);
15947
15948   // Now add the instructions.
15949   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15950   DebugLoc DL = MI->getDebugLoc();
15951
15952   unsigned CountReg = MI->getOperand(0).getReg();
15953   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15954   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15955
15956   if (!Subtarget->isTargetWin64()) {
15957     // If %al is 0, branch around the XMM save block.
15958     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15959     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15960     MBB->addSuccessor(EndMBB);
15961   }
15962
15963   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15964   // that was just emitted, but clearly shouldn't be "saved".
15965   assert((MI->getNumOperands() <= 3 ||
15966           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15967           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15968          && "Expected last argument to be EFLAGS");
15969   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15970   // In the XMM save block, save all the XMM argument registers.
15971   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15972     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15973     MachineMemOperand *MMO =
15974       F->getMachineMemOperand(
15975           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15976         MachineMemOperand::MOStore,
15977         /*Size=*/16, /*Align=*/16);
15978     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15979       .addFrameIndex(RegSaveFrameIndex)
15980       .addImm(/*Scale=*/1)
15981       .addReg(/*IndexReg=*/0)
15982       .addImm(/*Disp=*/Offset)
15983       .addReg(/*Segment=*/0)
15984       .addReg(MI->getOperand(i).getReg())
15985       .addMemOperand(MMO);
15986   }
15987
15988   MI->eraseFromParent();   // The pseudo instruction is gone now.
15989
15990   return EndMBB;
15991 }
15992
15993 // The EFLAGS operand of SelectItr might be missing a kill marker
15994 // because there were multiple uses of EFLAGS, and ISel didn't know
15995 // which to mark. Figure out whether SelectItr should have had a
15996 // kill marker, and set it if it should. Returns the correct kill
15997 // marker value.
15998 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15999                                      MachineBasicBlock* BB,
16000                                      const TargetRegisterInfo* TRI) {
16001   // Scan forward through BB for a use/def of EFLAGS.
16002   MachineBasicBlock::iterator miI(std::next(SelectItr));
16003   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16004     const MachineInstr& mi = *miI;
16005     if (mi.readsRegister(X86::EFLAGS))
16006       return false;
16007     if (mi.definesRegister(X86::EFLAGS))
16008       break; // Should have kill-flag - update below.
16009   }
16010
16011   // If we hit the end of the block, check whether EFLAGS is live into a
16012   // successor.
16013   if (miI == BB->end()) {
16014     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16015                                           sEnd = BB->succ_end();
16016          sItr != sEnd; ++sItr) {
16017       MachineBasicBlock* succ = *sItr;
16018       if (succ->isLiveIn(X86::EFLAGS))
16019         return false;
16020     }
16021   }
16022
16023   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16024   // out. SelectMI should have a kill flag on EFLAGS.
16025   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16026   return true;
16027 }
16028
16029 MachineBasicBlock *
16030 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16031                                      MachineBasicBlock *BB) const {
16032   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16033   DebugLoc DL = MI->getDebugLoc();
16034
16035   // To "insert" a SELECT_CC instruction, we actually have to insert the
16036   // diamond control-flow pattern.  The incoming instruction knows the
16037   // destination vreg to set, the condition code register to branch on, the
16038   // true/false values to select between, and a branch opcode to use.
16039   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16040   MachineFunction::iterator It = BB;
16041   ++It;
16042
16043   //  thisMBB:
16044   //  ...
16045   //   TrueVal = ...
16046   //   cmpTY ccX, r1, r2
16047   //   bCC copy1MBB
16048   //   fallthrough --> copy0MBB
16049   MachineBasicBlock *thisMBB = BB;
16050   MachineFunction *F = BB->getParent();
16051   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16052   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16053   F->insert(It, copy0MBB);
16054   F->insert(It, sinkMBB);
16055
16056   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16057   // live into the sink and copy blocks.
16058   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16059   if (!MI->killsRegister(X86::EFLAGS) &&
16060       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16061     copy0MBB->addLiveIn(X86::EFLAGS);
16062     sinkMBB->addLiveIn(X86::EFLAGS);
16063   }
16064
16065   // Transfer the remainder of BB and its successor edges to sinkMBB.
16066   sinkMBB->splice(sinkMBB->begin(), BB,
16067                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16068   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16069
16070   // Add the true and fallthrough blocks as its successors.
16071   BB->addSuccessor(copy0MBB);
16072   BB->addSuccessor(sinkMBB);
16073
16074   // Create the conditional branch instruction.
16075   unsigned Opc =
16076     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16077   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16078
16079   //  copy0MBB:
16080   //   %FalseValue = ...
16081   //   # fallthrough to sinkMBB
16082   copy0MBB->addSuccessor(sinkMBB);
16083
16084   //  sinkMBB:
16085   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16086   //  ...
16087   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16088           TII->get(X86::PHI), MI->getOperand(0).getReg())
16089     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16090     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16091
16092   MI->eraseFromParent();   // The pseudo instruction is gone now.
16093   return sinkMBB;
16094 }
16095
16096 MachineBasicBlock *
16097 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16098                                         bool Is64Bit) const {
16099   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16100   DebugLoc DL = MI->getDebugLoc();
16101   MachineFunction *MF = BB->getParent();
16102   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16103
16104   assert(MF->shouldSplitStack());
16105
16106   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16107   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16108
16109   // BB:
16110   //  ... [Till the alloca]
16111   // If stacklet is not large enough, jump to mallocMBB
16112   //
16113   // bumpMBB:
16114   //  Allocate by subtracting from RSP
16115   //  Jump to continueMBB
16116   //
16117   // mallocMBB:
16118   //  Allocate by call to runtime
16119   //
16120   // continueMBB:
16121   //  ...
16122   //  [rest of original BB]
16123   //
16124
16125   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16126   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16127   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16128
16129   MachineRegisterInfo &MRI = MF->getRegInfo();
16130   const TargetRegisterClass *AddrRegClass =
16131     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16132
16133   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16134     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16135     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16136     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16137     sizeVReg = MI->getOperand(1).getReg(),
16138     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16139
16140   MachineFunction::iterator MBBIter = BB;
16141   ++MBBIter;
16142
16143   MF->insert(MBBIter, bumpMBB);
16144   MF->insert(MBBIter, mallocMBB);
16145   MF->insert(MBBIter, continueMBB);
16146
16147   continueMBB->splice(continueMBB->begin(), BB,
16148                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16149   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16150
16151   // Add code to the main basic block to check if the stack limit has been hit,
16152   // and if so, jump to mallocMBB otherwise to bumpMBB.
16153   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16154   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16155     .addReg(tmpSPVReg).addReg(sizeVReg);
16156   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16157     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16158     .addReg(SPLimitVReg);
16159   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16160
16161   // bumpMBB simply decreases the stack pointer, since we know the current
16162   // stacklet has enough space.
16163   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16164     .addReg(SPLimitVReg);
16165   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16166     .addReg(SPLimitVReg);
16167   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16168
16169   // Calls into a routine in libgcc to allocate more space from the heap.
16170   const uint32_t *RegMask =
16171     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16172   if (Is64Bit) {
16173     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16174       .addReg(sizeVReg);
16175     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16176       .addExternalSymbol("__morestack_allocate_stack_space")
16177       .addRegMask(RegMask)
16178       .addReg(X86::RDI, RegState::Implicit)
16179       .addReg(X86::RAX, RegState::ImplicitDefine);
16180   } else {
16181     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16182       .addImm(12);
16183     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16184     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16185       .addExternalSymbol("__morestack_allocate_stack_space")
16186       .addRegMask(RegMask)
16187       .addReg(X86::EAX, RegState::ImplicitDefine);
16188   }
16189
16190   if (!Is64Bit)
16191     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16192       .addImm(16);
16193
16194   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16195     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16196   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16197
16198   // Set up the CFG correctly.
16199   BB->addSuccessor(bumpMBB);
16200   BB->addSuccessor(mallocMBB);
16201   mallocMBB->addSuccessor(continueMBB);
16202   bumpMBB->addSuccessor(continueMBB);
16203
16204   // Take care of the PHI nodes.
16205   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16206           MI->getOperand(0).getReg())
16207     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16208     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16209
16210   // Delete the original pseudo instruction.
16211   MI->eraseFromParent();
16212
16213   // And we're done.
16214   return continueMBB;
16215 }
16216
16217 MachineBasicBlock *
16218 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16219                                           MachineBasicBlock *BB) const {
16220   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16221   DebugLoc DL = MI->getDebugLoc();
16222
16223   assert(!Subtarget->isTargetMacho());
16224
16225   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16226   // non-trivial part is impdef of ESP.
16227
16228   if (Subtarget->isTargetWin64()) {
16229     if (Subtarget->isTargetCygMing()) {
16230       // ___chkstk(Mingw64):
16231       // Clobbers R10, R11, RAX and EFLAGS.
16232       // Updates RSP.
16233       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16234         .addExternalSymbol("___chkstk")
16235         .addReg(X86::RAX, RegState::Implicit)
16236         .addReg(X86::RSP, RegState::Implicit)
16237         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16238         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16239         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16240     } else {
16241       // __chkstk(MSVCRT): does not update stack pointer.
16242       // Clobbers R10, R11 and EFLAGS.
16243       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16244         .addExternalSymbol("__chkstk")
16245         .addReg(X86::RAX, RegState::Implicit)
16246         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16247       // RAX has the offset to be subtracted from RSP.
16248       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16249         .addReg(X86::RSP)
16250         .addReg(X86::RAX);
16251     }
16252   } else {
16253     const char *StackProbeSymbol =
16254       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16255
16256     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16257       .addExternalSymbol(StackProbeSymbol)
16258       .addReg(X86::EAX, RegState::Implicit)
16259       .addReg(X86::ESP, RegState::Implicit)
16260       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16261       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16262       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16263   }
16264
16265   MI->eraseFromParent();   // The pseudo instruction is gone now.
16266   return BB;
16267 }
16268
16269 MachineBasicBlock *
16270 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16271                                       MachineBasicBlock *BB) const {
16272   // This is pretty easy.  We're taking the value that we received from
16273   // our load from the relocation, sticking it in either RDI (x86-64)
16274   // or EAX and doing an indirect call.  The return value will then
16275   // be in the normal return register.
16276   const X86InstrInfo *TII
16277     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16278   DebugLoc DL = MI->getDebugLoc();
16279   MachineFunction *F = BB->getParent();
16280
16281   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16282   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16283
16284   // Get a register mask for the lowered call.
16285   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16286   // proper register mask.
16287   const uint32_t *RegMask =
16288     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16289   if (Subtarget->is64Bit()) {
16290     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16291                                       TII->get(X86::MOV64rm), X86::RDI)
16292     .addReg(X86::RIP)
16293     .addImm(0).addReg(0)
16294     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16295                       MI->getOperand(3).getTargetFlags())
16296     .addReg(0);
16297     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16298     addDirectMem(MIB, X86::RDI);
16299     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16300   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16301     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16302                                       TII->get(X86::MOV32rm), X86::EAX)
16303     .addReg(0)
16304     .addImm(0).addReg(0)
16305     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16306                       MI->getOperand(3).getTargetFlags())
16307     .addReg(0);
16308     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16309     addDirectMem(MIB, X86::EAX);
16310     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16311   } else {
16312     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16313                                       TII->get(X86::MOV32rm), X86::EAX)
16314     .addReg(TII->getGlobalBaseReg(F))
16315     .addImm(0).addReg(0)
16316     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16317                       MI->getOperand(3).getTargetFlags())
16318     .addReg(0);
16319     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16320     addDirectMem(MIB, X86::EAX);
16321     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16322   }
16323
16324   MI->eraseFromParent(); // The pseudo instruction is gone now.
16325   return BB;
16326 }
16327
16328 MachineBasicBlock *
16329 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16330                                     MachineBasicBlock *MBB) const {
16331   DebugLoc DL = MI->getDebugLoc();
16332   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16333
16334   MachineFunction *MF = MBB->getParent();
16335   MachineRegisterInfo &MRI = MF->getRegInfo();
16336
16337   const BasicBlock *BB = MBB->getBasicBlock();
16338   MachineFunction::iterator I = MBB;
16339   ++I;
16340
16341   // Memory Reference
16342   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16343   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16344
16345   unsigned DstReg;
16346   unsigned MemOpndSlot = 0;
16347
16348   unsigned CurOp = 0;
16349
16350   DstReg = MI->getOperand(CurOp++).getReg();
16351   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16352   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16353   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16354   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16355
16356   MemOpndSlot = CurOp;
16357
16358   MVT PVT = getPointerTy();
16359   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16360          "Invalid Pointer Size!");
16361
16362   // For v = setjmp(buf), we generate
16363   //
16364   // thisMBB:
16365   //  buf[LabelOffset] = restoreMBB
16366   //  SjLjSetup restoreMBB
16367   //
16368   // mainMBB:
16369   //  v_main = 0
16370   //
16371   // sinkMBB:
16372   //  v = phi(main, restore)
16373   //
16374   // restoreMBB:
16375   //  v_restore = 1
16376
16377   MachineBasicBlock *thisMBB = MBB;
16378   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16379   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16380   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16381   MF->insert(I, mainMBB);
16382   MF->insert(I, sinkMBB);
16383   MF->push_back(restoreMBB);
16384
16385   MachineInstrBuilder MIB;
16386
16387   // Transfer the remainder of BB and its successor edges to sinkMBB.
16388   sinkMBB->splice(sinkMBB->begin(), MBB,
16389                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16390   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16391
16392   // thisMBB:
16393   unsigned PtrStoreOpc = 0;
16394   unsigned LabelReg = 0;
16395   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16396   Reloc::Model RM = getTargetMachine().getRelocationModel();
16397   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16398                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16399
16400   // Prepare IP either in reg or imm.
16401   if (!UseImmLabel) {
16402     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16403     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16404     LabelReg = MRI.createVirtualRegister(PtrRC);
16405     if (Subtarget->is64Bit()) {
16406       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16407               .addReg(X86::RIP)
16408               .addImm(0)
16409               .addReg(0)
16410               .addMBB(restoreMBB)
16411               .addReg(0);
16412     } else {
16413       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16414       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16415               .addReg(XII->getGlobalBaseReg(MF))
16416               .addImm(0)
16417               .addReg(0)
16418               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16419               .addReg(0);
16420     }
16421   } else
16422     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16423   // Store IP
16424   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16425   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16426     if (i == X86::AddrDisp)
16427       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16428     else
16429       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16430   }
16431   if (!UseImmLabel)
16432     MIB.addReg(LabelReg);
16433   else
16434     MIB.addMBB(restoreMBB);
16435   MIB.setMemRefs(MMOBegin, MMOEnd);
16436   // Setup
16437   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16438           .addMBB(restoreMBB);
16439
16440   const X86RegisterInfo *RegInfo =
16441     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16442   MIB.addRegMask(RegInfo->getNoPreservedMask());
16443   thisMBB->addSuccessor(mainMBB);
16444   thisMBB->addSuccessor(restoreMBB);
16445
16446   // mainMBB:
16447   //  EAX = 0
16448   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16449   mainMBB->addSuccessor(sinkMBB);
16450
16451   // sinkMBB:
16452   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16453           TII->get(X86::PHI), DstReg)
16454     .addReg(mainDstReg).addMBB(mainMBB)
16455     .addReg(restoreDstReg).addMBB(restoreMBB);
16456
16457   // restoreMBB:
16458   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16459   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16460   restoreMBB->addSuccessor(sinkMBB);
16461
16462   MI->eraseFromParent();
16463   return sinkMBB;
16464 }
16465
16466 MachineBasicBlock *
16467 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16468                                      MachineBasicBlock *MBB) const {
16469   DebugLoc DL = MI->getDebugLoc();
16470   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16471
16472   MachineFunction *MF = MBB->getParent();
16473   MachineRegisterInfo &MRI = MF->getRegInfo();
16474
16475   // Memory Reference
16476   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16477   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16478
16479   MVT PVT = getPointerTy();
16480   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16481          "Invalid Pointer Size!");
16482
16483   const TargetRegisterClass *RC =
16484     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16485   unsigned Tmp = MRI.createVirtualRegister(RC);
16486   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16487   const X86RegisterInfo *RegInfo =
16488     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16489   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16490   unsigned SP = RegInfo->getStackRegister();
16491
16492   MachineInstrBuilder MIB;
16493
16494   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16495   const int64_t SPOffset = 2 * PVT.getStoreSize();
16496
16497   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16498   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16499
16500   // Reload FP
16501   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16502   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16503     MIB.addOperand(MI->getOperand(i));
16504   MIB.setMemRefs(MMOBegin, MMOEnd);
16505   // Reload IP
16506   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16507   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16508     if (i == X86::AddrDisp)
16509       MIB.addDisp(MI->getOperand(i), LabelOffset);
16510     else
16511       MIB.addOperand(MI->getOperand(i));
16512   }
16513   MIB.setMemRefs(MMOBegin, MMOEnd);
16514   // Reload SP
16515   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16516   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16517     if (i == X86::AddrDisp)
16518       MIB.addDisp(MI->getOperand(i), SPOffset);
16519     else
16520       MIB.addOperand(MI->getOperand(i));
16521   }
16522   MIB.setMemRefs(MMOBegin, MMOEnd);
16523   // Jump
16524   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16525
16526   MI->eraseFromParent();
16527   return MBB;
16528 }
16529
16530 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16531 // accumulator loops. Writing back to the accumulator allows the coalescer
16532 // to remove extra copies in the loop.   
16533 MachineBasicBlock *
16534 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16535                                  MachineBasicBlock *MBB) const {
16536   MachineOperand &AddendOp = MI->getOperand(3);
16537
16538   // Bail out early if the addend isn't a register - we can't switch these.
16539   if (!AddendOp.isReg())
16540     return MBB;
16541
16542   MachineFunction &MF = *MBB->getParent();
16543   MachineRegisterInfo &MRI = MF.getRegInfo();
16544
16545   // Check whether the addend is defined by a PHI:
16546   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16547   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16548   if (!AddendDef.isPHI())
16549     return MBB;
16550
16551   // Look for the following pattern:
16552   // loop:
16553   //   %addend = phi [%entry, 0], [%loop, %result]
16554   //   ...
16555   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16556
16557   // Replace with:
16558   //   loop:
16559   //   %addend = phi [%entry, 0], [%loop, %result]
16560   //   ...
16561   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16562
16563   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16564     assert(AddendDef.getOperand(i).isReg());
16565     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16566     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16567     if (&PHISrcInst == MI) {
16568       // Found a matching instruction.
16569       unsigned NewFMAOpc = 0;
16570       switch (MI->getOpcode()) {
16571         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16572         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16573         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16574         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16575         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16576         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16577         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16578         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16579         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16580         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16581         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16582         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16583         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16584         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16585         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16586         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16587         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16588         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16589         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16590         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16591         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16592         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16593         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16594         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16595         default: llvm_unreachable("Unrecognized FMA variant.");
16596       }
16597
16598       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16599       MachineInstrBuilder MIB =
16600         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16601         .addOperand(MI->getOperand(0))
16602         .addOperand(MI->getOperand(3))
16603         .addOperand(MI->getOperand(2))
16604         .addOperand(MI->getOperand(1));
16605       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16606       MI->eraseFromParent();
16607     }
16608   }
16609
16610   return MBB;
16611 }
16612
16613 MachineBasicBlock *
16614 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16615                                                MachineBasicBlock *BB) const {
16616   switch (MI->getOpcode()) {
16617   default: llvm_unreachable("Unexpected instr type to insert");
16618   case X86::TAILJMPd64:
16619   case X86::TAILJMPr64:
16620   case X86::TAILJMPm64:
16621     llvm_unreachable("TAILJMP64 would not be touched here.");
16622   case X86::TCRETURNdi64:
16623   case X86::TCRETURNri64:
16624   case X86::TCRETURNmi64:
16625     return BB;
16626   case X86::WIN_ALLOCA:
16627     return EmitLoweredWinAlloca(MI, BB);
16628   case X86::SEG_ALLOCA_32:
16629     return EmitLoweredSegAlloca(MI, BB, false);
16630   case X86::SEG_ALLOCA_64:
16631     return EmitLoweredSegAlloca(MI, BB, true);
16632   case X86::TLSCall_32:
16633   case X86::TLSCall_64:
16634     return EmitLoweredTLSCall(MI, BB);
16635   case X86::CMOV_GR8:
16636   case X86::CMOV_FR32:
16637   case X86::CMOV_FR64:
16638   case X86::CMOV_V4F32:
16639   case X86::CMOV_V2F64:
16640   case X86::CMOV_V2I64:
16641   case X86::CMOV_V8F32:
16642   case X86::CMOV_V4F64:
16643   case X86::CMOV_V4I64:
16644   case X86::CMOV_V16F32:
16645   case X86::CMOV_V8F64:
16646   case X86::CMOV_V8I64:
16647   case X86::CMOV_GR16:
16648   case X86::CMOV_GR32:
16649   case X86::CMOV_RFP32:
16650   case X86::CMOV_RFP64:
16651   case X86::CMOV_RFP80:
16652     return EmitLoweredSelect(MI, BB);
16653
16654   case X86::FP32_TO_INT16_IN_MEM:
16655   case X86::FP32_TO_INT32_IN_MEM:
16656   case X86::FP32_TO_INT64_IN_MEM:
16657   case X86::FP64_TO_INT16_IN_MEM:
16658   case X86::FP64_TO_INT32_IN_MEM:
16659   case X86::FP64_TO_INT64_IN_MEM:
16660   case X86::FP80_TO_INT16_IN_MEM:
16661   case X86::FP80_TO_INT32_IN_MEM:
16662   case X86::FP80_TO_INT64_IN_MEM: {
16663     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16664     DebugLoc DL = MI->getDebugLoc();
16665
16666     // Change the floating point control register to use "round towards zero"
16667     // mode when truncating to an integer value.
16668     MachineFunction *F = BB->getParent();
16669     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16670     addFrameReference(BuildMI(*BB, MI, DL,
16671                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16672
16673     // Load the old value of the high byte of the control word...
16674     unsigned OldCW =
16675       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16676     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16677                       CWFrameIdx);
16678
16679     // Set the high part to be round to zero...
16680     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16681       .addImm(0xC7F);
16682
16683     // Reload the modified control word now...
16684     addFrameReference(BuildMI(*BB, MI, DL,
16685                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16686
16687     // Restore the memory image of control word to original value
16688     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16689       .addReg(OldCW);
16690
16691     // Get the X86 opcode to use.
16692     unsigned Opc;
16693     switch (MI->getOpcode()) {
16694     default: llvm_unreachable("illegal opcode!");
16695     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16696     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16697     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16698     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16699     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16700     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16701     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16702     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16703     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16704     }
16705
16706     X86AddressMode AM;
16707     MachineOperand &Op = MI->getOperand(0);
16708     if (Op.isReg()) {
16709       AM.BaseType = X86AddressMode::RegBase;
16710       AM.Base.Reg = Op.getReg();
16711     } else {
16712       AM.BaseType = X86AddressMode::FrameIndexBase;
16713       AM.Base.FrameIndex = Op.getIndex();
16714     }
16715     Op = MI->getOperand(1);
16716     if (Op.isImm())
16717       AM.Scale = Op.getImm();
16718     Op = MI->getOperand(2);
16719     if (Op.isImm())
16720       AM.IndexReg = Op.getImm();
16721     Op = MI->getOperand(3);
16722     if (Op.isGlobal()) {
16723       AM.GV = Op.getGlobal();
16724     } else {
16725       AM.Disp = Op.getImm();
16726     }
16727     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16728                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16729
16730     // Reload the original control word now.
16731     addFrameReference(BuildMI(*BB, MI, DL,
16732                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16733
16734     MI->eraseFromParent();   // The pseudo instruction is gone now.
16735     return BB;
16736   }
16737     // String/text processing lowering.
16738   case X86::PCMPISTRM128REG:
16739   case X86::VPCMPISTRM128REG:
16740   case X86::PCMPISTRM128MEM:
16741   case X86::VPCMPISTRM128MEM:
16742   case X86::PCMPESTRM128REG:
16743   case X86::VPCMPESTRM128REG:
16744   case X86::PCMPESTRM128MEM:
16745   case X86::VPCMPESTRM128MEM:
16746     assert(Subtarget->hasSSE42() &&
16747            "Target must have SSE4.2 or AVX features enabled");
16748     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16749
16750   // String/text processing lowering.
16751   case X86::PCMPISTRIREG:
16752   case X86::VPCMPISTRIREG:
16753   case X86::PCMPISTRIMEM:
16754   case X86::VPCMPISTRIMEM:
16755   case X86::PCMPESTRIREG:
16756   case X86::VPCMPESTRIREG:
16757   case X86::PCMPESTRIMEM:
16758   case X86::VPCMPESTRIMEM:
16759     assert(Subtarget->hasSSE42() &&
16760            "Target must have SSE4.2 or AVX features enabled");
16761     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16762
16763   // Thread synchronization.
16764   case X86::MONITOR:
16765     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16766
16767   // xbegin
16768   case X86::XBEGIN:
16769     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16770
16771   // Atomic Lowering.
16772   case X86::ATOMAND8:
16773   case X86::ATOMAND16:
16774   case X86::ATOMAND32:
16775   case X86::ATOMAND64:
16776     // Fall through
16777   case X86::ATOMOR8:
16778   case X86::ATOMOR16:
16779   case X86::ATOMOR32:
16780   case X86::ATOMOR64:
16781     // Fall through
16782   case X86::ATOMXOR16:
16783   case X86::ATOMXOR8:
16784   case X86::ATOMXOR32:
16785   case X86::ATOMXOR64:
16786     // Fall through
16787   case X86::ATOMNAND8:
16788   case X86::ATOMNAND16:
16789   case X86::ATOMNAND32:
16790   case X86::ATOMNAND64:
16791     // Fall through
16792   case X86::ATOMMAX8:
16793   case X86::ATOMMAX16:
16794   case X86::ATOMMAX32:
16795   case X86::ATOMMAX64:
16796     // Fall through
16797   case X86::ATOMMIN8:
16798   case X86::ATOMMIN16:
16799   case X86::ATOMMIN32:
16800   case X86::ATOMMIN64:
16801     // Fall through
16802   case X86::ATOMUMAX8:
16803   case X86::ATOMUMAX16:
16804   case X86::ATOMUMAX32:
16805   case X86::ATOMUMAX64:
16806     // Fall through
16807   case X86::ATOMUMIN8:
16808   case X86::ATOMUMIN16:
16809   case X86::ATOMUMIN32:
16810   case X86::ATOMUMIN64:
16811     return EmitAtomicLoadArith(MI, BB);
16812
16813   // This group does 64-bit operations on a 32-bit host.
16814   case X86::ATOMAND6432:
16815   case X86::ATOMOR6432:
16816   case X86::ATOMXOR6432:
16817   case X86::ATOMNAND6432:
16818   case X86::ATOMADD6432:
16819   case X86::ATOMSUB6432:
16820   case X86::ATOMMAX6432:
16821   case X86::ATOMMIN6432:
16822   case X86::ATOMUMAX6432:
16823   case X86::ATOMUMIN6432:
16824   case X86::ATOMSWAP6432:
16825     return EmitAtomicLoadArith6432(MI, BB);
16826
16827   case X86::VASTART_SAVE_XMM_REGS:
16828     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16829
16830   case X86::VAARG_64:
16831     return EmitVAARG64WithCustomInserter(MI, BB);
16832
16833   case X86::EH_SjLj_SetJmp32:
16834   case X86::EH_SjLj_SetJmp64:
16835     return emitEHSjLjSetJmp(MI, BB);
16836
16837   case X86::EH_SjLj_LongJmp32:
16838   case X86::EH_SjLj_LongJmp64:
16839     return emitEHSjLjLongJmp(MI, BB);
16840
16841   case TargetOpcode::STACKMAP:
16842   case TargetOpcode::PATCHPOINT:
16843     return emitPatchPoint(MI, BB);
16844
16845   case X86::VFMADDPDr213r:
16846   case X86::VFMADDPSr213r:
16847   case X86::VFMADDSDr213r:
16848   case X86::VFMADDSSr213r:
16849   case X86::VFMSUBPDr213r:
16850   case X86::VFMSUBPSr213r:
16851   case X86::VFMSUBSDr213r:
16852   case X86::VFMSUBSSr213r:
16853   case X86::VFNMADDPDr213r:
16854   case X86::VFNMADDPSr213r:
16855   case X86::VFNMADDSDr213r:
16856   case X86::VFNMADDSSr213r:
16857   case X86::VFNMSUBPDr213r:
16858   case X86::VFNMSUBPSr213r:
16859   case X86::VFNMSUBSDr213r:
16860   case X86::VFNMSUBSSr213r:
16861   case X86::VFMADDPDr213rY:
16862   case X86::VFMADDPSr213rY:
16863   case X86::VFMSUBPDr213rY:
16864   case X86::VFMSUBPSr213rY:
16865   case X86::VFNMADDPDr213rY:
16866   case X86::VFNMADDPSr213rY:
16867   case X86::VFNMSUBPDr213rY:
16868   case X86::VFNMSUBPSr213rY:
16869     return emitFMA3Instr(MI, BB);
16870   }
16871 }
16872
16873 //===----------------------------------------------------------------------===//
16874 //                           X86 Optimization Hooks
16875 //===----------------------------------------------------------------------===//
16876
16877 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16878                                                        APInt &KnownZero,
16879                                                        APInt &KnownOne,
16880                                                        const SelectionDAG &DAG,
16881                                                        unsigned Depth) const {
16882   unsigned BitWidth = KnownZero.getBitWidth();
16883   unsigned Opc = Op.getOpcode();
16884   assert((Opc >= ISD::BUILTIN_OP_END ||
16885           Opc == ISD::INTRINSIC_WO_CHAIN ||
16886           Opc == ISD::INTRINSIC_W_CHAIN ||
16887           Opc == ISD::INTRINSIC_VOID) &&
16888          "Should use MaskedValueIsZero if you don't know whether Op"
16889          " is a target node!");
16890
16891   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16892   switch (Opc) {
16893   default: break;
16894   case X86ISD::ADD:
16895   case X86ISD::SUB:
16896   case X86ISD::ADC:
16897   case X86ISD::SBB:
16898   case X86ISD::SMUL:
16899   case X86ISD::UMUL:
16900   case X86ISD::INC:
16901   case X86ISD::DEC:
16902   case X86ISD::OR:
16903   case X86ISD::XOR:
16904   case X86ISD::AND:
16905     // These nodes' second result is a boolean.
16906     if (Op.getResNo() == 0)
16907       break;
16908     // Fallthrough
16909   case X86ISD::SETCC:
16910     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16911     break;
16912   case ISD::INTRINSIC_WO_CHAIN: {
16913     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16914     unsigned NumLoBits = 0;
16915     switch (IntId) {
16916     default: break;
16917     case Intrinsic::x86_sse_movmsk_ps:
16918     case Intrinsic::x86_avx_movmsk_ps_256:
16919     case Intrinsic::x86_sse2_movmsk_pd:
16920     case Intrinsic::x86_avx_movmsk_pd_256:
16921     case Intrinsic::x86_mmx_pmovmskb:
16922     case Intrinsic::x86_sse2_pmovmskb_128:
16923     case Intrinsic::x86_avx2_pmovmskb: {
16924       // High bits of movmskp{s|d}, pmovmskb are known zero.
16925       switch (IntId) {
16926         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16927         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16928         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16929         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16930         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16931         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16932         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16933         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16934       }
16935       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16936       break;
16937     }
16938     }
16939     break;
16940   }
16941   }
16942 }
16943
16944 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16945   SDValue Op,
16946   const SelectionDAG &,
16947   unsigned Depth) const {
16948   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16949   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16950     return Op.getValueType().getScalarType().getSizeInBits();
16951
16952   // Fallback case.
16953   return 1;
16954 }
16955
16956 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16957 /// node is a GlobalAddress + offset.
16958 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16959                                        const GlobalValue* &GA,
16960                                        int64_t &Offset) const {
16961   if (N->getOpcode() == X86ISD::Wrapper) {
16962     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16963       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16964       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16965       return true;
16966     }
16967   }
16968   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16969 }
16970
16971 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16972 /// same as extracting the high 128-bit part of 256-bit vector and then
16973 /// inserting the result into the low part of a new 256-bit vector
16974 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16975   EVT VT = SVOp->getValueType(0);
16976   unsigned NumElems = VT.getVectorNumElements();
16977
16978   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16979   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16980     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16981         SVOp->getMaskElt(j) >= 0)
16982       return false;
16983
16984   return true;
16985 }
16986
16987 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16988 /// same as extracting the low 128-bit part of 256-bit vector and then
16989 /// inserting the result into the high part of a new 256-bit vector
16990 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16991   EVT VT = SVOp->getValueType(0);
16992   unsigned NumElems = VT.getVectorNumElements();
16993
16994   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16995   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16996     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16997         SVOp->getMaskElt(j) >= 0)
16998       return false;
16999
17000   return true;
17001 }
17002
17003 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17004 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17005                                         TargetLowering::DAGCombinerInfo &DCI,
17006                                         const X86Subtarget* Subtarget) {
17007   SDLoc dl(N);
17008   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17009   SDValue V1 = SVOp->getOperand(0);
17010   SDValue V2 = SVOp->getOperand(1);
17011   EVT VT = SVOp->getValueType(0);
17012   unsigned NumElems = VT.getVectorNumElements();
17013
17014   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17015       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17016     //
17017     //                   0,0,0,...
17018     //                      |
17019     //    V      UNDEF    BUILD_VECTOR    UNDEF
17020     //     \      /           \           /
17021     //  CONCAT_VECTOR         CONCAT_VECTOR
17022     //         \                  /
17023     //          \                /
17024     //          RESULT: V + zero extended
17025     //
17026     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17027         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17028         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17029       return SDValue();
17030
17031     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17032       return SDValue();
17033
17034     // To match the shuffle mask, the first half of the mask should
17035     // be exactly the first vector, and all the rest a splat with the
17036     // first element of the second one.
17037     for (unsigned i = 0; i != NumElems/2; ++i)
17038       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17039           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17040         return SDValue();
17041
17042     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17043     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17044       if (Ld->hasNUsesOfValue(1, 0)) {
17045         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17046         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17047         SDValue ResNode =
17048           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17049                                   array_lengthof(Ops),
17050                                   Ld->getMemoryVT(),
17051                                   Ld->getPointerInfo(),
17052                                   Ld->getAlignment(),
17053                                   false/*isVolatile*/, true/*ReadMem*/,
17054                                   false/*WriteMem*/);
17055
17056         // Make sure the newly-created LOAD is in the same position as Ld in
17057         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17058         // and update uses of Ld's output chain to use the TokenFactor.
17059         if (Ld->hasAnyUseOfValue(1)) {
17060           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17061                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17062           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17063           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17064                                  SDValue(ResNode.getNode(), 1));
17065         }
17066
17067         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17068       }
17069     }
17070
17071     // Emit a zeroed vector and insert the desired subvector on its
17072     // first half.
17073     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17074     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17075     return DCI.CombineTo(N, InsV);
17076   }
17077
17078   //===--------------------------------------------------------------------===//
17079   // Combine some shuffles into subvector extracts and inserts:
17080   //
17081
17082   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17083   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17084     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17085     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17086     return DCI.CombineTo(N, InsV);
17087   }
17088
17089   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17090   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17091     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17092     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17093     return DCI.CombineTo(N, InsV);
17094   }
17095
17096   return SDValue();
17097 }
17098
17099 /// PerformShuffleCombine - Performs several different shuffle combines.
17100 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17101                                      TargetLowering::DAGCombinerInfo &DCI,
17102                                      const X86Subtarget *Subtarget) {
17103   SDLoc dl(N);
17104   EVT VT = N->getValueType(0);
17105
17106   // Don't create instructions with illegal types after legalize types has run.
17107   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17108   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17109     return SDValue();
17110
17111   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17112   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17113       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17114     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17115
17116   // Only handle 128 wide vector from here on.
17117   if (!VT.is128BitVector())
17118     return SDValue();
17119
17120   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17121   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17122   // consecutive, non-overlapping, and in the right order.
17123   SmallVector<SDValue, 16> Elts;
17124   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17125     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17126
17127   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17128 }
17129
17130 /// PerformTruncateCombine - Converts truncate operation to
17131 /// a sequence of vector shuffle operations.
17132 /// It is possible when we truncate 256-bit vector to 128-bit vector
17133 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17134                                       TargetLowering::DAGCombinerInfo &DCI,
17135                                       const X86Subtarget *Subtarget)  {
17136   return SDValue();
17137 }
17138
17139 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17140 /// specific shuffle of a load can be folded into a single element load.
17141 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17142 /// shuffles have been customed lowered so we need to handle those here.
17143 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17144                                          TargetLowering::DAGCombinerInfo &DCI) {
17145   if (DCI.isBeforeLegalizeOps())
17146     return SDValue();
17147
17148   SDValue InVec = N->getOperand(0);
17149   SDValue EltNo = N->getOperand(1);
17150
17151   if (!isa<ConstantSDNode>(EltNo))
17152     return SDValue();
17153
17154   EVT VT = InVec.getValueType();
17155
17156   bool HasShuffleIntoBitcast = false;
17157   if (InVec.getOpcode() == ISD::BITCAST) {
17158     // Don't duplicate a load with other uses.
17159     if (!InVec.hasOneUse())
17160       return SDValue();
17161     EVT BCVT = InVec.getOperand(0).getValueType();
17162     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17163       return SDValue();
17164     InVec = InVec.getOperand(0);
17165     HasShuffleIntoBitcast = true;
17166   }
17167
17168   if (!isTargetShuffle(InVec.getOpcode()))
17169     return SDValue();
17170
17171   // Don't duplicate a load with other uses.
17172   if (!InVec.hasOneUse())
17173     return SDValue();
17174
17175   SmallVector<int, 16> ShuffleMask;
17176   bool UnaryShuffle;
17177   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17178                             UnaryShuffle))
17179     return SDValue();
17180
17181   // Select the input vector, guarding against out of range extract vector.
17182   unsigned NumElems = VT.getVectorNumElements();
17183   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17184   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17185   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17186                                          : InVec.getOperand(1);
17187
17188   // If inputs to shuffle are the same for both ops, then allow 2 uses
17189   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17190
17191   if (LdNode.getOpcode() == ISD::BITCAST) {
17192     // Don't duplicate a load with other uses.
17193     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17194       return SDValue();
17195
17196     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17197     LdNode = LdNode.getOperand(0);
17198   }
17199
17200   if (!ISD::isNormalLoad(LdNode.getNode()))
17201     return SDValue();
17202
17203   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17204
17205   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17206     return SDValue();
17207
17208   if (HasShuffleIntoBitcast) {
17209     // If there's a bitcast before the shuffle, check if the load type and
17210     // alignment is valid.
17211     unsigned Align = LN0->getAlignment();
17212     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17213     unsigned NewAlign = TLI.getDataLayout()->
17214       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17215
17216     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17217       return SDValue();
17218   }
17219
17220   // All checks match so transform back to vector_shuffle so that DAG combiner
17221   // can finish the job
17222   SDLoc dl(N);
17223
17224   // Create shuffle node taking into account the case that its a unary shuffle
17225   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17226   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17227                                  InVec.getOperand(0), Shuffle,
17228                                  &ShuffleMask[0]);
17229   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17230   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17231                      EltNo);
17232 }
17233
17234 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17235 /// generation and convert it from being a bunch of shuffles and extracts
17236 /// to a simple store and scalar loads to extract the elements.
17237 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17238                                          TargetLowering::DAGCombinerInfo &DCI) {
17239   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17240   if (NewOp.getNode())
17241     return NewOp;
17242
17243   SDValue InputVector = N->getOperand(0);
17244
17245   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17246   // from mmx to v2i32 has a single usage.
17247   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17248       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17249       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17250     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17251                        N->getValueType(0),
17252                        InputVector.getNode()->getOperand(0));
17253
17254   // Only operate on vectors of 4 elements, where the alternative shuffling
17255   // gets to be more expensive.
17256   if (InputVector.getValueType() != MVT::v4i32)
17257     return SDValue();
17258
17259   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17260   // single use which is a sign-extend or zero-extend, and all elements are
17261   // used.
17262   SmallVector<SDNode *, 4> Uses;
17263   unsigned ExtractedElements = 0;
17264   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17265        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17266     if (UI.getUse().getResNo() != InputVector.getResNo())
17267       return SDValue();
17268
17269     SDNode *Extract = *UI;
17270     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17271       return SDValue();
17272
17273     if (Extract->getValueType(0) != MVT::i32)
17274       return SDValue();
17275     if (!Extract->hasOneUse())
17276       return SDValue();
17277     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17278         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17279       return SDValue();
17280     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17281       return SDValue();
17282
17283     // Record which element was extracted.
17284     ExtractedElements |=
17285       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17286
17287     Uses.push_back(Extract);
17288   }
17289
17290   // If not all the elements were used, this may not be worthwhile.
17291   if (ExtractedElements != 15)
17292     return SDValue();
17293
17294   // Ok, we've now decided to do the transformation.
17295   SDLoc dl(InputVector);
17296
17297   // Store the value to a temporary stack slot.
17298   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17299   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17300                             MachinePointerInfo(), false, false, 0);
17301
17302   // Replace each use (extract) with a load of the appropriate element.
17303   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17304        UE = Uses.end(); UI != UE; ++UI) {
17305     SDNode *Extract = *UI;
17306
17307     // cOMpute the element's address.
17308     SDValue Idx = Extract->getOperand(1);
17309     unsigned EltSize =
17310         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17311     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17312     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17313     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17314
17315     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17316                                      StackPtr, OffsetVal);
17317
17318     // Load the scalar.
17319     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17320                                      ScalarAddr, MachinePointerInfo(),
17321                                      false, false, false, 0);
17322
17323     // Replace the exact with the load.
17324     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17325   }
17326
17327   // The replacement was made in place; don't return anything.
17328   return SDValue();
17329 }
17330
17331 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17332 static std::pair<unsigned, bool>
17333 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17334                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17335   if (!VT.isVector())
17336     return std::make_pair(0, false);
17337
17338   bool NeedSplit = false;
17339   switch (VT.getSimpleVT().SimpleTy) {
17340   default: return std::make_pair(0, false);
17341   case MVT::v32i8:
17342   case MVT::v16i16:
17343   case MVT::v8i32:
17344     if (!Subtarget->hasAVX2())
17345       NeedSplit = true;
17346     if (!Subtarget->hasAVX())
17347       return std::make_pair(0, false);
17348     break;
17349   case MVT::v16i8:
17350   case MVT::v8i16:
17351   case MVT::v4i32:
17352     if (!Subtarget->hasSSE2())
17353       return std::make_pair(0, false);
17354   }
17355
17356   // SSE2 has only a small subset of the operations.
17357   bool hasUnsigned = Subtarget->hasSSE41() ||
17358                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17359   bool hasSigned = Subtarget->hasSSE41() ||
17360                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17361
17362   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17363
17364   unsigned Opc = 0;
17365   // Check for x CC y ? x : y.
17366   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17367       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17368     switch (CC) {
17369     default: break;
17370     case ISD::SETULT:
17371     case ISD::SETULE:
17372       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17373     case ISD::SETUGT:
17374     case ISD::SETUGE:
17375       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17376     case ISD::SETLT:
17377     case ISD::SETLE:
17378       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17379     case ISD::SETGT:
17380     case ISD::SETGE:
17381       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17382     }
17383   // Check for x CC y ? y : x -- a min/max with reversed arms.
17384   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17385              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17386     switch (CC) {
17387     default: break;
17388     case ISD::SETULT:
17389     case ISD::SETULE:
17390       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17391     case ISD::SETUGT:
17392     case ISD::SETUGE:
17393       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17394     case ISD::SETLT:
17395     case ISD::SETLE:
17396       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17397     case ISD::SETGT:
17398     case ISD::SETGE:
17399       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17400     }
17401   }
17402
17403   return std::make_pair(Opc, NeedSplit);
17404 }
17405
17406 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17407 /// nodes.
17408 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17409                                     TargetLowering::DAGCombinerInfo &DCI,
17410                                     const X86Subtarget *Subtarget) {
17411   SDLoc DL(N);
17412   SDValue Cond = N->getOperand(0);
17413   // Get the LHS/RHS of the select.
17414   SDValue LHS = N->getOperand(1);
17415   SDValue RHS = N->getOperand(2);
17416   EVT VT = LHS.getValueType();
17417   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17418
17419   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17420   // instructions match the semantics of the common C idiom x<y?x:y but not
17421   // x<=y?x:y, because of how they handle negative zero (which can be
17422   // ignored in unsafe-math mode).
17423   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17424       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17425       (Subtarget->hasSSE2() ||
17426        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17427     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17428
17429     unsigned Opcode = 0;
17430     // Check for x CC y ? x : y.
17431     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17432         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17433       switch (CC) {
17434       default: break;
17435       case ISD::SETULT:
17436         // Converting this to a min would handle NaNs incorrectly, and swapping
17437         // the operands would cause it to handle comparisons between positive
17438         // and negative zero incorrectly.
17439         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17440           if (!DAG.getTarget().Options.UnsafeFPMath &&
17441               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17442             break;
17443           std::swap(LHS, RHS);
17444         }
17445         Opcode = X86ISD::FMIN;
17446         break;
17447       case ISD::SETOLE:
17448         // Converting this to a min would handle comparisons between positive
17449         // and negative zero incorrectly.
17450         if (!DAG.getTarget().Options.UnsafeFPMath &&
17451             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17452           break;
17453         Opcode = X86ISD::FMIN;
17454         break;
17455       case ISD::SETULE:
17456         // Converting this to a min would handle both negative zeros and NaNs
17457         // incorrectly, but we can swap the operands to fix both.
17458         std::swap(LHS, RHS);
17459       case ISD::SETOLT:
17460       case ISD::SETLT:
17461       case ISD::SETLE:
17462         Opcode = X86ISD::FMIN;
17463         break;
17464
17465       case ISD::SETOGE:
17466         // Converting this to a max would handle comparisons between positive
17467         // and negative zero incorrectly.
17468         if (!DAG.getTarget().Options.UnsafeFPMath &&
17469             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17470           break;
17471         Opcode = X86ISD::FMAX;
17472         break;
17473       case ISD::SETUGT:
17474         // Converting this to a max would handle NaNs incorrectly, and swapping
17475         // the operands would cause it to handle comparisons between positive
17476         // and negative zero incorrectly.
17477         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17478           if (!DAG.getTarget().Options.UnsafeFPMath &&
17479               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17480             break;
17481           std::swap(LHS, RHS);
17482         }
17483         Opcode = X86ISD::FMAX;
17484         break;
17485       case ISD::SETUGE:
17486         // Converting this to a max would handle both negative zeros and NaNs
17487         // incorrectly, but we can swap the operands to fix both.
17488         std::swap(LHS, RHS);
17489       case ISD::SETOGT:
17490       case ISD::SETGT:
17491       case ISD::SETGE:
17492         Opcode = X86ISD::FMAX;
17493         break;
17494       }
17495     // Check for x CC y ? y : x -- a min/max with reversed arms.
17496     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17497                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17498       switch (CC) {
17499       default: break;
17500       case ISD::SETOGE:
17501         // Converting this to a min would handle comparisons between positive
17502         // and negative zero incorrectly, and swapping the operands would
17503         // cause it to handle NaNs incorrectly.
17504         if (!DAG.getTarget().Options.UnsafeFPMath &&
17505             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17506           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17507             break;
17508           std::swap(LHS, RHS);
17509         }
17510         Opcode = X86ISD::FMIN;
17511         break;
17512       case ISD::SETUGT:
17513         // Converting this to a min would handle NaNs incorrectly.
17514         if (!DAG.getTarget().Options.UnsafeFPMath &&
17515             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17516           break;
17517         Opcode = X86ISD::FMIN;
17518         break;
17519       case ISD::SETUGE:
17520         // Converting this to a min would handle both negative zeros and NaNs
17521         // incorrectly, but we can swap the operands to fix both.
17522         std::swap(LHS, RHS);
17523       case ISD::SETOGT:
17524       case ISD::SETGT:
17525       case ISD::SETGE:
17526         Opcode = X86ISD::FMIN;
17527         break;
17528
17529       case ISD::SETULT:
17530         // Converting this to a max would handle NaNs incorrectly.
17531         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17532           break;
17533         Opcode = X86ISD::FMAX;
17534         break;
17535       case ISD::SETOLE:
17536         // Converting this to a max would handle comparisons between positive
17537         // and negative zero incorrectly, and swapping the operands would
17538         // cause it to handle NaNs incorrectly.
17539         if (!DAG.getTarget().Options.UnsafeFPMath &&
17540             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17541           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17542             break;
17543           std::swap(LHS, RHS);
17544         }
17545         Opcode = X86ISD::FMAX;
17546         break;
17547       case ISD::SETULE:
17548         // Converting this to a max would handle both negative zeros and NaNs
17549         // incorrectly, but we can swap the operands to fix both.
17550         std::swap(LHS, RHS);
17551       case ISD::SETOLT:
17552       case ISD::SETLT:
17553       case ISD::SETLE:
17554         Opcode = X86ISD::FMAX;
17555         break;
17556       }
17557     }
17558
17559     if (Opcode)
17560       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17561   }
17562
17563   EVT CondVT = Cond.getValueType();
17564   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17565       CondVT.getVectorElementType() == MVT::i1) {
17566     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17567     // lowering on AVX-512. In this case we convert it to
17568     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17569     // The same situation for all 128 and 256-bit vectors of i8 and i16
17570     EVT OpVT = LHS.getValueType();
17571     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17572         (OpVT.getVectorElementType() == MVT::i8 ||
17573          OpVT.getVectorElementType() == MVT::i16)) {
17574       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17575       DCI.AddToWorklist(Cond.getNode());
17576       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17577     }
17578   }
17579   // If this is a select between two integer constants, try to do some
17580   // optimizations.
17581   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17582     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17583       // Don't do this for crazy integer types.
17584       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17585         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17586         // so that TrueC (the true value) is larger than FalseC.
17587         bool NeedsCondInvert = false;
17588
17589         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17590             // Efficiently invertible.
17591             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17592              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17593               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17594           NeedsCondInvert = true;
17595           std::swap(TrueC, FalseC);
17596         }
17597
17598         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17599         if (FalseC->getAPIntValue() == 0 &&
17600             TrueC->getAPIntValue().isPowerOf2()) {
17601           if (NeedsCondInvert) // Invert the condition if needed.
17602             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17603                                DAG.getConstant(1, Cond.getValueType()));
17604
17605           // Zero extend the condition if needed.
17606           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17607
17608           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17609           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17610                              DAG.getConstant(ShAmt, MVT::i8));
17611         }
17612
17613         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17614         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17615           if (NeedsCondInvert) // Invert the condition if needed.
17616             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17617                                DAG.getConstant(1, Cond.getValueType()));
17618
17619           // Zero extend the condition if needed.
17620           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17621                              FalseC->getValueType(0), Cond);
17622           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17623                              SDValue(FalseC, 0));
17624         }
17625
17626         // Optimize cases that will turn into an LEA instruction.  This requires
17627         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17628         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17629           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17630           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17631
17632           bool isFastMultiplier = false;
17633           if (Diff < 10) {
17634             switch ((unsigned char)Diff) {
17635               default: break;
17636               case 1:  // result = add base, cond
17637               case 2:  // result = lea base(    , cond*2)
17638               case 3:  // result = lea base(cond, cond*2)
17639               case 4:  // result = lea base(    , cond*4)
17640               case 5:  // result = lea base(cond, cond*4)
17641               case 8:  // result = lea base(    , cond*8)
17642               case 9:  // result = lea base(cond, cond*8)
17643                 isFastMultiplier = true;
17644                 break;
17645             }
17646           }
17647
17648           if (isFastMultiplier) {
17649             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17650             if (NeedsCondInvert) // Invert the condition if needed.
17651               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17652                                  DAG.getConstant(1, Cond.getValueType()));
17653
17654             // Zero extend the condition if needed.
17655             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17656                                Cond);
17657             // Scale the condition by the difference.
17658             if (Diff != 1)
17659               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17660                                  DAG.getConstant(Diff, Cond.getValueType()));
17661
17662             // Add the base if non-zero.
17663             if (FalseC->getAPIntValue() != 0)
17664               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17665                                  SDValue(FalseC, 0));
17666             return Cond;
17667           }
17668         }
17669       }
17670   }
17671
17672   // Canonicalize max and min:
17673   // (x > y) ? x : y -> (x >= y) ? x : y
17674   // (x < y) ? x : y -> (x <= y) ? x : y
17675   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17676   // the need for an extra compare
17677   // against zero. e.g.
17678   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17679   // subl   %esi, %edi
17680   // testl  %edi, %edi
17681   // movl   $0, %eax
17682   // cmovgl %edi, %eax
17683   // =>
17684   // xorl   %eax, %eax
17685   // subl   %esi, $edi
17686   // cmovsl %eax, %edi
17687   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17688       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17689       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17690     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17691     switch (CC) {
17692     default: break;
17693     case ISD::SETLT:
17694     case ISD::SETGT: {
17695       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17696       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17697                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17698       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17699     }
17700     }
17701   }
17702
17703   // Early exit check
17704   if (!TLI.isTypeLegal(VT))
17705     return SDValue();
17706
17707   // Match VSELECTs into subs with unsigned saturation.
17708   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17709       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17710       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17711        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17712     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17713
17714     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17715     // left side invert the predicate to simplify logic below.
17716     SDValue Other;
17717     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17718       Other = RHS;
17719       CC = ISD::getSetCCInverse(CC, true);
17720     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17721       Other = LHS;
17722     }
17723
17724     if (Other.getNode() && Other->getNumOperands() == 2 &&
17725         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17726       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17727       SDValue CondRHS = Cond->getOperand(1);
17728
17729       // Look for a general sub with unsigned saturation first.
17730       // x >= y ? x-y : 0 --> subus x, y
17731       // x >  y ? x-y : 0 --> subus x, y
17732       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17733           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17734         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17735
17736       // If the RHS is a constant we have to reverse the const canonicalization.
17737       // x > C-1 ? x+-C : 0 --> subus x, C
17738       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17739           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17740         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17741         if (CondRHS.getConstantOperandVal(0) == -A-1)
17742           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17743                              DAG.getConstant(-A, VT));
17744       }
17745
17746       // Another special case: If C was a sign bit, the sub has been
17747       // canonicalized into a xor.
17748       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17749       //        it's safe to decanonicalize the xor?
17750       // x s< 0 ? x^C : 0 --> subus x, C
17751       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17752           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17753           isSplatVector(OpRHS.getNode())) {
17754         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17755         if (A.isSignBit())
17756           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17757       }
17758     }
17759   }
17760
17761   // Try to match a min/max vector operation.
17762   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17763     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17764     unsigned Opc = ret.first;
17765     bool NeedSplit = ret.second;
17766
17767     if (Opc && NeedSplit) {
17768       unsigned NumElems = VT.getVectorNumElements();
17769       // Extract the LHS vectors
17770       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17771       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17772
17773       // Extract the RHS vectors
17774       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17775       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17776
17777       // Create min/max for each subvector
17778       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17779       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17780
17781       // Merge the result
17782       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17783     } else if (Opc)
17784       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17785   }
17786
17787   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17788   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17789       // Check if SETCC has already been promoted
17790       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17791       // Check that condition value type matches vselect operand type
17792       CondVT == VT) { 
17793
17794     assert(Cond.getValueType().isVector() &&
17795            "vector select expects a vector selector!");
17796
17797     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17798     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17799
17800     if (!TValIsAllOnes && !FValIsAllZeros) {
17801       // Try invert the condition if true value is not all 1s and false value
17802       // is not all 0s.
17803       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17804       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17805
17806       if (TValIsAllZeros || FValIsAllOnes) {
17807         SDValue CC = Cond.getOperand(2);
17808         ISD::CondCode NewCC =
17809           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17810                                Cond.getOperand(0).getValueType().isInteger());
17811         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17812         std::swap(LHS, RHS);
17813         TValIsAllOnes = FValIsAllOnes;
17814         FValIsAllZeros = TValIsAllZeros;
17815       }
17816     }
17817
17818     if (TValIsAllOnes || FValIsAllZeros) {
17819       SDValue Ret;
17820
17821       if (TValIsAllOnes && FValIsAllZeros)
17822         Ret = Cond;
17823       else if (TValIsAllOnes)
17824         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17825                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17826       else if (FValIsAllZeros)
17827         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17828                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17829
17830       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17831     }
17832   }
17833
17834   // Try to fold this VSELECT into a MOVSS/MOVSD
17835   if (N->getOpcode() == ISD::VSELECT &&
17836       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17837     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17838         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17839       bool CanFold = false;
17840       unsigned NumElems = Cond.getNumOperands();
17841       SDValue A = LHS;
17842       SDValue B = RHS;
17843       
17844       if (isZero(Cond.getOperand(0))) {
17845         CanFold = true;
17846
17847         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17848         // fold (vselect <0,-1> -> (movsd A, B)
17849         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17850           CanFold = isAllOnes(Cond.getOperand(i));
17851       } else if (isAllOnes(Cond.getOperand(0))) {
17852         CanFold = true;
17853         std::swap(A, B);
17854
17855         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17856         // fold (vselect <-1,0> -> (movsd B, A)
17857         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17858           CanFold = isZero(Cond.getOperand(i));
17859       }
17860
17861       if (CanFold) {
17862         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17863           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17864         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17865       }
17866
17867       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17868         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17869         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17870         //                             (v2i64 (bitcast B)))))
17871         //
17872         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17873         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17874         //                             (v2f64 (bitcast B)))))
17875         //
17876         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17877         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17878         //                             (v2i64 (bitcast A)))))
17879         //
17880         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17881         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17882         //                             (v2f64 (bitcast A)))))
17883
17884         CanFold = (isZero(Cond.getOperand(0)) &&
17885                    isZero(Cond.getOperand(1)) &&
17886                    isAllOnes(Cond.getOperand(2)) &&
17887                    isAllOnes(Cond.getOperand(3)));
17888
17889         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17890             isAllOnes(Cond.getOperand(1)) &&
17891             isZero(Cond.getOperand(2)) &&
17892             isZero(Cond.getOperand(3))) {
17893           CanFold = true;
17894           std::swap(LHS, RHS);
17895         }
17896
17897         if (CanFold) {
17898           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17899           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17900           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17901           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17902                                                 NewB, DAG);
17903           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17904         }
17905       }
17906     }
17907   }
17908
17909   // If we know that this node is legal then we know that it is going to be
17910   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17911   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17912   // to simplify previous instructions.
17913   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17914       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17915     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17916
17917     // Don't optimize vector selects that map to mask-registers.
17918     if (BitWidth == 1)
17919       return SDValue();
17920
17921     // Check all uses of that condition operand to check whether it will be
17922     // consumed by non-BLEND instructions, which may depend on all bits are set
17923     // properly.
17924     for (SDNode::use_iterator I = Cond->use_begin(),
17925                               E = Cond->use_end(); I != E; ++I)
17926       if (I->getOpcode() != ISD::VSELECT)
17927         // TODO: Add other opcodes eventually lowered into BLEND.
17928         return SDValue();
17929
17930     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17931     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17932
17933     APInt KnownZero, KnownOne;
17934     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17935                                           DCI.isBeforeLegalizeOps());
17936     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17937         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17938       DCI.CommitTargetLoweringOpt(TLO);
17939   }
17940
17941   return SDValue();
17942 }
17943
17944 // Check whether a boolean test is testing a boolean value generated by
17945 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17946 // code.
17947 //
17948 // Simplify the following patterns:
17949 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17950 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17951 // to (Op EFLAGS Cond)
17952 //
17953 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17954 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17955 // to (Op EFLAGS !Cond)
17956 //
17957 // where Op could be BRCOND or CMOV.
17958 //
17959 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17960   // Quit if not CMP and SUB with its value result used.
17961   if (Cmp.getOpcode() != X86ISD::CMP &&
17962       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17963       return SDValue();
17964
17965   // Quit if not used as a boolean value.
17966   if (CC != X86::COND_E && CC != X86::COND_NE)
17967     return SDValue();
17968
17969   // Check CMP operands. One of them should be 0 or 1 and the other should be
17970   // an SetCC or extended from it.
17971   SDValue Op1 = Cmp.getOperand(0);
17972   SDValue Op2 = Cmp.getOperand(1);
17973
17974   SDValue SetCC;
17975   const ConstantSDNode* C = nullptr;
17976   bool needOppositeCond = (CC == X86::COND_E);
17977   bool checkAgainstTrue = false; // Is it a comparison against 1?
17978
17979   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17980     SetCC = Op2;
17981   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17982     SetCC = Op1;
17983   else // Quit if all operands are not constants.
17984     return SDValue();
17985
17986   if (C->getZExtValue() == 1) {
17987     needOppositeCond = !needOppositeCond;
17988     checkAgainstTrue = true;
17989   } else if (C->getZExtValue() != 0)
17990     // Quit if the constant is neither 0 or 1.
17991     return SDValue();
17992
17993   bool truncatedToBoolWithAnd = false;
17994   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17995   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17996          SetCC.getOpcode() == ISD::TRUNCATE ||
17997          SetCC.getOpcode() == ISD::AND) {
17998     if (SetCC.getOpcode() == ISD::AND) {
17999       int OpIdx = -1;
18000       ConstantSDNode *CS;
18001       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18002           CS->getZExtValue() == 1)
18003         OpIdx = 1;
18004       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18005           CS->getZExtValue() == 1)
18006         OpIdx = 0;
18007       if (OpIdx == -1)
18008         break;
18009       SetCC = SetCC.getOperand(OpIdx);
18010       truncatedToBoolWithAnd = true;
18011     } else
18012       SetCC = SetCC.getOperand(0);
18013   }
18014
18015   switch (SetCC.getOpcode()) {
18016   case X86ISD::SETCC_CARRY:
18017     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18018     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18019     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18020     // truncated to i1 using 'and'.
18021     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18022       break;
18023     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18024            "Invalid use of SETCC_CARRY!");
18025     // FALL THROUGH
18026   case X86ISD::SETCC:
18027     // Set the condition code or opposite one if necessary.
18028     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18029     if (needOppositeCond)
18030       CC = X86::GetOppositeBranchCondition(CC);
18031     return SetCC.getOperand(1);
18032   case X86ISD::CMOV: {
18033     // Check whether false/true value has canonical one, i.e. 0 or 1.
18034     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18035     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18036     // Quit if true value is not a constant.
18037     if (!TVal)
18038       return SDValue();
18039     // Quit if false value is not a constant.
18040     if (!FVal) {
18041       SDValue Op = SetCC.getOperand(0);
18042       // Skip 'zext' or 'trunc' node.
18043       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18044           Op.getOpcode() == ISD::TRUNCATE)
18045         Op = Op.getOperand(0);
18046       // A special case for rdrand/rdseed, where 0 is set if false cond is
18047       // found.
18048       if ((Op.getOpcode() != X86ISD::RDRAND &&
18049            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18050         return SDValue();
18051     }
18052     // Quit if false value is not the constant 0 or 1.
18053     bool FValIsFalse = true;
18054     if (FVal && FVal->getZExtValue() != 0) {
18055       if (FVal->getZExtValue() != 1)
18056         return SDValue();
18057       // If FVal is 1, opposite cond is needed.
18058       needOppositeCond = !needOppositeCond;
18059       FValIsFalse = false;
18060     }
18061     // Quit if TVal is not the constant opposite of FVal.
18062     if (FValIsFalse && TVal->getZExtValue() != 1)
18063       return SDValue();
18064     if (!FValIsFalse && TVal->getZExtValue() != 0)
18065       return SDValue();
18066     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18067     if (needOppositeCond)
18068       CC = X86::GetOppositeBranchCondition(CC);
18069     return SetCC.getOperand(3);
18070   }
18071   }
18072
18073   return SDValue();
18074 }
18075
18076 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18077 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18078                                   TargetLowering::DAGCombinerInfo &DCI,
18079                                   const X86Subtarget *Subtarget) {
18080   SDLoc DL(N);
18081
18082   // If the flag operand isn't dead, don't touch this CMOV.
18083   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18084     return SDValue();
18085
18086   SDValue FalseOp = N->getOperand(0);
18087   SDValue TrueOp = N->getOperand(1);
18088   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18089   SDValue Cond = N->getOperand(3);
18090
18091   if (CC == X86::COND_E || CC == X86::COND_NE) {
18092     switch (Cond.getOpcode()) {
18093     default: break;
18094     case X86ISD::BSR:
18095     case X86ISD::BSF:
18096       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18097       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18098         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18099     }
18100   }
18101
18102   SDValue Flags;
18103
18104   Flags = checkBoolTestSetCCCombine(Cond, CC);
18105   if (Flags.getNode() &&
18106       // Extra check as FCMOV only supports a subset of X86 cond.
18107       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18108     SDValue Ops[] = { FalseOp, TrueOp,
18109                       DAG.getConstant(CC, MVT::i8), Flags };
18110     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18111   }
18112
18113   // If this is a select between two integer constants, try to do some
18114   // optimizations.  Note that the operands are ordered the opposite of SELECT
18115   // operands.
18116   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18117     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18118       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18119       // larger than FalseC (the false value).
18120       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18121         CC = X86::GetOppositeBranchCondition(CC);
18122         std::swap(TrueC, FalseC);
18123         std::swap(TrueOp, FalseOp);
18124       }
18125
18126       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18127       // This is efficient for any integer data type (including i8/i16) and
18128       // shift amount.
18129       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18130         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18131                            DAG.getConstant(CC, MVT::i8), Cond);
18132
18133         // Zero extend the condition if needed.
18134         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18135
18136         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18137         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18138                            DAG.getConstant(ShAmt, MVT::i8));
18139         if (N->getNumValues() == 2)  // Dead flag value?
18140           return DCI.CombineTo(N, Cond, SDValue());
18141         return Cond;
18142       }
18143
18144       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18145       // for any integer data type, including i8/i16.
18146       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18147         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18148                            DAG.getConstant(CC, MVT::i8), Cond);
18149
18150         // Zero extend the condition if needed.
18151         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18152                            FalseC->getValueType(0), Cond);
18153         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18154                            SDValue(FalseC, 0));
18155
18156         if (N->getNumValues() == 2)  // Dead flag value?
18157           return DCI.CombineTo(N, Cond, SDValue());
18158         return Cond;
18159       }
18160
18161       // Optimize cases that will turn into an LEA instruction.  This requires
18162       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18163       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18164         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18165         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18166
18167         bool isFastMultiplier = false;
18168         if (Diff < 10) {
18169           switch ((unsigned char)Diff) {
18170           default: break;
18171           case 1:  // result = add base, cond
18172           case 2:  // result = lea base(    , cond*2)
18173           case 3:  // result = lea base(cond, cond*2)
18174           case 4:  // result = lea base(    , cond*4)
18175           case 5:  // result = lea base(cond, cond*4)
18176           case 8:  // result = lea base(    , cond*8)
18177           case 9:  // result = lea base(cond, cond*8)
18178             isFastMultiplier = true;
18179             break;
18180           }
18181         }
18182
18183         if (isFastMultiplier) {
18184           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18185           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18186                              DAG.getConstant(CC, MVT::i8), Cond);
18187           // Zero extend the condition if needed.
18188           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18189                              Cond);
18190           // Scale the condition by the difference.
18191           if (Diff != 1)
18192             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18193                                DAG.getConstant(Diff, Cond.getValueType()));
18194
18195           // Add the base if non-zero.
18196           if (FalseC->getAPIntValue() != 0)
18197             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18198                                SDValue(FalseC, 0));
18199           if (N->getNumValues() == 2)  // Dead flag value?
18200             return DCI.CombineTo(N, Cond, SDValue());
18201           return Cond;
18202         }
18203       }
18204     }
18205   }
18206
18207   // Handle these cases:
18208   //   (select (x != c), e, c) -> select (x != c), e, x),
18209   //   (select (x == c), c, e) -> select (x == c), x, e)
18210   // where the c is an integer constant, and the "select" is the combination
18211   // of CMOV and CMP.
18212   //
18213   // The rationale for this change is that the conditional-move from a constant
18214   // needs two instructions, however, conditional-move from a register needs
18215   // only one instruction.
18216   //
18217   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18218   //  some instruction-combining opportunities. This opt needs to be
18219   //  postponed as late as possible.
18220   //
18221   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18222     // the DCI.xxxx conditions are provided to postpone the optimization as
18223     // late as possible.
18224
18225     ConstantSDNode *CmpAgainst = nullptr;
18226     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18227         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18228         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18229
18230       if (CC == X86::COND_NE &&
18231           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18232         CC = X86::GetOppositeBranchCondition(CC);
18233         std::swap(TrueOp, FalseOp);
18234       }
18235
18236       if (CC == X86::COND_E &&
18237           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18238         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18239                           DAG.getConstant(CC, MVT::i8), Cond };
18240         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18241       }
18242     }
18243   }
18244
18245   return SDValue();
18246 }
18247
18248 /// PerformMulCombine - Optimize a single multiply with constant into two
18249 /// in order to implement it with two cheaper instructions, e.g.
18250 /// LEA + SHL, LEA + LEA.
18251 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18252                                  TargetLowering::DAGCombinerInfo &DCI) {
18253   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18254     return SDValue();
18255
18256   EVT VT = N->getValueType(0);
18257   if (VT != MVT::i64)
18258     return SDValue();
18259
18260   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18261   if (!C)
18262     return SDValue();
18263   uint64_t MulAmt = C->getZExtValue();
18264   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18265     return SDValue();
18266
18267   uint64_t MulAmt1 = 0;
18268   uint64_t MulAmt2 = 0;
18269   if ((MulAmt % 9) == 0) {
18270     MulAmt1 = 9;
18271     MulAmt2 = MulAmt / 9;
18272   } else if ((MulAmt % 5) == 0) {
18273     MulAmt1 = 5;
18274     MulAmt2 = MulAmt / 5;
18275   } else if ((MulAmt % 3) == 0) {
18276     MulAmt1 = 3;
18277     MulAmt2 = MulAmt / 3;
18278   }
18279   if (MulAmt2 &&
18280       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18281     SDLoc DL(N);
18282
18283     if (isPowerOf2_64(MulAmt2) &&
18284         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18285       // If second multiplifer is pow2, issue it first. We want the multiply by
18286       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18287       // is an add.
18288       std::swap(MulAmt1, MulAmt2);
18289
18290     SDValue NewMul;
18291     if (isPowerOf2_64(MulAmt1))
18292       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18293                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18294     else
18295       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18296                            DAG.getConstant(MulAmt1, VT));
18297
18298     if (isPowerOf2_64(MulAmt2))
18299       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18300                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18301     else
18302       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18303                            DAG.getConstant(MulAmt2, VT));
18304
18305     // Do not add new nodes to DAG combiner worklist.
18306     DCI.CombineTo(N, NewMul, false);
18307   }
18308   return SDValue();
18309 }
18310
18311 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18312   SDValue N0 = N->getOperand(0);
18313   SDValue N1 = N->getOperand(1);
18314   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18315   EVT VT = N0.getValueType();
18316
18317   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18318   // since the result of setcc_c is all zero's or all ones.
18319   if (VT.isInteger() && !VT.isVector() &&
18320       N1C && N0.getOpcode() == ISD::AND &&
18321       N0.getOperand(1).getOpcode() == ISD::Constant) {
18322     SDValue N00 = N0.getOperand(0);
18323     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18324         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18325           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18326          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18327       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18328       APInt ShAmt = N1C->getAPIntValue();
18329       Mask = Mask.shl(ShAmt);
18330       if (Mask != 0)
18331         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18332                            N00, DAG.getConstant(Mask, VT));
18333     }
18334   }
18335
18336   // Hardware support for vector shifts is sparse which makes us scalarize the
18337   // vector operations in many cases. Also, on sandybridge ADD is faster than
18338   // shl.
18339   // (shl V, 1) -> add V,V
18340   if (isSplatVector(N1.getNode())) {
18341     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18342     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18343     // We shift all of the values by one. In many cases we do not have
18344     // hardware support for this operation. This is better expressed as an ADD
18345     // of two values.
18346     if (N1C && (1 == N1C->getZExtValue())) {
18347       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18348     }
18349   }
18350
18351   return SDValue();
18352 }
18353
18354 /// \brief Returns a vector of 0s if the node in input is a vector logical
18355 /// shift by a constant amount which is known to be bigger than or equal
18356 /// to the vector element size in bits.
18357 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18358                                       const X86Subtarget *Subtarget) {
18359   EVT VT = N->getValueType(0);
18360
18361   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18362       (!Subtarget->hasInt256() ||
18363        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18364     return SDValue();
18365
18366   SDValue Amt = N->getOperand(1);
18367   SDLoc DL(N);
18368   if (isSplatVector(Amt.getNode())) {
18369     SDValue SclrAmt = Amt->getOperand(0);
18370     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18371       APInt ShiftAmt = C->getAPIntValue();
18372       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18373
18374       // SSE2/AVX2 logical shifts always return a vector of 0s
18375       // if the shift amount is bigger than or equal to
18376       // the element size. The constant shift amount will be
18377       // encoded as a 8-bit immediate.
18378       if (ShiftAmt.trunc(8).uge(MaxAmount))
18379         return getZeroVector(VT, Subtarget, DAG, DL);
18380     }
18381   }
18382
18383   return SDValue();
18384 }
18385
18386 /// PerformShiftCombine - Combine shifts.
18387 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18388                                    TargetLowering::DAGCombinerInfo &DCI,
18389                                    const X86Subtarget *Subtarget) {
18390   if (N->getOpcode() == ISD::SHL) {
18391     SDValue V = PerformSHLCombine(N, DAG);
18392     if (V.getNode()) return V;
18393   }
18394
18395   if (N->getOpcode() != ISD::SRA) {
18396     // Try to fold this logical shift into a zero vector.
18397     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18398     if (V.getNode()) return V;
18399   }
18400
18401   return SDValue();
18402 }
18403
18404 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18405 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18406 // and friends.  Likewise for OR -> CMPNEQSS.
18407 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18408                             TargetLowering::DAGCombinerInfo &DCI,
18409                             const X86Subtarget *Subtarget) {
18410   unsigned opcode;
18411
18412   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18413   // we're requiring SSE2 for both.
18414   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18415     SDValue N0 = N->getOperand(0);
18416     SDValue N1 = N->getOperand(1);
18417     SDValue CMP0 = N0->getOperand(1);
18418     SDValue CMP1 = N1->getOperand(1);
18419     SDLoc DL(N);
18420
18421     // The SETCCs should both refer to the same CMP.
18422     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18423       return SDValue();
18424
18425     SDValue CMP00 = CMP0->getOperand(0);
18426     SDValue CMP01 = CMP0->getOperand(1);
18427     EVT     VT    = CMP00.getValueType();
18428
18429     if (VT == MVT::f32 || VT == MVT::f64) {
18430       bool ExpectingFlags = false;
18431       // Check for any users that want flags:
18432       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18433            !ExpectingFlags && UI != UE; ++UI)
18434         switch (UI->getOpcode()) {
18435         default:
18436         case ISD::BR_CC:
18437         case ISD::BRCOND:
18438         case ISD::SELECT:
18439           ExpectingFlags = true;
18440           break;
18441         case ISD::CopyToReg:
18442         case ISD::SIGN_EXTEND:
18443         case ISD::ZERO_EXTEND:
18444         case ISD::ANY_EXTEND:
18445           break;
18446         }
18447
18448       if (!ExpectingFlags) {
18449         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18450         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18451
18452         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18453           X86::CondCode tmp = cc0;
18454           cc0 = cc1;
18455           cc1 = tmp;
18456         }
18457
18458         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18459             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18460           // FIXME: need symbolic constants for these magic numbers.
18461           // See X86ATTInstPrinter.cpp:printSSECC().
18462           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18463           if (Subtarget->hasAVX512()) {
18464             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18465                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18466             if (N->getValueType(0) != MVT::i1)
18467               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18468                                  FSetCC);
18469             return FSetCC;
18470           }
18471           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18472                                               CMP00.getValueType(), CMP00, CMP01,
18473                                               DAG.getConstant(x86cc, MVT::i8));
18474
18475           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18476           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18477
18478           if (is64BitFP && !Subtarget->is64Bit()) {
18479             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18480             // 64-bit integer, since that's not a legal type. Since
18481             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18482             // bits, but can do this little dance to extract the lowest 32 bits
18483             // and work with those going forward.
18484             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18485                                            OnesOrZeroesF);
18486             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18487                                            Vector64);
18488             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18489                                         Vector32, DAG.getIntPtrConstant(0));
18490             IntVT = MVT::i32;
18491           }
18492
18493           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18494           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18495                                       DAG.getConstant(1, IntVT));
18496           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18497           return OneBitOfTruth;
18498         }
18499       }
18500     }
18501   }
18502   return SDValue();
18503 }
18504
18505 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18506 /// so it can be folded inside ANDNP.
18507 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18508   EVT VT = N->getValueType(0);
18509
18510   // Match direct AllOnes for 128 and 256-bit vectors
18511   if (ISD::isBuildVectorAllOnes(N))
18512     return true;
18513
18514   // Look through a bit convert.
18515   if (N->getOpcode() == ISD::BITCAST)
18516     N = N->getOperand(0).getNode();
18517
18518   // Sometimes the operand may come from a insert_subvector building a 256-bit
18519   // allones vector
18520   if (VT.is256BitVector() &&
18521       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18522     SDValue V1 = N->getOperand(0);
18523     SDValue V2 = N->getOperand(1);
18524
18525     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18526         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18527         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18528         ISD::isBuildVectorAllOnes(V2.getNode()))
18529       return true;
18530   }
18531
18532   return false;
18533 }
18534
18535 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18536 // register. In most cases we actually compare or select YMM-sized registers
18537 // and mixing the two types creates horrible code. This method optimizes
18538 // some of the transition sequences.
18539 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18540                                  TargetLowering::DAGCombinerInfo &DCI,
18541                                  const X86Subtarget *Subtarget) {
18542   EVT VT = N->getValueType(0);
18543   if (!VT.is256BitVector())
18544     return SDValue();
18545
18546   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18547           N->getOpcode() == ISD::ZERO_EXTEND ||
18548           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18549
18550   SDValue Narrow = N->getOperand(0);
18551   EVT NarrowVT = Narrow->getValueType(0);
18552   if (!NarrowVT.is128BitVector())
18553     return SDValue();
18554
18555   if (Narrow->getOpcode() != ISD::XOR &&
18556       Narrow->getOpcode() != ISD::AND &&
18557       Narrow->getOpcode() != ISD::OR)
18558     return SDValue();
18559
18560   SDValue N0  = Narrow->getOperand(0);
18561   SDValue N1  = Narrow->getOperand(1);
18562   SDLoc DL(Narrow);
18563
18564   // The Left side has to be a trunc.
18565   if (N0.getOpcode() != ISD::TRUNCATE)
18566     return SDValue();
18567
18568   // The type of the truncated inputs.
18569   EVT WideVT = N0->getOperand(0)->getValueType(0);
18570   if (WideVT != VT)
18571     return SDValue();
18572
18573   // The right side has to be a 'trunc' or a constant vector.
18574   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18575   bool RHSConst = (isSplatVector(N1.getNode()) &&
18576                    isa<ConstantSDNode>(N1->getOperand(0)));
18577   if (!RHSTrunc && !RHSConst)
18578     return SDValue();
18579
18580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18581
18582   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18583     return SDValue();
18584
18585   // Set N0 and N1 to hold the inputs to the new wide operation.
18586   N0 = N0->getOperand(0);
18587   if (RHSConst) {
18588     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18589                      N1->getOperand(0));
18590     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18591     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18592   } else if (RHSTrunc) {
18593     N1 = N1->getOperand(0);
18594   }
18595
18596   // Generate the wide operation.
18597   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18598   unsigned Opcode = N->getOpcode();
18599   switch (Opcode) {
18600   case ISD::ANY_EXTEND:
18601     return Op;
18602   case ISD::ZERO_EXTEND: {
18603     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18604     APInt Mask = APInt::getAllOnesValue(InBits);
18605     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18606     return DAG.getNode(ISD::AND, DL, VT,
18607                        Op, DAG.getConstant(Mask, VT));
18608   }
18609   case ISD::SIGN_EXTEND:
18610     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18611                        Op, DAG.getValueType(NarrowVT));
18612   default:
18613     llvm_unreachable("Unexpected opcode");
18614   }
18615 }
18616
18617 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18618                                  TargetLowering::DAGCombinerInfo &DCI,
18619                                  const X86Subtarget *Subtarget) {
18620   EVT VT = N->getValueType(0);
18621   if (DCI.isBeforeLegalizeOps())
18622     return SDValue();
18623
18624   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18625   if (R.getNode())
18626     return R;
18627
18628   // Create BEXTR instructions
18629   // BEXTR is ((X >> imm) & (2**size-1))
18630   if (VT == MVT::i32 || VT == MVT::i64) {
18631     SDValue N0 = N->getOperand(0);
18632     SDValue N1 = N->getOperand(1);
18633     SDLoc DL(N);
18634
18635     // Check for BEXTR.
18636     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18637         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18638       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18639       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18640       if (MaskNode && ShiftNode) {
18641         uint64_t Mask = MaskNode->getZExtValue();
18642         uint64_t Shift = ShiftNode->getZExtValue();
18643         if (isMask_64(Mask)) {
18644           uint64_t MaskSize = CountPopulation_64(Mask);
18645           if (Shift + MaskSize <= VT.getSizeInBits())
18646             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18647                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18648         }
18649       }
18650     } // BEXTR
18651
18652     return SDValue();
18653   }
18654
18655   // Want to form ANDNP nodes:
18656   // 1) In the hopes of then easily combining them with OR and AND nodes
18657   //    to form PBLEND/PSIGN.
18658   // 2) To match ANDN packed intrinsics
18659   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18660     return SDValue();
18661
18662   SDValue N0 = N->getOperand(0);
18663   SDValue N1 = N->getOperand(1);
18664   SDLoc DL(N);
18665
18666   // Check LHS for vnot
18667   if (N0.getOpcode() == ISD::XOR &&
18668       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18669       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18670     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18671
18672   // Check RHS for vnot
18673   if (N1.getOpcode() == ISD::XOR &&
18674       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18675       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18676     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18677
18678   return SDValue();
18679 }
18680
18681 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18682                                 TargetLowering::DAGCombinerInfo &DCI,
18683                                 const X86Subtarget *Subtarget) {
18684   if (DCI.isBeforeLegalizeOps())
18685     return SDValue();
18686
18687   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18688   if (R.getNode())
18689     return R;
18690
18691   SDValue N0 = N->getOperand(0);
18692   SDValue N1 = N->getOperand(1);
18693   EVT VT = N->getValueType(0);
18694
18695   // look for psign/blend
18696   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18697     if (!Subtarget->hasSSSE3() ||
18698         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18699       return SDValue();
18700
18701     // Canonicalize pandn to RHS
18702     if (N0.getOpcode() == X86ISD::ANDNP)
18703       std::swap(N0, N1);
18704     // or (and (m, y), (pandn m, x))
18705     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18706       SDValue Mask = N1.getOperand(0);
18707       SDValue X    = N1.getOperand(1);
18708       SDValue Y;
18709       if (N0.getOperand(0) == Mask)
18710         Y = N0.getOperand(1);
18711       if (N0.getOperand(1) == Mask)
18712         Y = N0.getOperand(0);
18713
18714       // Check to see if the mask appeared in both the AND and ANDNP and
18715       if (!Y.getNode())
18716         return SDValue();
18717
18718       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18719       // Look through mask bitcast.
18720       if (Mask.getOpcode() == ISD::BITCAST)
18721         Mask = Mask.getOperand(0);
18722       if (X.getOpcode() == ISD::BITCAST)
18723         X = X.getOperand(0);
18724       if (Y.getOpcode() == ISD::BITCAST)
18725         Y = Y.getOperand(0);
18726
18727       EVT MaskVT = Mask.getValueType();
18728
18729       // Validate that the Mask operand is a vector sra node.
18730       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18731       // there is no psrai.b
18732       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18733       unsigned SraAmt = ~0;
18734       if (Mask.getOpcode() == ISD::SRA) {
18735         SDValue Amt = Mask.getOperand(1);
18736         if (isSplatVector(Amt.getNode())) {
18737           SDValue SclrAmt = Amt->getOperand(0);
18738           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18739             SraAmt = C->getZExtValue();
18740         }
18741       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18742         SDValue SraC = Mask.getOperand(1);
18743         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18744       }
18745       if ((SraAmt + 1) != EltBits)
18746         return SDValue();
18747
18748       SDLoc DL(N);
18749
18750       // Now we know we at least have a plendvb with the mask val.  See if
18751       // we can form a psignb/w/d.
18752       // psign = x.type == y.type == mask.type && y = sub(0, x);
18753       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18754           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18755           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18756         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18757                "Unsupported VT for PSIGN");
18758         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18759         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18760       }
18761       // PBLENDVB only available on SSE 4.1
18762       if (!Subtarget->hasSSE41())
18763         return SDValue();
18764
18765       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18766
18767       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18768       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18769       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18770       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18771       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18772     }
18773   }
18774
18775   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18776     return SDValue();
18777
18778   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18779   MachineFunction &MF = DAG.getMachineFunction();
18780   bool OptForSize = MF.getFunction()->getAttributes().
18781     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18782
18783   // SHLD/SHRD instructions have lower register pressure, but on some
18784   // platforms they have higher latency than the equivalent
18785   // series of shifts/or that would otherwise be generated.
18786   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18787   // have higher latencies and we are not optimizing for size.
18788   if (!OptForSize && Subtarget->isSHLDSlow())
18789     return SDValue();
18790
18791   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18792     std::swap(N0, N1);
18793   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18794     return SDValue();
18795   if (!N0.hasOneUse() || !N1.hasOneUse())
18796     return SDValue();
18797
18798   SDValue ShAmt0 = N0.getOperand(1);
18799   if (ShAmt0.getValueType() != MVT::i8)
18800     return SDValue();
18801   SDValue ShAmt1 = N1.getOperand(1);
18802   if (ShAmt1.getValueType() != MVT::i8)
18803     return SDValue();
18804   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18805     ShAmt0 = ShAmt0.getOperand(0);
18806   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18807     ShAmt1 = ShAmt1.getOperand(0);
18808
18809   SDLoc DL(N);
18810   unsigned Opc = X86ISD::SHLD;
18811   SDValue Op0 = N0.getOperand(0);
18812   SDValue Op1 = N1.getOperand(0);
18813   if (ShAmt0.getOpcode() == ISD::SUB) {
18814     Opc = X86ISD::SHRD;
18815     std::swap(Op0, Op1);
18816     std::swap(ShAmt0, ShAmt1);
18817   }
18818
18819   unsigned Bits = VT.getSizeInBits();
18820   if (ShAmt1.getOpcode() == ISD::SUB) {
18821     SDValue Sum = ShAmt1.getOperand(0);
18822     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18823       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18824       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18825         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18826       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18827         return DAG.getNode(Opc, DL, VT,
18828                            Op0, Op1,
18829                            DAG.getNode(ISD::TRUNCATE, DL,
18830                                        MVT::i8, ShAmt0));
18831     }
18832   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18833     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18834     if (ShAmt0C &&
18835         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18836       return DAG.getNode(Opc, DL, VT,
18837                          N0.getOperand(0), N1.getOperand(0),
18838                          DAG.getNode(ISD::TRUNCATE, DL,
18839                                        MVT::i8, ShAmt0));
18840   }
18841
18842   return SDValue();
18843 }
18844
18845 // Generate NEG and CMOV for integer abs.
18846 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18847   EVT VT = N->getValueType(0);
18848
18849   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18850   // 8-bit integer abs to NEG and CMOV.
18851   if (VT.isInteger() && VT.getSizeInBits() == 8)
18852     return SDValue();
18853
18854   SDValue N0 = N->getOperand(0);
18855   SDValue N1 = N->getOperand(1);
18856   SDLoc DL(N);
18857
18858   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18859   // and change it to SUB and CMOV.
18860   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18861       N0.getOpcode() == ISD::ADD &&
18862       N0.getOperand(1) == N1 &&
18863       N1.getOpcode() == ISD::SRA &&
18864       N1.getOperand(0) == N0.getOperand(0))
18865     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18866       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18867         // Generate SUB & CMOV.
18868         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18869                                   DAG.getConstant(0, VT), N0.getOperand(0));
18870
18871         SDValue Ops[] = { N0.getOperand(0), Neg,
18872                           DAG.getConstant(X86::COND_GE, MVT::i8),
18873                           SDValue(Neg.getNode(), 1) };
18874         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18875       }
18876   return SDValue();
18877 }
18878
18879 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18880 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18881                                  TargetLowering::DAGCombinerInfo &DCI,
18882                                  const X86Subtarget *Subtarget) {
18883   if (DCI.isBeforeLegalizeOps())
18884     return SDValue();
18885
18886   if (Subtarget->hasCMov()) {
18887     SDValue RV = performIntegerAbsCombine(N, DAG);
18888     if (RV.getNode())
18889       return RV;
18890   }
18891
18892   return SDValue();
18893 }
18894
18895 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18896 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18897                                   TargetLowering::DAGCombinerInfo &DCI,
18898                                   const X86Subtarget *Subtarget) {
18899   LoadSDNode *Ld = cast<LoadSDNode>(N);
18900   EVT RegVT = Ld->getValueType(0);
18901   EVT MemVT = Ld->getMemoryVT();
18902   SDLoc dl(Ld);
18903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18904   unsigned RegSz = RegVT.getSizeInBits();
18905
18906   // On Sandybridge unaligned 256bit loads are inefficient.
18907   ISD::LoadExtType Ext = Ld->getExtensionType();
18908   unsigned Alignment = Ld->getAlignment();
18909   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18910   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18911       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18912     unsigned NumElems = RegVT.getVectorNumElements();
18913     if (NumElems < 2)
18914       return SDValue();
18915
18916     SDValue Ptr = Ld->getBasePtr();
18917     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18918
18919     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18920                                   NumElems/2);
18921     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18922                                 Ld->getPointerInfo(), Ld->isVolatile(),
18923                                 Ld->isNonTemporal(), Ld->isInvariant(),
18924                                 Alignment);
18925     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18926     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18927                                 Ld->getPointerInfo(), Ld->isVolatile(),
18928                                 Ld->isNonTemporal(), Ld->isInvariant(),
18929                                 std::min(16U, Alignment));
18930     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18931                              Load1.getValue(1),
18932                              Load2.getValue(1));
18933
18934     SDValue NewVec = DAG.getUNDEF(RegVT);
18935     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18936     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18937     return DCI.CombineTo(N, NewVec, TF, true);
18938   }
18939
18940   // If this is a vector EXT Load then attempt to optimize it using a
18941   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18942   // expansion is still better than scalar code.
18943   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18944   // emit a shuffle and a arithmetic shift.
18945   // TODO: It is possible to support ZExt by zeroing the undef values
18946   // during the shuffle phase or after the shuffle.
18947   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18948       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18949     assert(MemVT != RegVT && "Cannot extend to the same type");
18950     assert(MemVT.isVector() && "Must load a vector from memory");
18951
18952     unsigned NumElems = RegVT.getVectorNumElements();
18953     unsigned MemSz = MemVT.getSizeInBits();
18954     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18955
18956     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18957       return SDValue();
18958
18959     // All sizes must be a power of two.
18960     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18961       return SDValue();
18962
18963     // Attempt to load the original value using scalar loads.
18964     // Find the largest scalar type that divides the total loaded size.
18965     MVT SclrLoadTy = MVT::i8;
18966     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18967          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18968       MVT Tp = (MVT::SimpleValueType)tp;
18969       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18970         SclrLoadTy = Tp;
18971       }
18972     }
18973
18974     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18975     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18976         (64 <= MemSz))
18977       SclrLoadTy = MVT::f64;
18978
18979     // Calculate the number of scalar loads that we need to perform
18980     // in order to load our vector from memory.
18981     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18982     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18983       return SDValue();
18984
18985     unsigned loadRegZize = RegSz;
18986     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18987       loadRegZize /= 2;
18988
18989     // Represent our vector as a sequence of elements which are the
18990     // largest scalar that we can load.
18991     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18992       loadRegZize/SclrLoadTy.getSizeInBits());
18993
18994     // Represent the data using the same element type that is stored in
18995     // memory. In practice, we ''widen'' MemVT.
18996     EVT WideVecVT =
18997           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18998                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18999
19000     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19001       "Invalid vector type");
19002
19003     // We can't shuffle using an illegal type.
19004     if (!TLI.isTypeLegal(WideVecVT))
19005       return SDValue();
19006
19007     SmallVector<SDValue, 8> Chains;
19008     SDValue Ptr = Ld->getBasePtr();
19009     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19010                                         TLI.getPointerTy());
19011     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19012
19013     for (unsigned i = 0; i < NumLoads; ++i) {
19014       // Perform a single load.
19015       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19016                                        Ptr, Ld->getPointerInfo(),
19017                                        Ld->isVolatile(), Ld->isNonTemporal(),
19018                                        Ld->isInvariant(), Ld->getAlignment());
19019       Chains.push_back(ScalarLoad.getValue(1));
19020       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19021       // another round of DAGCombining.
19022       if (i == 0)
19023         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19024       else
19025         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19026                           ScalarLoad, DAG.getIntPtrConstant(i));
19027
19028       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19029     }
19030
19031     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19032
19033     // Bitcast the loaded value to a vector of the original element type, in
19034     // the size of the target vector type.
19035     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19036     unsigned SizeRatio = RegSz/MemSz;
19037
19038     if (Ext == ISD::SEXTLOAD) {
19039       // If we have SSE4.1 we can directly emit a VSEXT node.
19040       if (Subtarget->hasSSE41()) {
19041         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19042         return DCI.CombineTo(N, Sext, TF, true);
19043       }
19044
19045       // Otherwise we'll shuffle the small elements in the high bits of the
19046       // larger type and perform an arithmetic shift. If the shift is not legal
19047       // it's better to scalarize.
19048       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19049         return SDValue();
19050
19051       // Redistribute the loaded elements into the different locations.
19052       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19053       for (unsigned i = 0; i != NumElems; ++i)
19054         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19055
19056       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19057                                            DAG.getUNDEF(WideVecVT),
19058                                            &ShuffleVec[0]);
19059
19060       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19061
19062       // Build the arithmetic shift.
19063       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19064                      MemVT.getVectorElementType().getSizeInBits();
19065       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19066                           DAG.getConstant(Amt, RegVT));
19067
19068       return DCI.CombineTo(N, Shuff, TF, true);
19069     }
19070
19071     // Redistribute the loaded elements into the different locations.
19072     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19073     for (unsigned i = 0; i != NumElems; ++i)
19074       ShuffleVec[i*SizeRatio] = i;
19075
19076     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19077                                          DAG.getUNDEF(WideVecVT),
19078                                          &ShuffleVec[0]);
19079
19080     // Bitcast to the requested type.
19081     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19082     // Replace the original load with the new sequence
19083     // and return the new chain.
19084     return DCI.CombineTo(N, Shuff, TF, true);
19085   }
19086
19087   return SDValue();
19088 }
19089
19090 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19091 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19092                                    const X86Subtarget *Subtarget) {
19093   StoreSDNode *St = cast<StoreSDNode>(N);
19094   EVT VT = St->getValue().getValueType();
19095   EVT StVT = St->getMemoryVT();
19096   SDLoc dl(St);
19097   SDValue StoredVal = St->getOperand(1);
19098   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19099
19100   // If we are saving a concatenation of two XMM registers, perform two stores.
19101   // On Sandy Bridge, 256-bit memory operations are executed by two
19102   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19103   // memory  operation.
19104   unsigned Alignment = St->getAlignment();
19105   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19106   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19107       StVT == VT && !IsAligned) {
19108     unsigned NumElems = VT.getVectorNumElements();
19109     if (NumElems < 2)
19110       return SDValue();
19111
19112     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19113     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19114
19115     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19116     SDValue Ptr0 = St->getBasePtr();
19117     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19118
19119     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19120                                 St->getPointerInfo(), St->isVolatile(),
19121                                 St->isNonTemporal(), Alignment);
19122     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19123                                 St->getPointerInfo(), St->isVolatile(),
19124                                 St->isNonTemporal(),
19125                                 std::min(16U, Alignment));
19126     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19127   }
19128
19129   // Optimize trunc store (of multiple scalars) to shuffle and store.
19130   // First, pack all of the elements in one place. Next, store to memory
19131   // in fewer chunks.
19132   if (St->isTruncatingStore() && VT.isVector()) {
19133     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19134     unsigned NumElems = VT.getVectorNumElements();
19135     assert(StVT != VT && "Cannot truncate to the same type");
19136     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19137     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19138
19139     // From, To sizes and ElemCount must be pow of two
19140     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19141     // We are going to use the original vector elt for storing.
19142     // Accumulated smaller vector elements must be a multiple of the store size.
19143     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19144
19145     unsigned SizeRatio  = FromSz / ToSz;
19146
19147     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19148
19149     // Create a type on which we perform the shuffle
19150     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19151             StVT.getScalarType(), NumElems*SizeRatio);
19152
19153     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19154
19155     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19156     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19157     for (unsigned i = 0; i != NumElems; ++i)
19158       ShuffleVec[i] = i * SizeRatio;
19159
19160     // Can't shuffle using an illegal type.
19161     if (!TLI.isTypeLegal(WideVecVT))
19162       return SDValue();
19163
19164     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19165                                          DAG.getUNDEF(WideVecVT),
19166                                          &ShuffleVec[0]);
19167     // At this point all of the data is stored at the bottom of the
19168     // register. We now need to save it to mem.
19169
19170     // Find the largest store unit
19171     MVT StoreType = MVT::i8;
19172     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19173          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19174       MVT Tp = (MVT::SimpleValueType)tp;
19175       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19176         StoreType = Tp;
19177     }
19178
19179     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19180     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19181         (64 <= NumElems * ToSz))
19182       StoreType = MVT::f64;
19183
19184     // Bitcast the original vector into a vector of store-size units
19185     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19186             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19187     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19188     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19189     SmallVector<SDValue, 8> Chains;
19190     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19191                                         TLI.getPointerTy());
19192     SDValue Ptr = St->getBasePtr();
19193
19194     // Perform one or more big stores into memory.
19195     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19196       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19197                                    StoreType, ShuffWide,
19198                                    DAG.getIntPtrConstant(i));
19199       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19200                                 St->getPointerInfo(), St->isVolatile(),
19201                                 St->isNonTemporal(), St->getAlignment());
19202       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19203       Chains.push_back(Ch);
19204     }
19205
19206     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19207   }
19208
19209   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19210   // the FP state in cases where an emms may be missing.
19211   // A preferable solution to the general problem is to figure out the right
19212   // places to insert EMMS.  This qualifies as a quick hack.
19213
19214   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19215   if (VT.getSizeInBits() != 64)
19216     return SDValue();
19217
19218   const Function *F = DAG.getMachineFunction().getFunction();
19219   bool NoImplicitFloatOps = F->getAttributes().
19220     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19221   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19222                      && Subtarget->hasSSE2();
19223   if ((VT.isVector() ||
19224        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19225       isa<LoadSDNode>(St->getValue()) &&
19226       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19227       St->getChain().hasOneUse() && !St->isVolatile()) {
19228     SDNode* LdVal = St->getValue().getNode();
19229     LoadSDNode *Ld = nullptr;
19230     int TokenFactorIndex = -1;
19231     SmallVector<SDValue, 8> Ops;
19232     SDNode* ChainVal = St->getChain().getNode();
19233     // Must be a store of a load.  We currently handle two cases:  the load
19234     // is a direct child, and it's under an intervening TokenFactor.  It is
19235     // possible to dig deeper under nested TokenFactors.
19236     if (ChainVal == LdVal)
19237       Ld = cast<LoadSDNode>(St->getChain());
19238     else if (St->getValue().hasOneUse() &&
19239              ChainVal->getOpcode() == ISD::TokenFactor) {
19240       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19241         if (ChainVal->getOperand(i).getNode() == LdVal) {
19242           TokenFactorIndex = i;
19243           Ld = cast<LoadSDNode>(St->getValue());
19244         } else
19245           Ops.push_back(ChainVal->getOperand(i));
19246       }
19247     }
19248
19249     if (!Ld || !ISD::isNormalLoad(Ld))
19250       return SDValue();
19251
19252     // If this is not the MMX case, i.e. we are just turning i64 load/store
19253     // into f64 load/store, avoid the transformation if there are multiple
19254     // uses of the loaded value.
19255     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19256       return SDValue();
19257
19258     SDLoc LdDL(Ld);
19259     SDLoc StDL(N);
19260     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19261     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19262     // pair instead.
19263     if (Subtarget->is64Bit() || F64IsLegal) {
19264       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19265       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19266                                   Ld->getPointerInfo(), Ld->isVolatile(),
19267                                   Ld->isNonTemporal(), Ld->isInvariant(),
19268                                   Ld->getAlignment());
19269       SDValue NewChain = NewLd.getValue(1);
19270       if (TokenFactorIndex != -1) {
19271         Ops.push_back(NewChain);
19272         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19273       }
19274       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19275                           St->getPointerInfo(),
19276                           St->isVolatile(), St->isNonTemporal(),
19277                           St->getAlignment());
19278     }
19279
19280     // Otherwise, lower to two pairs of 32-bit loads / stores.
19281     SDValue LoAddr = Ld->getBasePtr();
19282     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19283                                  DAG.getConstant(4, MVT::i32));
19284
19285     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19286                                Ld->getPointerInfo(),
19287                                Ld->isVolatile(), Ld->isNonTemporal(),
19288                                Ld->isInvariant(), Ld->getAlignment());
19289     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19290                                Ld->getPointerInfo().getWithOffset(4),
19291                                Ld->isVolatile(), Ld->isNonTemporal(),
19292                                Ld->isInvariant(),
19293                                MinAlign(Ld->getAlignment(), 4));
19294
19295     SDValue NewChain = LoLd.getValue(1);
19296     if (TokenFactorIndex != -1) {
19297       Ops.push_back(LoLd);
19298       Ops.push_back(HiLd);
19299       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19300     }
19301
19302     LoAddr = St->getBasePtr();
19303     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19304                          DAG.getConstant(4, MVT::i32));
19305
19306     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19307                                 St->getPointerInfo(),
19308                                 St->isVolatile(), St->isNonTemporal(),
19309                                 St->getAlignment());
19310     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19311                                 St->getPointerInfo().getWithOffset(4),
19312                                 St->isVolatile(),
19313                                 St->isNonTemporal(),
19314                                 MinAlign(St->getAlignment(), 4));
19315     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19316   }
19317   return SDValue();
19318 }
19319
19320 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19321 /// and return the operands for the horizontal operation in LHS and RHS.  A
19322 /// horizontal operation performs the binary operation on successive elements
19323 /// of its first operand, then on successive elements of its second operand,
19324 /// returning the resulting values in a vector.  For example, if
19325 ///   A = < float a0, float a1, float a2, float a3 >
19326 /// and
19327 ///   B = < float b0, float b1, float b2, float b3 >
19328 /// then the result of doing a horizontal operation on A and B is
19329 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19330 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19331 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19332 /// set to A, RHS to B, and the routine returns 'true'.
19333 /// Note that the binary operation should have the property that if one of the
19334 /// operands is UNDEF then the result is UNDEF.
19335 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19336   // Look for the following pattern: if
19337   //   A = < float a0, float a1, float a2, float a3 >
19338   //   B = < float b0, float b1, float b2, float b3 >
19339   // and
19340   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19341   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19342   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19343   // which is A horizontal-op B.
19344
19345   // At least one of the operands should be a vector shuffle.
19346   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19347       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19348     return false;
19349
19350   MVT VT = LHS.getSimpleValueType();
19351
19352   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19353          "Unsupported vector type for horizontal add/sub");
19354
19355   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19356   // operate independently on 128-bit lanes.
19357   unsigned NumElts = VT.getVectorNumElements();
19358   unsigned NumLanes = VT.getSizeInBits()/128;
19359   unsigned NumLaneElts = NumElts / NumLanes;
19360   assert((NumLaneElts % 2 == 0) &&
19361          "Vector type should have an even number of elements in each lane");
19362   unsigned HalfLaneElts = NumLaneElts/2;
19363
19364   // View LHS in the form
19365   //   LHS = VECTOR_SHUFFLE A, B, LMask
19366   // If LHS is not a shuffle then pretend it is the shuffle
19367   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19368   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19369   // type VT.
19370   SDValue A, B;
19371   SmallVector<int, 16> LMask(NumElts);
19372   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19373     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19374       A = LHS.getOperand(0);
19375     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19376       B = LHS.getOperand(1);
19377     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19378     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19379   } else {
19380     if (LHS.getOpcode() != ISD::UNDEF)
19381       A = LHS;
19382     for (unsigned i = 0; i != NumElts; ++i)
19383       LMask[i] = i;
19384   }
19385
19386   // Likewise, view RHS in the form
19387   //   RHS = VECTOR_SHUFFLE C, D, RMask
19388   SDValue C, D;
19389   SmallVector<int, 16> RMask(NumElts);
19390   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19391     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19392       C = RHS.getOperand(0);
19393     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19394       D = RHS.getOperand(1);
19395     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19396     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19397   } else {
19398     if (RHS.getOpcode() != ISD::UNDEF)
19399       C = RHS;
19400     for (unsigned i = 0; i != NumElts; ++i)
19401       RMask[i] = i;
19402   }
19403
19404   // Check that the shuffles are both shuffling the same vectors.
19405   if (!(A == C && B == D) && !(A == D && B == C))
19406     return false;
19407
19408   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19409   if (!A.getNode() && !B.getNode())
19410     return false;
19411
19412   // If A and B occur in reverse order in RHS, then "swap" them (which means
19413   // rewriting the mask).
19414   if (A != C)
19415     CommuteVectorShuffleMask(RMask, NumElts);
19416
19417   // At this point LHS and RHS are equivalent to
19418   //   LHS = VECTOR_SHUFFLE A, B, LMask
19419   //   RHS = VECTOR_SHUFFLE A, B, RMask
19420   // Check that the masks correspond to performing a horizontal operation.
19421   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19422     for (unsigned i = 0; i != NumLaneElts; ++i) {
19423       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19424
19425       // Ignore any UNDEF components.
19426       if (LIdx < 0 || RIdx < 0 ||
19427           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19428           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19429         continue;
19430
19431       // Check that successive elements are being operated on.  If not, this is
19432       // not a horizontal operation.
19433       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19434       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19435       if (!(LIdx == Index && RIdx == Index + 1) &&
19436           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19437         return false;
19438     }
19439   }
19440
19441   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19442   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19443   return true;
19444 }
19445
19446 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19447 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19448                                   const X86Subtarget *Subtarget) {
19449   EVT VT = N->getValueType(0);
19450   SDValue LHS = N->getOperand(0);
19451   SDValue RHS = N->getOperand(1);
19452
19453   // Try to synthesize horizontal adds from adds of shuffles.
19454   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19455        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19456       isHorizontalBinOp(LHS, RHS, true))
19457     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19458   return SDValue();
19459 }
19460
19461 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19462 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19463                                   const X86Subtarget *Subtarget) {
19464   EVT VT = N->getValueType(0);
19465   SDValue LHS = N->getOperand(0);
19466   SDValue RHS = N->getOperand(1);
19467
19468   // Try to synthesize horizontal subs from subs of shuffles.
19469   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19470        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19471       isHorizontalBinOp(LHS, RHS, false))
19472     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19473   return SDValue();
19474 }
19475
19476 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19477 /// X86ISD::FXOR nodes.
19478 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19479   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19480   // F[X]OR(0.0, x) -> x
19481   // F[X]OR(x, 0.0) -> x
19482   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19483     if (C->getValueAPF().isPosZero())
19484       return N->getOperand(1);
19485   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19486     if (C->getValueAPF().isPosZero())
19487       return N->getOperand(0);
19488   return SDValue();
19489 }
19490
19491 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19492 /// X86ISD::FMAX nodes.
19493 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19494   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19495
19496   // Only perform optimizations if UnsafeMath is used.
19497   if (!DAG.getTarget().Options.UnsafeFPMath)
19498     return SDValue();
19499
19500   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19501   // into FMINC and FMAXC, which are Commutative operations.
19502   unsigned NewOp = 0;
19503   switch (N->getOpcode()) {
19504     default: llvm_unreachable("unknown opcode");
19505     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19506     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19507   }
19508
19509   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19510                      N->getOperand(0), N->getOperand(1));
19511 }
19512
19513 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19514 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19515   // FAND(0.0, x) -> 0.0
19516   // FAND(x, 0.0) -> 0.0
19517   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19518     if (C->getValueAPF().isPosZero())
19519       return N->getOperand(0);
19520   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19521     if (C->getValueAPF().isPosZero())
19522       return N->getOperand(1);
19523   return SDValue();
19524 }
19525
19526 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19527 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19528   // FANDN(x, 0.0) -> 0.0
19529   // FANDN(0.0, x) -> x
19530   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19531     if (C->getValueAPF().isPosZero())
19532       return N->getOperand(1);
19533   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19534     if (C->getValueAPF().isPosZero())
19535       return N->getOperand(1);
19536   return SDValue();
19537 }
19538
19539 static SDValue PerformBTCombine(SDNode *N,
19540                                 SelectionDAG &DAG,
19541                                 TargetLowering::DAGCombinerInfo &DCI) {
19542   // BT ignores high bits in the bit index operand.
19543   SDValue Op1 = N->getOperand(1);
19544   if (Op1.hasOneUse()) {
19545     unsigned BitWidth = Op1.getValueSizeInBits();
19546     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19547     APInt KnownZero, KnownOne;
19548     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19549                                           !DCI.isBeforeLegalizeOps());
19550     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19551     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19552         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19553       DCI.CommitTargetLoweringOpt(TLO);
19554   }
19555   return SDValue();
19556 }
19557
19558 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19559   SDValue Op = N->getOperand(0);
19560   if (Op.getOpcode() == ISD::BITCAST)
19561     Op = Op.getOperand(0);
19562   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19563   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19564       VT.getVectorElementType().getSizeInBits() ==
19565       OpVT.getVectorElementType().getSizeInBits()) {
19566     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19567   }
19568   return SDValue();
19569 }
19570
19571 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19572                                                const X86Subtarget *Subtarget) {
19573   EVT VT = N->getValueType(0);
19574   if (!VT.isVector())
19575     return SDValue();
19576
19577   SDValue N0 = N->getOperand(0);
19578   SDValue N1 = N->getOperand(1);
19579   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19580   SDLoc dl(N);
19581
19582   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19583   // both SSE and AVX2 since there is no sign-extended shift right
19584   // operation on a vector with 64-bit elements.
19585   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19586   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19587   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19588       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19589     SDValue N00 = N0.getOperand(0);
19590
19591     // EXTLOAD has a better solution on AVX2,
19592     // it may be replaced with X86ISD::VSEXT node.
19593     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19594       if (!ISD::isNormalLoad(N00.getNode()))
19595         return SDValue();
19596
19597     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19598         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19599                                   N00, N1);
19600       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19601     }
19602   }
19603   return SDValue();
19604 }
19605
19606 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19607                                   TargetLowering::DAGCombinerInfo &DCI,
19608                                   const X86Subtarget *Subtarget) {
19609   if (!DCI.isBeforeLegalizeOps())
19610     return SDValue();
19611
19612   if (!Subtarget->hasFp256())
19613     return SDValue();
19614
19615   EVT VT = N->getValueType(0);
19616   if (VT.isVector() && VT.getSizeInBits() == 256) {
19617     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19618     if (R.getNode())
19619       return R;
19620   }
19621
19622   return SDValue();
19623 }
19624
19625 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19626                                  const X86Subtarget* Subtarget) {
19627   SDLoc dl(N);
19628   EVT VT = N->getValueType(0);
19629
19630   // Let legalize expand this if it isn't a legal type yet.
19631   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19632     return SDValue();
19633
19634   EVT ScalarVT = VT.getScalarType();
19635   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19636       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19637     return SDValue();
19638
19639   SDValue A = N->getOperand(0);
19640   SDValue B = N->getOperand(1);
19641   SDValue C = N->getOperand(2);
19642
19643   bool NegA = (A.getOpcode() == ISD::FNEG);
19644   bool NegB = (B.getOpcode() == ISD::FNEG);
19645   bool NegC = (C.getOpcode() == ISD::FNEG);
19646
19647   // Negative multiplication when NegA xor NegB
19648   bool NegMul = (NegA != NegB);
19649   if (NegA)
19650     A = A.getOperand(0);
19651   if (NegB)
19652     B = B.getOperand(0);
19653   if (NegC)
19654     C = C.getOperand(0);
19655
19656   unsigned Opcode;
19657   if (!NegMul)
19658     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19659   else
19660     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19661
19662   return DAG.getNode(Opcode, dl, VT, A, B, C);
19663 }
19664
19665 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19666                                   TargetLowering::DAGCombinerInfo &DCI,
19667                                   const X86Subtarget *Subtarget) {
19668   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19669   //           (and (i32 x86isd::setcc_carry), 1)
19670   // This eliminates the zext. This transformation is necessary because
19671   // ISD::SETCC is always legalized to i8.
19672   SDLoc dl(N);
19673   SDValue N0 = N->getOperand(0);
19674   EVT VT = N->getValueType(0);
19675
19676   if (N0.getOpcode() == ISD::AND &&
19677       N0.hasOneUse() &&
19678       N0.getOperand(0).hasOneUse()) {
19679     SDValue N00 = N0.getOperand(0);
19680     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19681       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19682       if (!C || C->getZExtValue() != 1)
19683         return SDValue();
19684       return DAG.getNode(ISD::AND, dl, VT,
19685                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19686                                      N00.getOperand(0), N00.getOperand(1)),
19687                          DAG.getConstant(1, VT));
19688     }
19689   }
19690
19691   if (N0.getOpcode() == ISD::TRUNCATE &&
19692       N0.hasOneUse() &&
19693       N0.getOperand(0).hasOneUse()) {
19694     SDValue N00 = N0.getOperand(0);
19695     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19696       return DAG.getNode(ISD::AND, dl, VT,
19697                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19698                                      N00.getOperand(0), N00.getOperand(1)),
19699                          DAG.getConstant(1, VT));
19700     }
19701   }
19702   if (VT.is256BitVector()) {
19703     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19704     if (R.getNode())
19705       return R;
19706   }
19707
19708   return SDValue();
19709 }
19710
19711 // Optimize x == -y --> x+y == 0
19712 //          x != -y --> x+y != 0
19713 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19714                                       const X86Subtarget* Subtarget) {
19715   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19716   SDValue LHS = N->getOperand(0);
19717   SDValue RHS = N->getOperand(1);
19718   EVT VT = N->getValueType(0);
19719   SDLoc DL(N);
19720
19721   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19723       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19724         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19725                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19726         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19727                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19728       }
19729   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19730     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19731       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19732         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19733                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19734         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19735                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19736       }
19737
19738   if (VT.getScalarType() == MVT::i1) {
19739     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19740       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19741     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19742     if (!IsSEXT0 && !IsVZero0)
19743       return SDValue();
19744     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19745       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19746     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19747
19748     if (!IsSEXT1 && !IsVZero1)
19749       return SDValue();
19750
19751     if (IsSEXT0 && IsVZero1) {
19752       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19753       if (CC == ISD::SETEQ)
19754         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19755       return LHS.getOperand(0);
19756     }
19757     if (IsSEXT1 && IsVZero0) {
19758       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19759       if (CC == ISD::SETEQ)
19760         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19761       return RHS.getOperand(0);
19762     }
19763   }
19764
19765   return SDValue();
19766 }
19767
19768 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19769 // as "sbb reg,reg", since it can be extended without zext and produces
19770 // an all-ones bit which is more useful than 0/1 in some cases.
19771 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19772                                MVT VT) {
19773   if (VT == MVT::i8)
19774     return DAG.getNode(ISD::AND, DL, VT,
19775                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19776                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19777                        DAG.getConstant(1, VT));
19778   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19779   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19780                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19781                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19782 }
19783
19784 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19785 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19786                                    TargetLowering::DAGCombinerInfo &DCI,
19787                                    const X86Subtarget *Subtarget) {
19788   SDLoc DL(N);
19789   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19790   SDValue EFLAGS = N->getOperand(1);
19791
19792   if (CC == X86::COND_A) {
19793     // Try to convert COND_A into COND_B in an attempt to facilitate
19794     // materializing "setb reg".
19795     //
19796     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19797     // cannot take an immediate as its first operand.
19798     //
19799     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19800         EFLAGS.getValueType().isInteger() &&
19801         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19802       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19803                                    EFLAGS.getNode()->getVTList(),
19804                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19805       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19806       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19807     }
19808   }
19809
19810   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19811   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19812   // cases.
19813   if (CC == X86::COND_B)
19814     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19815
19816   SDValue Flags;
19817
19818   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19819   if (Flags.getNode()) {
19820     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19821     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19822   }
19823
19824   return SDValue();
19825 }
19826
19827 // Optimize branch condition evaluation.
19828 //
19829 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19830                                     TargetLowering::DAGCombinerInfo &DCI,
19831                                     const X86Subtarget *Subtarget) {
19832   SDLoc DL(N);
19833   SDValue Chain = N->getOperand(0);
19834   SDValue Dest = N->getOperand(1);
19835   SDValue EFLAGS = N->getOperand(3);
19836   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19837
19838   SDValue Flags;
19839
19840   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19841   if (Flags.getNode()) {
19842     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19843     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19844                        Flags);
19845   }
19846
19847   return SDValue();
19848 }
19849
19850 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19851                                         const X86TargetLowering *XTLI) {
19852   SDValue Op0 = N->getOperand(0);
19853   EVT InVT = Op0->getValueType(0);
19854
19855   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19856   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19857     SDLoc dl(N);
19858     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19859     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19860     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19861   }
19862
19863   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19864   // a 32-bit target where SSE doesn't support i64->FP operations.
19865   if (Op0.getOpcode() == ISD::LOAD) {
19866     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19867     EVT VT = Ld->getValueType(0);
19868     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19869         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19870         !XTLI->getSubtarget()->is64Bit() &&
19871         VT == MVT::i64) {
19872       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19873                                           Ld->getChain(), Op0, DAG);
19874       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19875       return FILDChain;
19876     }
19877   }
19878   return SDValue();
19879 }
19880
19881 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19882 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19883                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19884   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19885   // the result is either zero or one (depending on the input carry bit).
19886   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19887   if (X86::isZeroNode(N->getOperand(0)) &&
19888       X86::isZeroNode(N->getOperand(1)) &&
19889       // We don't have a good way to replace an EFLAGS use, so only do this when
19890       // dead right now.
19891       SDValue(N, 1).use_empty()) {
19892     SDLoc DL(N);
19893     EVT VT = N->getValueType(0);
19894     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19895     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19896                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19897                                            DAG.getConstant(X86::COND_B,MVT::i8),
19898                                            N->getOperand(2)),
19899                                DAG.getConstant(1, VT));
19900     return DCI.CombineTo(N, Res1, CarryOut);
19901   }
19902
19903   return SDValue();
19904 }
19905
19906 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19907 //      (add Y, (setne X, 0)) -> sbb -1, Y
19908 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19909 //      (sub (setne X, 0), Y) -> adc -1, Y
19910 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19911   SDLoc DL(N);
19912
19913   // Look through ZExts.
19914   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19915   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19916     return SDValue();
19917
19918   SDValue SetCC = Ext.getOperand(0);
19919   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19920     return SDValue();
19921
19922   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19923   if (CC != X86::COND_E && CC != X86::COND_NE)
19924     return SDValue();
19925
19926   SDValue Cmp = SetCC.getOperand(1);
19927   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19928       !X86::isZeroNode(Cmp.getOperand(1)) ||
19929       !Cmp.getOperand(0).getValueType().isInteger())
19930     return SDValue();
19931
19932   SDValue CmpOp0 = Cmp.getOperand(0);
19933   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19934                                DAG.getConstant(1, CmpOp0.getValueType()));
19935
19936   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19937   if (CC == X86::COND_NE)
19938     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19939                        DL, OtherVal.getValueType(), OtherVal,
19940                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19941   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19942                      DL, OtherVal.getValueType(), OtherVal,
19943                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19944 }
19945
19946 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19947 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19948                                  const X86Subtarget *Subtarget) {
19949   EVT VT = N->getValueType(0);
19950   SDValue Op0 = N->getOperand(0);
19951   SDValue Op1 = N->getOperand(1);
19952
19953   // Try to synthesize horizontal adds from adds of shuffles.
19954   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19955        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19956       isHorizontalBinOp(Op0, Op1, true))
19957     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19958
19959   return OptimizeConditionalInDecrement(N, DAG);
19960 }
19961
19962 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19963                                  const X86Subtarget *Subtarget) {
19964   SDValue Op0 = N->getOperand(0);
19965   SDValue Op1 = N->getOperand(1);
19966
19967   // X86 can't encode an immediate LHS of a sub. See if we can push the
19968   // negation into a preceding instruction.
19969   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19970     // If the RHS of the sub is a XOR with one use and a constant, invert the
19971     // immediate. Then add one to the LHS of the sub so we can turn
19972     // X-Y -> X+~Y+1, saving one register.
19973     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19974         isa<ConstantSDNode>(Op1.getOperand(1))) {
19975       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19976       EVT VT = Op0.getValueType();
19977       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19978                                    Op1.getOperand(0),
19979                                    DAG.getConstant(~XorC, VT));
19980       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19981                          DAG.getConstant(C->getAPIntValue()+1, VT));
19982     }
19983   }
19984
19985   // Try to synthesize horizontal adds from adds of shuffles.
19986   EVT VT = N->getValueType(0);
19987   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19988        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19989       isHorizontalBinOp(Op0, Op1, true))
19990     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19991
19992   return OptimizeConditionalInDecrement(N, DAG);
19993 }
19994
19995 /// performVZEXTCombine - Performs build vector combines
19996 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19997                                         TargetLowering::DAGCombinerInfo &DCI,
19998                                         const X86Subtarget *Subtarget) {
19999   // (vzext (bitcast (vzext (x)) -> (vzext x)
20000   SDValue In = N->getOperand(0);
20001   while (In.getOpcode() == ISD::BITCAST)
20002     In = In.getOperand(0);
20003
20004   if (In.getOpcode() != X86ISD::VZEXT)
20005     return SDValue();
20006
20007   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20008                      In.getOperand(0));
20009 }
20010
20011 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20012                                              DAGCombinerInfo &DCI) const {
20013   SelectionDAG &DAG = DCI.DAG;
20014   switch (N->getOpcode()) {
20015   default: break;
20016   case ISD::EXTRACT_VECTOR_ELT:
20017     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20018   case ISD::VSELECT:
20019   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20020   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20021   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20022   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20023   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20024   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20025   case ISD::SHL:
20026   case ISD::SRA:
20027   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20028   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20029   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20030   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20031   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20032   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20033   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20034   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20035   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20036   case X86ISD::FXOR:
20037   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20038   case X86ISD::FMIN:
20039   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20040   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20041   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20042   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20043   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20044   case ISD::ANY_EXTEND:
20045   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20046   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20047   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20048   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20049   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20050   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20051   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20052   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20053   case X86ISD::SHUFP:       // Handle all target specific shuffles
20054   case X86ISD::PALIGNR:
20055   case X86ISD::UNPCKH:
20056   case X86ISD::UNPCKL:
20057   case X86ISD::MOVHLPS:
20058   case X86ISD::MOVLHPS:
20059   case X86ISD::PSHUFD:
20060   case X86ISD::PSHUFHW:
20061   case X86ISD::PSHUFLW:
20062   case X86ISD::MOVSS:
20063   case X86ISD::MOVSD:
20064   case X86ISD::VPERMILP:
20065   case X86ISD::VPERM2X128:
20066   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20067   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20068   }
20069
20070   return SDValue();
20071 }
20072
20073 /// isTypeDesirableForOp - Return true if the target has native support for
20074 /// the specified value type and it is 'desirable' to use the type for the
20075 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20076 /// instruction encodings are longer and some i16 instructions are slow.
20077 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20078   if (!isTypeLegal(VT))
20079     return false;
20080   if (VT != MVT::i16)
20081     return true;
20082
20083   switch (Opc) {
20084   default:
20085     return true;
20086   case ISD::LOAD:
20087   case ISD::SIGN_EXTEND:
20088   case ISD::ZERO_EXTEND:
20089   case ISD::ANY_EXTEND:
20090   case ISD::SHL:
20091   case ISD::SRL:
20092   case ISD::SUB:
20093   case ISD::ADD:
20094   case ISD::MUL:
20095   case ISD::AND:
20096   case ISD::OR:
20097   case ISD::XOR:
20098     return false;
20099   }
20100 }
20101
20102 /// IsDesirableToPromoteOp - This method query the target whether it is
20103 /// beneficial for dag combiner to promote the specified node. If true, it
20104 /// should return the desired promotion type by reference.
20105 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20106   EVT VT = Op.getValueType();
20107   if (VT != MVT::i16)
20108     return false;
20109
20110   bool Promote = false;
20111   bool Commute = false;
20112   switch (Op.getOpcode()) {
20113   default: break;
20114   case ISD::LOAD: {
20115     LoadSDNode *LD = cast<LoadSDNode>(Op);
20116     // If the non-extending load has a single use and it's not live out, then it
20117     // might be folded.
20118     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20119                                                      Op.hasOneUse()*/) {
20120       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20121              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20122         // The only case where we'd want to promote LOAD (rather then it being
20123         // promoted as an operand is when it's only use is liveout.
20124         if (UI->getOpcode() != ISD::CopyToReg)
20125           return false;
20126       }
20127     }
20128     Promote = true;
20129     break;
20130   }
20131   case ISD::SIGN_EXTEND:
20132   case ISD::ZERO_EXTEND:
20133   case ISD::ANY_EXTEND:
20134     Promote = true;
20135     break;
20136   case ISD::SHL:
20137   case ISD::SRL: {
20138     SDValue N0 = Op.getOperand(0);
20139     // Look out for (store (shl (load), x)).
20140     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20141       return false;
20142     Promote = true;
20143     break;
20144   }
20145   case ISD::ADD:
20146   case ISD::MUL:
20147   case ISD::AND:
20148   case ISD::OR:
20149   case ISD::XOR:
20150     Commute = true;
20151     // fallthrough
20152   case ISD::SUB: {
20153     SDValue N0 = Op.getOperand(0);
20154     SDValue N1 = Op.getOperand(1);
20155     if (!Commute && MayFoldLoad(N1))
20156       return false;
20157     // Avoid disabling potential load folding opportunities.
20158     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20159       return false;
20160     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20161       return false;
20162     Promote = true;
20163   }
20164   }
20165
20166   PVT = MVT::i32;
20167   return Promote;
20168 }
20169
20170 //===----------------------------------------------------------------------===//
20171 //                           X86 Inline Assembly Support
20172 //===----------------------------------------------------------------------===//
20173
20174 namespace {
20175   // Helper to match a string separated by whitespace.
20176   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20177     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20178
20179     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20180       StringRef piece(*args[i]);
20181       if (!s.startswith(piece)) // Check if the piece matches.
20182         return false;
20183
20184       s = s.substr(piece.size());
20185       StringRef::size_type pos = s.find_first_not_of(" \t");
20186       if (pos == 0) // We matched a prefix.
20187         return false;
20188
20189       s = s.substr(pos);
20190     }
20191
20192     return s.empty();
20193   }
20194   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20195 }
20196
20197 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20198
20199   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20200     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20201         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20202         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20203
20204       if (AsmPieces.size() == 3)
20205         return true;
20206       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20207         return true;
20208     }
20209   }
20210   return false;
20211 }
20212
20213 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20214   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20215
20216   std::string AsmStr = IA->getAsmString();
20217
20218   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20219   if (!Ty || Ty->getBitWidth() % 16 != 0)
20220     return false;
20221
20222   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20223   SmallVector<StringRef, 4> AsmPieces;
20224   SplitString(AsmStr, AsmPieces, ";\n");
20225
20226   switch (AsmPieces.size()) {
20227   default: return false;
20228   case 1:
20229     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20230     // we will turn this bswap into something that will be lowered to logical
20231     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20232     // lower so don't worry about this.
20233     // bswap $0
20234     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20235         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20236         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20237         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20238         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20239         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20240       // No need to check constraints, nothing other than the equivalent of
20241       // "=r,0" would be valid here.
20242       return IntrinsicLowering::LowerToByteSwap(CI);
20243     }
20244
20245     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20246     if (CI->getType()->isIntegerTy(16) &&
20247         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20248         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20249          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20250       AsmPieces.clear();
20251       const std::string &ConstraintsStr = IA->getConstraintString();
20252       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20253       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20254       if (clobbersFlagRegisters(AsmPieces))
20255         return IntrinsicLowering::LowerToByteSwap(CI);
20256     }
20257     break;
20258   case 3:
20259     if (CI->getType()->isIntegerTy(32) &&
20260         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20261         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20262         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20263         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20264       AsmPieces.clear();
20265       const std::string &ConstraintsStr = IA->getConstraintString();
20266       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20267       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20268       if (clobbersFlagRegisters(AsmPieces))
20269         return IntrinsicLowering::LowerToByteSwap(CI);
20270     }
20271
20272     if (CI->getType()->isIntegerTy(64)) {
20273       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20274       if (Constraints.size() >= 2 &&
20275           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20276           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20277         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20278         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20279             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20280             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20281           return IntrinsicLowering::LowerToByteSwap(CI);
20282       }
20283     }
20284     break;
20285   }
20286   return false;
20287 }
20288
20289 /// getConstraintType - Given a constraint letter, return the type of
20290 /// constraint it is for this target.
20291 X86TargetLowering::ConstraintType
20292 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20293   if (Constraint.size() == 1) {
20294     switch (Constraint[0]) {
20295     case 'R':
20296     case 'q':
20297     case 'Q':
20298     case 'f':
20299     case 't':
20300     case 'u':
20301     case 'y':
20302     case 'x':
20303     case 'Y':
20304     case 'l':
20305       return C_RegisterClass;
20306     case 'a':
20307     case 'b':
20308     case 'c':
20309     case 'd':
20310     case 'S':
20311     case 'D':
20312     case 'A':
20313       return C_Register;
20314     case 'I':
20315     case 'J':
20316     case 'K':
20317     case 'L':
20318     case 'M':
20319     case 'N':
20320     case 'G':
20321     case 'C':
20322     case 'e':
20323     case 'Z':
20324       return C_Other;
20325     default:
20326       break;
20327     }
20328   }
20329   return TargetLowering::getConstraintType(Constraint);
20330 }
20331
20332 /// Examine constraint type and operand type and determine a weight value.
20333 /// This object must already have been set up with the operand type
20334 /// and the current alternative constraint selected.
20335 TargetLowering::ConstraintWeight
20336   X86TargetLowering::getSingleConstraintMatchWeight(
20337     AsmOperandInfo &info, const char *constraint) const {
20338   ConstraintWeight weight = CW_Invalid;
20339   Value *CallOperandVal = info.CallOperandVal;
20340     // If we don't have a value, we can't do a match,
20341     // but allow it at the lowest weight.
20342   if (!CallOperandVal)
20343     return CW_Default;
20344   Type *type = CallOperandVal->getType();
20345   // Look at the constraint type.
20346   switch (*constraint) {
20347   default:
20348     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20349   case 'R':
20350   case 'q':
20351   case 'Q':
20352   case 'a':
20353   case 'b':
20354   case 'c':
20355   case 'd':
20356   case 'S':
20357   case 'D':
20358   case 'A':
20359     if (CallOperandVal->getType()->isIntegerTy())
20360       weight = CW_SpecificReg;
20361     break;
20362   case 'f':
20363   case 't':
20364   case 'u':
20365     if (type->isFloatingPointTy())
20366       weight = CW_SpecificReg;
20367     break;
20368   case 'y':
20369     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20370       weight = CW_SpecificReg;
20371     break;
20372   case 'x':
20373   case 'Y':
20374     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20375         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20376       weight = CW_Register;
20377     break;
20378   case 'I':
20379     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20380       if (C->getZExtValue() <= 31)
20381         weight = CW_Constant;
20382     }
20383     break;
20384   case 'J':
20385     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20386       if (C->getZExtValue() <= 63)
20387         weight = CW_Constant;
20388     }
20389     break;
20390   case 'K':
20391     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20392       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20393         weight = CW_Constant;
20394     }
20395     break;
20396   case 'L':
20397     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20398       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20399         weight = CW_Constant;
20400     }
20401     break;
20402   case 'M':
20403     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20404       if (C->getZExtValue() <= 3)
20405         weight = CW_Constant;
20406     }
20407     break;
20408   case 'N':
20409     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20410       if (C->getZExtValue() <= 0xff)
20411         weight = CW_Constant;
20412     }
20413     break;
20414   case 'G':
20415   case 'C':
20416     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20417       weight = CW_Constant;
20418     }
20419     break;
20420   case 'e':
20421     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20422       if ((C->getSExtValue() >= -0x80000000LL) &&
20423           (C->getSExtValue() <= 0x7fffffffLL))
20424         weight = CW_Constant;
20425     }
20426     break;
20427   case 'Z':
20428     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20429       if (C->getZExtValue() <= 0xffffffff)
20430         weight = CW_Constant;
20431     }
20432     break;
20433   }
20434   return weight;
20435 }
20436
20437 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20438 /// with another that has more specific requirements based on the type of the
20439 /// corresponding operand.
20440 const char *X86TargetLowering::
20441 LowerXConstraint(EVT ConstraintVT) const {
20442   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20443   // 'f' like normal targets.
20444   if (ConstraintVT.isFloatingPoint()) {
20445     if (Subtarget->hasSSE2())
20446       return "Y";
20447     if (Subtarget->hasSSE1())
20448       return "x";
20449   }
20450
20451   return TargetLowering::LowerXConstraint(ConstraintVT);
20452 }
20453
20454 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20455 /// vector.  If it is invalid, don't add anything to Ops.
20456 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20457                                                      std::string &Constraint,
20458                                                      std::vector<SDValue>&Ops,
20459                                                      SelectionDAG &DAG) const {
20460   SDValue Result;
20461
20462   // Only support length 1 constraints for now.
20463   if (Constraint.length() > 1) return;
20464
20465   char ConstraintLetter = Constraint[0];
20466   switch (ConstraintLetter) {
20467   default: break;
20468   case 'I':
20469     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20470       if (C->getZExtValue() <= 31) {
20471         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20472         break;
20473       }
20474     }
20475     return;
20476   case 'J':
20477     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20478       if (C->getZExtValue() <= 63) {
20479         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20480         break;
20481       }
20482     }
20483     return;
20484   case 'K':
20485     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20486       if (isInt<8>(C->getSExtValue())) {
20487         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20488         break;
20489       }
20490     }
20491     return;
20492   case 'N':
20493     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20494       if (C->getZExtValue() <= 255) {
20495         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20496         break;
20497       }
20498     }
20499     return;
20500   case 'e': {
20501     // 32-bit signed value
20502     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20503       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20504                                            C->getSExtValue())) {
20505         // Widen to 64 bits here to get it sign extended.
20506         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20507         break;
20508       }
20509     // FIXME gcc accepts some relocatable values here too, but only in certain
20510     // memory models; it's complicated.
20511     }
20512     return;
20513   }
20514   case 'Z': {
20515     // 32-bit unsigned value
20516     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20517       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20518                                            C->getZExtValue())) {
20519         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20520         break;
20521       }
20522     }
20523     // FIXME gcc accepts some relocatable values here too, but only in certain
20524     // memory models; it's complicated.
20525     return;
20526   }
20527   case 'i': {
20528     // Literal immediates are always ok.
20529     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20530       // Widen to 64 bits here to get it sign extended.
20531       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20532       break;
20533     }
20534
20535     // In any sort of PIC mode addresses need to be computed at runtime by
20536     // adding in a register or some sort of table lookup.  These can't
20537     // be used as immediates.
20538     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20539       return;
20540
20541     // If we are in non-pic codegen mode, we allow the address of a global (with
20542     // an optional displacement) to be used with 'i'.
20543     GlobalAddressSDNode *GA = nullptr;
20544     int64_t Offset = 0;
20545
20546     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20547     while (1) {
20548       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20549         Offset += GA->getOffset();
20550         break;
20551       } else if (Op.getOpcode() == ISD::ADD) {
20552         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20553           Offset += C->getZExtValue();
20554           Op = Op.getOperand(0);
20555           continue;
20556         }
20557       } else if (Op.getOpcode() == ISD::SUB) {
20558         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20559           Offset += -C->getZExtValue();
20560           Op = Op.getOperand(0);
20561           continue;
20562         }
20563       }
20564
20565       // Otherwise, this isn't something we can handle, reject it.
20566       return;
20567     }
20568
20569     const GlobalValue *GV = GA->getGlobal();
20570     // If we require an extra load to get this address, as in PIC mode, we
20571     // can't accept it.
20572     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20573                                                         getTargetMachine())))
20574       return;
20575
20576     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20577                                         GA->getValueType(0), Offset);
20578     break;
20579   }
20580   }
20581
20582   if (Result.getNode()) {
20583     Ops.push_back(Result);
20584     return;
20585   }
20586   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20587 }
20588
20589 std::pair<unsigned, const TargetRegisterClass*>
20590 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20591                                                 MVT VT) const {
20592   // First, see if this is a constraint that directly corresponds to an LLVM
20593   // register class.
20594   if (Constraint.size() == 1) {
20595     // GCC Constraint Letters
20596     switch (Constraint[0]) {
20597     default: break;
20598       // TODO: Slight differences here in allocation order and leaving
20599       // RIP in the class. Do they matter any more here than they do
20600       // in the normal allocation?
20601     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20602       if (Subtarget->is64Bit()) {
20603         if (VT == MVT::i32 || VT == MVT::f32)
20604           return std::make_pair(0U, &X86::GR32RegClass);
20605         if (VT == MVT::i16)
20606           return std::make_pair(0U, &X86::GR16RegClass);
20607         if (VT == MVT::i8 || VT == MVT::i1)
20608           return std::make_pair(0U, &X86::GR8RegClass);
20609         if (VT == MVT::i64 || VT == MVT::f64)
20610           return std::make_pair(0U, &X86::GR64RegClass);
20611         break;
20612       }
20613       // 32-bit fallthrough
20614     case 'Q':   // Q_REGS
20615       if (VT == MVT::i32 || VT == MVT::f32)
20616         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20617       if (VT == MVT::i16)
20618         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20619       if (VT == MVT::i8 || VT == MVT::i1)
20620         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20621       if (VT == MVT::i64)
20622         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20623       break;
20624     case 'r':   // GENERAL_REGS
20625     case 'l':   // INDEX_REGS
20626       if (VT == MVT::i8 || VT == MVT::i1)
20627         return std::make_pair(0U, &X86::GR8RegClass);
20628       if (VT == MVT::i16)
20629         return std::make_pair(0U, &X86::GR16RegClass);
20630       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20631         return std::make_pair(0U, &X86::GR32RegClass);
20632       return std::make_pair(0U, &X86::GR64RegClass);
20633     case 'R':   // LEGACY_REGS
20634       if (VT == MVT::i8 || VT == MVT::i1)
20635         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20636       if (VT == MVT::i16)
20637         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20638       if (VT == MVT::i32 || !Subtarget->is64Bit())
20639         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20640       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20641     case 'f':  // FP Stack registers.
20642       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20643       // value to the correct fpstack register class.
20644       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20645         return std::make_pair(0U, &X86::RFP32RegClass);
20646       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20647         return std::make_pair(0U, &X86::RFP64RegClass);
20648       return std::make_pair(0U, &X86::RFP80RegClass);
20649     case 'y':   // MMX_REGS if MMX allowed.
20650       if (!Subtarget->hasMMX()) break;
20651       return std::make_pair(0U, &X86::VR64RegClass);
20652     case 'Y':   // SSE_REGS if SSE2 allowed
20653       if (!Subtarget->hasSSE2()) break;
20654       // FALL THROUGH.
20655     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20656       if (!Subtarget->hasSSE1()) break;
20657
20658       switch (VT.SimpleTy) {
20659       default: break;
20660       // Scalar SSE types.
20661       case MVT::f32:
20662       case MVT::i32:
20663         return std::make_pair(0U, &X86::FR32RegClass);
20664       case MVT::f64:
20665       case MVT::i64:
20666         return std::make_pair(0U, &X86::FR64RegClass);
20667       // Vector types.
20668       case MVT::v16i8:
20669       case MVT::v8i16:
20670       case MVT::v4i32:
20671       case MVT::v2i64:
20672       case MVT::v4f32:
20673       case MVT::v2f64:
20674         return std::make_pair(0U, &X86::VR128RegClass);
20675       // AVX types.
20676       case MVT::v32i8:
20677       case MVT::v16i16:
20678       case MVT::v8i32:
20679       case MVT::v4i64:
20680       case MVT::v8f32:
20681       case MVT::v4f64:
20682         return std::make_pair(0U, &X86::VR256RegClass);
20683       case MVT::v8f64:
20684       case MVT::v16f32:
20685       case MVT::v16i32:
20686       case MVT::v8i64:
20687         return std::make_pair(0U, &X86::VR512RegClass);
20688       }
20689       break;
20690     }
20691   }
20692
20693   // Use the default implementation in TargetLowering to convert the register
20694   // constraint into a member of a register class.
20695   std::pair<unsigned, const TargetRegisterClass*> Res;
20696   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20697
20698   // Not found as a standard register?
20699   if (!Res.second) {
20700     // Map st(0) -> st(7) -> ST0
20701     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20702         tolower(Constraint[1]) == 's' &&
20703         tolower(Constraint[2]) == 't' &&
20704         Constraint[3] == '(' &&
20705         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20706         Constraint[5] == ')' &&
20707         Constraint[6] == '}') {
20708
20709       Res.first = X86::ST0+Constraint[4]-'0';
20710       Res.second = &X86::RFP80RegClass;
20711       return Res;
20712     }
20713
20714     // GCC allows "st(0)" to be called just plain "st".
20715     if (StringRef("{st}").equals_lower(Constraint)) {
20716       Res.first = X86::ST0;
20717       Res.second = &X86::RFP80RegClass;
20718       return Res;
20719     }
20720
20721     // flags -> EFLAGS
20722     if (StringRef("{flags}").equals_lower(Constraint)) {
20723       Res.first = X86::EFLAGS;
20724       Res.second = &X86::CCRRegClass;
20725       return Res;
20726     }
20727
20728     // 'A' means EAX + EDX.
20729     if (Constraint == "A") {
20730       Res.first = X86::EAX;
20731       Res.second = &X86::GR32_ADRegClass;
20732       return Res;
20733     }
20734     return Res;
20735   }
20736
20737   // Otherwise, check to see if this is a register class of the wrong value
20738   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20739   // turn into {ax},{dx}.
20740   if (Res.second->hasType(VT))
20741     return Res;   // Correct type already, nothing to do.
20742
20743   // All of the single-register GCC register classes map their values onto
20744   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20745   // really want an 8-bit or 32-bit register, map to the appropriate register
20746   // class and return the appropriate register.
20747   if (Res.second == &X86::GR16RegClass) {
20748     if (VT == MVT::i8 || VT == MVT::i1) {
20749       unsigned DestReg = 0;
20750       switch (Res.first) {
20751       default: break;
20752       case X86::AX: DestReg = X86::AL; break;
20753       case X86::DX: DestReg = X86::DL; break;
20754       case X86::CX: DestReg = X86::CL; break;
20755       case X86::BX: DestReg = X86::BL; break;
20756       }
20757       if (DestReg) {
20758         Res.first = DestReg;
20759         Res.second = &X86::GR8RegClass;
20760       }
20761     } else if (VT == MVT::i32 || VT == MVT::f32) {
20762       unsigned DestReg = 0;
20763       switch (Res.first) {
20764       default: break;
20765       case X86::AX: DestReg = X86::EAX; break;
20766       case X86::DX: DestReg = X86::EDX; break;
20767       case X86::CX: DestReg = X86::ECX; break;
20768       case X86::BX: DestReg = X86::EBX; break;
20769       case X86::SI: DestReg = X86::ESI; break;
20770       case X86::DI: DestReg = X86::EDI; break;
20771       case X86::BP: DestReg = X86::EBP; break;
20772       case X86::SP: DestReg = X86::ESP; break;
20773       }
20774       if (DestReg) {
20775         Res.first = DestReg;
20776         Res.second = &X86::GR32RegClass;
20777       }
20778     } else if (VT == MVT::i64 || VT == MVT::f64) {
20779       unsigned DestReg = 0;
20780       switch (Res.first) {
20781       default: break;
20782       case X86::AX: DestReg = X86::RAX; break;
20783       case X86::DX: DestReg = X86::RDX; break;
20784       case X86::CX: DestReg = X86::RCX; break;
20785       case X86::BX: DestReg = X86::RBX; break;
20786       case X86::SI: DestReg = X86::RSI; break;
20787       case X86::DI: DestReg = X86::RDI; break;
20788       case X86::BP: DestReg = X86::RBP; break;
20789       case X86::SP: DestReg = X86::RSP; break;
20790       }
20791       if (DestReg) {
20792         Res.first = DestReg;
20793         Res.second = &X86::GR64RegClass;
20794       }
20795     }
20796   } else if (Res.second == &X86::FR32RegClass ||
20797              Res.second == &X86::FR64RegClass ||
20798              Res.second == &X86::VR128RegClass ||
20799              Res.second == &X86::VR256RegClass ||
20800              Res.second == &X86::FR32XRegClass ||
20801              Res.second == &X86::FR64XRegClass ||
20802              Res.second == &X86::VR128XRegClass ||
20803              Res.second == &X86::VR256XRegClass ||
20804              Res.second == &X86::VR512RegClass) {
20805     // Handle references to XMM physical registers that got mapped into the
20806     // wrong class.  This can happen with constraints like {xmm0} where the
20807     // target independent register mapper will just pick the first match it can
20808     // find, ignoring the required type.
20809
20810     if (VT == MVT::f32 || VT == MVT::i32)
20811       Res.second = &X86::FR32RegClass;
20812     else if (VT == MVT::f64 || VT == MVT::i64)
20813       Res.second = &X86::FR64RegClass;
20814     else if (X86::VR128RegClass.hasType(VT))
20815       Res.second = &X86::VR128RegClass;
20816     else if (X86::VR256RegClass.hasType(VT))
20817       Res.second = &X86::VR256RegClass;
20818     else if (X86::VR512RegClass.hasType(VT))
20819       Res.second = &X86::VR512RegClass;
20820   }
20821
20822   return Res;
20823 }
20824
20825 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20826                                             Type *Ty) const {
20827   // Scaling factors are not free at all.
20828   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20829   // will take 2 allocations instead of 1 for plain addressing mode,
20830   // i.e. inst (reg1).
20831   if (isLegalAddressingMode(AM, Ty))
20832     // Scale represents reg2 * scale, thus account for 1
20833     // as soon as we use a second register.
20834     return AM.Scale != 0;
20835   return -1;
20836 }